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
charliermarsh__ruff
crates/ty_python_semantic/resources/corpus/95_annotation_class.py
{ "start": 0, "end": 27 }
class ____(): z: int = 5
F
python
pypa__warehouse
warehouse/admin/services.py
{ "start": 1755, "end": 2917 }
class ____(GenericSponsorLogoStorage): @classmethod @google.api_core.retry.Retry( predicate=google.api_core.retry.if_exception_type( google.api_core.exceptions.ServiceUnavailable ) ) def create_service(cls, context, request): storage_client = request.find_service(name="gcloud.gcs") bucket_name = request.registry.settings["sponsorlogos.bucket"] bucket = storage_client.get_bucket(bucket_name) prefix = request.registry.settings.get("sponsorlogos.prefix") return cls(bucket, prefix=prefix) @google.api_core.retry.Retry( predicate=google.api_core.retry.if_exception_type( google.api_core.exceptions.ServiceUnavailable ) ) def store(self, path, file_path, content_type=None, *, meta=None): if self.prefix is not None: path = os.path.join(self.prefix, path) blob = self.bucket.blob(path) blob.content_type = content_type if meta is not None: blob.metadata = meta blob.upload_from_filename(file_path) blob.make_public() return blob.public_url
GCSSponsorLogoStorage
python
ansible__ansible
test/lib/ansible_test/_internal/provider/layout/__init__.py
{ "start": 5140, "end": 5398 }
class ____: """Messages generated during layout creation that should be deferred for later display.""" def __init__(self) -> None: self.info: list[str] = [] self.warning: list[str] = [] self.error: list[str] = []
LayoutMessages
python
pytorch__pytorch
torch/ao/nn/intrinsic/modules/fused.py
{ "start": 8586, "end": 9061 }
class ____(_FusedModule): r"""This is a sequential container which calls the Linear and LeakyReLU modules. During quantization this will be replaced with the corresponding fused module.""" def __init__(self, linear, leaky_relu): assert type(linear) is Linear and type(leaky_relu) is torch.nn.LeakyReLU, ( f"Incorrect types for input modules{type(linear)}{type(leaky_relu)}" ) super().__init__(linear, leaky_relu)
LinearLeakyReLU
python
airbytehq__airbyte
airbyte-integrations/connectors/source-monday/unit_tests/integrations/config.py
{ "start": 95, "end": 1228 }
class ____: def __init__(self) -> None: self._credentials: Dict[str, str] = {} self._board_ids: List[int] = [] def with_oauth_credentials(self, client_id: str, client_secret: str, access_token: str, subdomain: str) -> "ConfigBuilder": self._credentials["auth_type"] = "oauth2.0" self._credentials["client_id"] = client_id self._credentials["client_secret"] = client_secret self._credentials["access_token"] = access_token self._credentials["subdomain"] = subdomain return self def with_api_token_credentials(self, api_token: str) -> "ConfigBuilder": self._credentials["api_token"] = api_token self._credentials["auth_type"] = "api_token" return self def with_board_ids(self, board_ids: List[int]) -> "ConfigBuilder": self._board_ids = board_ids return self def build(self) -> Dict[str, Any]: config = {} if self._credentials: config["credentials"] = self._credentials if self._board_ids: config["board_ids"] = self._board_ids return config
ConfigBuilder
python
PyCQA__pylint
pylint/config/callback_actions.py
{ "start": 3828, "end": 4220 }
class ____(_AccessRunObjectAction): """Display all available messages.""" def __call__( self, parser: argparse.ArgumentParser, namespace: argparse.Namespace, values: str | Sequence[Any] | None, option_string: str | None = "--list-enabled", ) -> None: self.run.linter.msgs_store.list_messages() sys.exit(0)
_ListMessagesAction
python
faif__python-patterns
patterns/behavioral/specification.py
{ "start": 207, "end": 536 }
class ____: def and_specification(self, candidate): raise NotImplementedError() def or_specification(self, candidate): raise NotImplementedError() def not_specification(self): raise NotImplementedError() @abstractmethod def is_satisfied_by(self, candidate): pass
Specification
python
neetcode-gh__leetcode
python/1475-final-prices-with-a-special-discount-in-a-shop.py
{ "start": 0, "end": 715 }
class ____: def finalPrices(self, prices: List[int]) -> List[int]: stack = [] res = [] for i in range(len(prices) - 1, -1, -1): if len(stack) == 0: res.append(prices[i]) elif len(stack) and stack[-1] <= prices[i]: res.append(prices[i] - stack[-1]) elif len(stack) and stack[-1] > prices[i]: while len(stack) and stack[-1] > prices[i]: stack.pop() if len(stack) == 0: res.append(prices[i]) else: res.append(prices[i] - stack[-1]) stack.append(prices[i]) res.reverse() return res
Solution
python
huggingface__transformers
src/transformers/models/auto/modeling_auto.py
{ "start": 85744, "end": 85961 }
class ____(_BaseAutoModelClass): _model_mapping = MODEL_FOR_MULTIPLE_CHOICE_MAPPING AutoModelForMultipleChoice = auto_class_update(AutoModelForMultipleChoice, head_doc="multiple choice")
AutoModelForMultipleChoice
python
walkccc__LeetCode
solutions/1561. Maximum Number of Coins You Can Get/1561.py
{ "start": 0, "end": 113 }
class ____: def maxCoins(self, piles: list[int]) -> int: return sum(sorted(piles)[len(piles) // 3::2])
Solution
python
huggingface__transformers
src/transformers/models/olmoe/modeling_olmoe.py
{ "start": 27085, "end": 31616 }
class ____(OlmoePreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config): super().__init__(config) self.model = OlmoeModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.router_aux_loss_coef = config.router_aux_loss_coef self.num_experts = config.num_experts self.num_experts_per_tok = config.num_experts_per_tok # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring 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_router_logits: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> MoeCausalLMOutputWithPast: 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]`. Example: ```python >>> from transformers import AutoTokenizer, OlmoeForCausalLM >>> model = OlmoeForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0924") >>> tokenizer = AutoTokenizer.from_pretrained("allenai/OLMoE-1B-7B-0924") >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] 'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m' ``` """ output_router_logits = ( output_router_logits if output_router_logits is not None else self.config.output_router_logits ) # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs: MoeModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_router_logits=output_router_logits, cache_position=cache_position, **kwargs, ) hidden_states = outputs.last_hidden_state # 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, labels, self.vocab_size, **kwargs) aux_loss = None if output_router_logits: aux_loss = load_balancing_loss_func( outputs.router_logits, self.num_experts, self.num_experts_per_tok, attention_mask, ) if labels is not None: loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device return MoeCausalLMOutputWithPast( loss=loss, aux_loss=aux_loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, router_logits=outputs.router_logits, ) __all__ = ["OlmoeForCausalLM", "OlmoeModel", "OlmoePreTrainedModel"]
OlmoeForCausalLM
python
kamyu104__LeetCode-Solutions
Python/stickers-to-spell-word.py
{ "start": 62, "end": 1279 }
class ____(object): def minStickers(self, stickers, target): """ :type stickers: List[str] :type target: str :rtype: int """ def minStickersHelper(sticker_counts, target, dp): if "".join(target) in dp: return dp["".join(target)] target_count = collections.Counter(target) result = float("inf") for sticker_count in sticker_counts: if sticker_count[target[0]] == 0: continue new_target = [] for k in target_count.keys(): if target_count[k] > sticker_count[k]: new_target += [k]*(target_count[k] - sticker_count[k]) if len(new_target) != len(target): num = minStickersHelper(sticker_counts, new_target, dp) if num != -1: result = min(result, 1+num) dp["".join(target)] = -1 if result == float("inf") else result return dp["".join(target)] sticker_counts = map(collections.Counter, stickers) dp = { "":0 } return minStickersHelper(sticker_counts, target, dp)
Solution
python
ansible__ansible
lib/ansible/plugins/connection/paramiko_ssh.py
{ "start": 9535, "end": 11381 }
class ____(MissingHostKeyPolicy): """ Based on AutoAddPolicy in paramiko so we can determine when keys are added and also prompt for input. Policy for automatically adding the hostname and new host key to the local L{HostKeys} object, and saving it. This is used by L{SSHClient}. """ def __init__(self, connection: Connection) -> None: self.connection = connection self._options = connection._options def missing_host_key(self, client, hostname, key) -> None: if all((self.connection.get_option('host_key_checking'), not self.connection.get_option('host_key_auto_add'))): fingerprint = hexlify(key.get_fingerprint()) ktype = key.get_name() if self.connection.get_option('use_persistent_connections') or self.connection.force_persistence: # don't print the prompt string since the user cannot respond # to the question anyway raise AnsibleError(AUTHENTICITY_MSG[1:92] % (hostname, ktype, fingerprint)) inp = to_text( display.prompt_until(AUTHENTICITY_MSG % (hostname, ktype, fingerprint), private=False), errors='surrogate_or_strict' ) if inp not in ['yes', 'y', '']: raise AnsibleError("host connection rejected by user") key._added_by_ansible_this_time = True # existing implementation below: client._host_keys.add(hostname, key.get_name(), key) # host keys are actually saved in close() function below # in order to control ordering. # keep connection objects on a per host basis to avoid repeated attempts to reconnect SSH_CONNECTION_CACHE: dict[str, paramiko.client.SSHClient] = {} SFTP_CONNECTION_CACHE: dict[str, paramiko.sftp_client.SFTPClient] = {}
MyAddPolicy
python
euske__pdfminer
pdfminer/converter.py
{ "start": 4912, "end": 6423 }
class ____(PDFConverter): def __init__(self, rsrcmgr, outfp, pageno=1, laparams=None, showpageno=False, imagewriter=None): PDFConverter.__init__(self, rsrcmgr, outfp, pageno=pageno, laparams=laparams) self.showpageno = showpageno self.imagewriter = imagewriter return def write_text(self, text): self.outfp.write(text) return def receive_layout(self, ltpage): def render(item): if isinstance(item, LTContainer): for child in item: render(child) elif isinstance(item, LTText): self.write_text(item.get_text()) if isinstance(item, LTTextBox): self.write_text('\n') elif isinstance(item, LTImage): if self.imagewriter is not None: self.imagewriter.export_image(item) if self.showpageno: self.write_text('Page %s\n' % ltpage.pageid) render(ltpage) self.write_text('\f') return # Some dummy functions to save memory/CPU when all that is wanted # is text. This stops all the image and drawing output from being # recorded and taking up RAM. def render_image(self, name, stream): if self.imagewriter is None: return PDFConverter.render_image(self, name, stream) return def paint_path(self, gstate, stroke, fill, evenodd, path): return ## HTMLConverter ##
TextConverter
python
getsentry__sentry
tests/sentry/integrations/bitbucket/test_search.py
{ "start": 455, "end": 5531 }
class ____(APITestCase): def setUp(self) -> None: self.base_url = "https://api.bitbucket.org" self.shared_secret = "234567890" self.subject = "connect:1234567" self.integration, _ = self.create_provider_integration_for( self.organization, self.user, provider="bitbucket", external_id=self.subject, name="meredithanya", metadata={ "base_url": self.base_url, "shared_secret": self.shared_secret, "subject": self.subject, }, ) self.login_as(self.user) self.path = reverse( "sentry-extensions-bitbucket-search", args=[self.organization.slug, self.integration.id] ) @responses.activate @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_search_issues(self, mock_record: MagicMock) -> None: responses.add( responses.GET, "https://api.bitbucket.org/2.0/repositories/meredithanya/apples/issues", json={ "values": [ {"id": "123", "title": "Issue Title 123"}, {"id": "456", "title": "Issue Title 456"}, ] }, ) resp = self.client.get( self.path, data={"field": "externalIssue", "query": "issue", "repo": "meredithanya/apples"}, ) assert resp.status_code == 200 assert resp.data == [ {"label": "#123 Issue Title 123", "value": "123"}, {"label": "#456 Issue Title 456", "value": "456"}, ] assert len(mock_record.mock_calls) == 8 # first 2 are middleware calls to ensure control silo, then the next one and the last one are also middleware calls for get_response_from_control_silo middleware_calls = mock_record.mock_calls[:3] + mock_record.mock_calls[-1:] assert_middleware_metrics(middleware_calls) product_calls = mock_record.mock_calls[3:-1] start1, start2, halt1, halt2 = product_calls assert start1.args[0] == EventLifecycleOutcome.STARTED assert start2.args[0] == EventLifecycleOutcome.STARTED assert halt1.args[0] == EventLifecycleOutcome.SUCCESS assert halt2.args[0] == EventLifecycleOutcome.SUCCESS @responses.activate @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_search_repositories(self, mock_record: MagicMock) -> None: responses.add( responses.GET, "https://api.bitbucket.org/2.0/repositories/meredithanya", json={"values": [{"full_name": "meredithanya/apples"}]}, ) resp = self.client.get(self.path, data={"field": "repo", "query": "apple"}) assert resp.status_code == 200 assert resp.data == [{"label": "meredithanya/apples", "value": "meredithanya/apples"}] middleware_calls = mock_record.mock_calls[:3] + mock_record.mock_calls[-1:] assert_middleware_metrics(middleware_calls) product_calls = mock_record.mock_calls[3:-1] start1, start2, halt1, halt2 = ( product_calls # calls get, which calls handle_search_repositories ) assert start1.args[0] == EventLifecycleOutcome.STARTED assert start2.args[0] == EventLifecycleOutcome.STARTED assert halt1.args[0] == EventLifecycleOutcome.SUCCESS assert halt2.args[0] == EventLifecycleOutcome.SUCCESS @responses.activate @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_search_repositories_no_issue_tracker(self, mock_record: MagicMock) -> None: responses.add( responses.GET, "https://api.bitbucket.org/2.0/repositories/meredithanya/apples/issues", json={"type": "error", "error": {"message": "Repository has no issue tracker."}}, status=404, ) resp = self.client.get( self.path, data={"field": "externalIssue", "query": "issue", "repo": "meredithanya/apples"}, ) assert resp.status_code == 400 assert resp.data == {"detail": "Bitbucket Repository has no issue tracker."} middleware_calls = mock_record.mock_calls[:3] + mock_record.mock_calls[-1:] assert_middleware_metrics(middleware_calls) product_calls = mock_record.mock_calls[3:-1] start1, start2, halt1, halt2 = product_calls # calls get, which calls handle_search_issues assert start1.args[0] == EventLifecycleOutcome.STARTED assert start2.args[0] == EventLifecycleOutcome.STARTED assert halt1.args[0] == EventLifecycleOutcome.HALTED assert_halt_metric(mock_record, SourceCodeSearchEndpointHaltReason.NO_ISSUE_TRACKER.value) # NOTE: handle_search_issues returns without raising an API error, so for the # purposes of logging the GET request completes successfully assert halt2.args[0] == EventLifecycleOutcome.SUCCESS
BitbucketSearchEndpointTest
python
keon__algorithms
tests/test_heap.py
{ "start": 122, "end": 1202 }
class ____(unittest.TestCase): """ Test suite for the binary_heap data structures """ def setUp(self): self.min_heap = BinaryHeap() self.min_heap.insert(4) self.min_heap.insert(50) self.min_heap.insert(7) self.min_heap.insert(55) self.min_heap.insert(90) self.min_heap.insert(87) def test_insert(self): # Before insert 2: [0, 4, 50, 7, 55, 90, 87] # After insert: [0, 2, 50, 4, 55, 90, 87, 7] self.min_heap.insert(2) self.assertEqual([0, 2, 50, 4, 55, 90, 87, 7], self.min_heap.heap) self.assertEqual(7, self.min_heap.current_size) def test_remove_min(self): ret = self.min_heap.remove_min() # Before remove_min : [0, 4, 50, 7, 55, 90, 87] # After remove_min: [7, 50, 87, 55, 90] # Test return value self.assertEqual(4, ret) self.assertEqual([0, 7, 50, 87, 55, 90], self.min_heap.heap) self.assertEqual(5, self.min_heap.current_size)
TestBinaryHeap
python
kamyu104__LeetCode-Solutions
Python/best-team-with-no-conflicts.py
{ "start": 5615, "end": 6162 }
class ____(object): def bestTeamScore(self, scores, ages): """ :type scores: List[int] :type ages: List[int] :rtype: int """ players = sorted(zip(ages, scores)) dp = [0]*len(players) result = 0 for i in xrange(len(players)): dp[i] = players[i][1] for j in xrange(i): if players[j][1] <= players[i][1]: dp[i] = max(dp[i], dp[j] + players[i][1]) result = max(result, dp[i]) return result
Solution6
python
wandb__wandb
wandb/vendor/pygments/lexers/shell.py
{ "start": 24119, "end": 24413 }
class ____(ShellSessionBaseLexer): """ Lexer for Tcsh sessions. .. versionadded:: 2.1 """ name = 'Tcsh Session' aliases = ['tcshcon'] filenames = [] mimetypes = [] _innerLexerCls = TcshLexer _ps1rgx = r'^([^>]+>)(.*\n?)' _ps2 = '? '
TcshSessionLexer
python
huggingface__transformers
src/transformers/models/swin/modeling_swin.py
{ "start": 2487, "end": 3639 }
class ____(ModelOutput): r""" pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed): Average pooling of the last layer hidden-state. reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of shape `(batch_size, hidden_size, height, width)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to include the spatial dimensions. """ last_hidden_state: Optional[torch.FloatTensor] = None pooler_output: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass @auto_docstring( custom_intro=""" Swin masked image model outputs. """ )
SwinModelOutput
python
PyCQA__pylint
pylint/extensions/redefined_variable_type.py
{ "start": 508, "end": 4105 }
class ____(BaseChecker): """Checks for variable type redefinition (NoneType excepted). At a function, method, class or module scope This rule could be improved: - Currently, if an attribute is set to different types in 2 methods of a same class, it won't be detected (see functional test) - One could improve the support for inference on assignment with tuples, ifexpr, etc. Also, it would be great to have support for inference on str.split() """ name = "multiple_types" msgs = { "R0204": ( "Redefinition of %s type from %s to %s", "redefined-variable-type", "Used when the type of a variable changes inside a " "method or a function.", ) } def visit_classdef(self, _: nodes.ClassDef) -> None: self._assigns.append({}) @only_required_for_messages("redefined-variable-type") def leave_classdef(self, _: nodes.ClassDef) -> None: self._check_and_add_messages() visit_functiondef = visit_asyncfunctiondef = visit_classdef leave_functiondef = leave_asyncfunctiondef = leave_module = leave_classdef def visit_module(self, _: nodes.Module) -> None: self._assigns: list[dict[str, list[tuple[nodes.Assign, str]]]] = [{}] def _check_and_add_messages(self) -> None: assigns = self._assigns.pop() for name, args in assigns.items(): if len(args) <= 1: continue orig_node, orig_type = args[0] # Check if there is a type in the following nodes that would be # different from orig_type. for redef_node, redef_type in args[1:]: if redef_type == orig_type: continue # if a variable is defined to several types in an if node, # this is not actually redefining. orig_parent = orig_node.parent redef_parent = redef_node.parent if isinstance(orig_parent, nodes.If): if orig_parent == redef_parent: if ( redef_node in orig_parent.orelse and orig_node not in orig_parent.orelse ): orig_node, orig_type = redef_node, redef_type continue elif isinstance( redef_parent, nodes.If ) and redef_parent in orig_parent.nodes_of_class(nodes.If): orig_node, orig_type = redef_node, redef_type continue orig_type = orig_type.replace("builtins.", "") redef_type = redef_type.replace("builtins.", "") self.add_message( "redefined-variable-type", node=redef_node, args=(name, orig_type, redef_type), ) break def visit_assign(self, node: nodes.Assign) -> None: # we don't handle multiple assignment nor slice assignment target = node.targets[0] if isinstance(target, (nodes.Tuple, nodes.Subscript)): return # ignore NoneType if is_none(node): return _type = node_type(node.value) if _type: self._assigns[-1].setdefault(target.as_string(), []).append( (node, _type.pytype()) ) def register(linter: PyLinter) -> None: linter.register_checker(MultipleTypesChecker(linter))
MultipleTypesChecker
python
huggingface__transformers
tests/models/wav2vec2_bert/test_modeling_wav2vec2_bert.py
{ "start": 31628, "end": 34676 }
class ____(unittest.TestCase): def _load_datasamples(self, num_samples): ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") # automatic decoding with librispeech speech_samples = ds.sort("id").filter(lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)]) speech_samples = speech_samples[:num_samples]["audio"] return [x["array"] for x in speech_samples] def test_inference_w2v2_bert(self): model = Wav2Vec2BertModel.from_pretrained("facebook/w2v-bert-2.0") model.to(torch_device) feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/w2v-bert-2.0") input_speech = self._load_datasamples(2) inputs = feature_extractor(input_speech, return_tensors="pt", padding=True).to(torch_device) model.eval() with torch.no_grad(): outputs = model(**inputs, output_attentions=True) # fmt: off expected_slice_0 = torch.tensor( [[-0.0098, -0.0570, -0.1286, 0.0439, -0.1037, -0.0235], [-0.0767, 0.0574, -0.3224, 0.0482, 0.0440, -0.0193], [ 0.0220, -0.0878, -0.2027, -0.0028, -0.0666, 0.0721], [ 0.0307, -0.1099, 0.0273, -0.0416, -0.0715, 0.0094], [ 0.0758, -0.0291, 0.1084, 0.0004, -0.0751, -0.0116], [ 0.0349, -0.0343, -0.0098, 0.0415, -0.0617, 0.0241], [-0.0193, -0.0171, 0.1965, 0.0797, -0.0308, 0.2033], [-0.0323, -0.0315, 0.0948, 0.0944, -0.0254, 0.1241], [-0.0493, 0.0010, -0.1762, 0.0034, -0.0787, 0.0832], [ 0.0043, -0.1228, -0.0739, 0.0266, -0.0337, -0.0068]] ).to(torch_device) # fmt: on # fmt: off expected_slice_1 = torch.tensor( [[-0.0348, -0.0521, -0.3036, 0.0285, -0.0715, -0.0453], [-0.0102, 0.0114, -0.3266, 0.0027, -0.0558, 0.0038], [ 0.0454, 0.0148, -0.2418, -0.0392, -0.0455, 0.0478], [-0.0013, 0.0825, -0.1730, -0.0091, -0.0426, 0.0360], [-0.0227, 0.0687, -0.1168, 0.0569, -0.0160, 0.0759], [-0.0318, 0.0562, -0.0508, 0.0605, 0.0150, 0.0953], [-0.0415, 0.0438, 0.0233, 0.0336, 0.0262, 0.0860], [-0.0163, 0.0048, 0.0807, 0.0119, 0.0712, 0.0158], [ 0.0244, -0.0145, 0.0262, -0.0237, 0.0283, -0.0125], [-0.0587, -0.0516, -0.0368, -0.0196, 0.0307, -0.1434]] ).to(torch_device) # fmt: on self.assertTrue((outputs.last_hidden_state[0, 25:35, 4:10] - expected_slice_0).abs().max() <= 1e-4) self.assertTrue((outputs.last_hidden_state[1, 25:35, 4:10] - expected_slice_1).abs().max() <= 1e-4) self.assertAlmostEqual(outputs.last_hidden_state[1].mean().item(), 3.3123e-05) self.assertAlmostEqual(outputs.last_hidden_state[1].std().item(), 0.1545, delta=2e-5) self.assertListEqual(list(outputs.last_hidden_state.shape), [2, 326, 1024])
Wav2Vec2BertModelIntegrationTest
python
Lightning-AI__lightning
src/lightning/fabric/plugins/io/torch_io.py
{ "start": 987, "end": 4214 }
class ____(CheckpointIO): """CheckpointIO that utilizes :func:`torch.save` and :func:`torch.load` to save and load checkpoints respectively, common for most use cases. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. """ @override def save_checkpoint(self, checkpoint: dict[str, Any], path: _PATH, storage_options: Optional[Any] = None) -> None: """Save model/training states as a checkpoint file through state-dump and file-write. Args: checkpoint: dict containing model and trainer state path: write-target path storage_options: not used in ``TorchCheckpointIO.save_checkpoint`` Raises: TypeError: If ``storage_options`` arg is passed in """ if storage_options is not None: raise TypeError( "`Trainer.save_checkpoint(..., storage_options=...)` with `storage_options` arg" f" is not supported for `{self.__class__.__name__}`. Please implement your custom `CheckpointIO`" " to define how you'd like to use `storage_options`." ) fs = get_filesystem(path) fs.makedirs(os.path.dirname(path), exist_ok=True) _atomic_save(checkpoint, path) @override def load_checkpoint( self, path: _PATH, map_location: Optional[Callable] = lambda storage, loc: storage, weights_only: Optional[bool] = None, ) -> dict[str, Any]: """Loads checkpoint using :func:`torch.load`, with additional handling for ``fsspec`` remote loading of files. Args: path: Path to checkpoint map_location: a function, :class:`torch.device`, string or a dict specifying how to remap storage locations. weights_only: Defaults to ``None``. If ``True``, restricts loading to ``state_dicts`` of plain ``torch.Tensor`` and other primitive types. If loading a checkpoint from a trusted source that contains an ``nn.Module``, use ``weights_only=False``. If loading checkpoint from an untrusted source, we recommend using ``weights_only=True``. For more information, please refer to the `PyTorch Developer Notes on Serialization Semantics <https://docs.pytorch.org/docs/main/notes/serialization.html#id3>`_. Returns: The loaded checkpoint. Raises: FileNotFoundError: If ``path`` is not found by the ``fsspec`` filesystem """ # Try to read the checkpoint at `path`. If not exist, do not restore checkpoint. fs = get_filesystem(path) if not fs.exists(path): raise FileNotFoundError(f"Checkpoint file not found: {path}") return pl_load(path, map_location=map_location, weights_only=weights_only) @override def remove_checkpoint(self, path: _PATH) -> None: """Remove checkpoint file from the filesystem. Args: path: Path to checkpoint """ fs = get_filesystem(path) if fs.exists(path): fs.rm(path, recursive=True) log.debug(f"Removed checkpoint: {path}")
TorchCheckpointIO
python
keras-team__keras
keras/src/backend/torch/optimizers/torch_adamw.py
{ "start": 93, "end": 150 }
class ____(torch_adam.Adam, optimizers.AdamW): pass
AdamW
python
crytic__slither
slither/utils/colors.py
{ "start": 59, "end": 3329 }
class ____: # pylint: disable=too-few-public-methods COLORIZATION_ENABLED = True RED = "\033[91m" GREEN = "\033[92m" YELLOW = "\033[93m" BLUE = "\033[94m" MAGENTA = "\033[95m" BOLD = "\033[1m" END = "\033[0m" def colorize(color: Colors, txt: str) -> str: if Colors.COLORIZATION_ENABLED: return f"{color}{txt}{Colors.END}" return txt def enable_windows_virtual_terminal_sequences() -> bool: """ Sets the appropriate flags to enable virtual terminal sequences in a Windows command prompt. Reference: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences """ try: # pylint: disable=import-outside-toplevel from ctypes import windll, byref # type: ignore from ctypes.wintypes import DWORD, HANDLE kernel32 = windll.kernel32 virtual_terminal_flag = 0x04 # ENABLE_VIRTUAL_TERMINAL_PROCESSING # Obtain our stdout/stderr handles. # Reference: https://docs.microsoft.com/en-us/windows/console/getstdhandle handle_stdout = kernel32.GetStdHandle(-11) handle_stderr = kernel32.GetStdHandle(-12) # Loop for each stdout/stderr handle. for current_handle in [handle_stdout, handle_stderr]: # If we get a null handle, or fail any subsequent calls in this scope, we do not colorize any output. if current_handle is None or current_handle == HANDLE(-1): return False # Try to obtain the current flags for the console. current_mode = DWORD() if not kernel32.GetConsoleMode(current_handle, byref(current_mode)): return False # If the virtual terminal sequence processing is not yet enabled, we enable it. if (current_mode.value & virtual_terminal_flag) == 0: if not kernel32.SetConsoleMode( current_handle, current_mode.value | virtual_terminal_flag ): return False except Exception: # pylint: disable=broad-except # Any generic failure (possibly from calling these methods on older Windows builds where they do not exist) # will fall back onto disabling colorization. return False return True def set_colorization_enabled(enabled: bool) -> None: """ Sets the enabled state of output colorization. :param enabled: Boolean indicating whether output should be colorized. :return: None """ # If color is supposed to be enabled and this is windows, we have to enable console virtual terminal sequences: if enabled and platform.system() == "Windows": Colors.COLORIZATION_ENABLED = enable_windows_virtual_terminal_sequences() else: # This is not windows, or colorization is being disabled, so we can adjust the state immediately. Colors.COLORIZATION_ENABLED = enabled green = partial(colorize, Colors.GREEN) yellow = partial(colorize, Colors.YELLOW) red = partial(colorize, Colors.RED) blue = partial(colorize, Colors.BLUE) magenta = partial(colorize, Colors.MAGENTA) bold = partial(colorize, Colors.BOLD) # We enable colorization by default if the output is a tty set_colorization_enabled(sys.stdout.isatty())
Colors
python
davidhalter__jedi
test/completion/classes.py
{ "start": 8636, "end": 8755 }
class ____(object): a = 3 #? ['mro'] A.mro #? [] A().mro # ----------------- # mro resolution # -----------------
A
python
getsentry__sentry
tests/sentry/eventstream/test_eventstream.py
{ "start": 954, "end": 21899 }
class ____(TestCase, SnubaTestCase, OccurrenceTestMixin): @pytest.fixture(autouse=True) def patch_get_producer(self): self.kafka_eventstream = KafkaEventStream() self.producer_mock = Mock() with patch.object(KafkaEventStream, "get_producer", return_value=self.producer_mock): yield def __build_event(self, timestamp): raw_event = { "event_id": "a" * 32, "message": "foo", "timestamp": time.mktime(timestamp.timetuple()), "level": logging.ERROR, "logger": "default", "tags": [], } manager = EventManager(raw_event) manager.normalize() return manager.save(self.project.id) def __build_transaction_event(self): manager = EventManager(load_data("transaction")) manager.normalize() return manager.save(self.project.id) def __produce_event(self, *insert_args, **insert_kwargs): event_type = self.kafka_eventstream._get_event_type(insert_kwargs["event"]) # pass arguments on to Kafka EventManager self.kafka_eventstream.insert(*insert_args, **insert_kwargs) producer = self.producer_mock produce_args, produce_kwargs = list(producer.produce.call_args) assert not produce_args if event_type == EventStreamEventType.Transaction: assert produce_kwargs["topic"] == "transactions" assert produce_kwargs["key"] is None elif event_type == EventStreamEventType.Generic: assert produce_kwargs["topic"] == "generic-events" assert produce_kwargs["key"] is None else: assert produce_kwargs["topic"] == "events" assert produce_kwargs["key"] == str(self.project.id).encode("utf-8") version, type_, payload1, payload2 = json.loads(produce_kwargs["value"]) assert version == 2 assert type_ == "insert" # insert what would have been the Kafka payload directly # into Snuba, expect an HTTP 200 and for the event to now exist snuba_eventstream = SnubaEventStream() snuba_eventstream._send( self.project.id, "insert", (payload1, payload2), event_type=event_type, ) def __produce_payload(self, *insert_args, **insert_kwargs): # pass arguments on to Kafka EventManager self.kafka_eventstream.insert(*insert_args, **insert_kwargs) producer = self.producer_mock produce_args, produce_kwargs = list(producer.produce.call_args) assert not produce_args version, type_, payload1, payload2 = json.loads(produce_kwargs["value"]) # only return headers and body payload return produce_kwargs["headers"], payload2 def test_init_options(self): # options in the constructor shouldn't cause errors stream = KafkaEventStream(foo="bar") assert stream @patch("sentry.eventstream.backend.insert", autospec=True) def test(self, mock_eventstream_insert: MagicMock) -> None: now = timezone.now() event = self.__build_event(now) # verify eventstream was called by EventManager insert_args, insert_kwargs = list(mock_eventstream_insert.call_args) assert not insert_args group_state = { "is_new_group_environment": True, "is_new": True, "is_regression": False, } assert insert_kwargs == { "event": event, **group_state, "primary_hash": "acbd18db4cc2f85cedef654fccc4a4d8", "skip_consume": False, "received_timestamp": event.data["received"], "group_states": [{"id": event.groups[0].id, **group_state}], } self.__produce_event(*insert_args, **insert_kwargs) assert ( snuba.query( start=now - timedelta(days=1), end=now + timedelta(days=1), groupby=["project_id"], filter_keys={"project_id": [self.project.id]}, tenant_ids={"organization_id": 1, "referrer": "r"}, ).get(self.project.id, 0) == 1 ) @patch("sentry.eventstream.backend.insert", autospec=True) def test_issueless(self, mock_eventstream_insert: MagicMock) -> None: now = timezone.now() event = self.__build_transaction_event() event.group_id = None insert_args = () insert_kwargs = { "event": event, "is_new_group_environment": True, "is_new": True, "is_regression": False, "primary_hash": "acbd18db4cc2f85cedef654fccc4a4d8", "skip_consume": False, "received_timestamp": event.data["received"], } self.__produce_event(*insert_args, **insert_kwargs) result = snuba.raw_query( dataset=Dataset.Transactions, start=now - timedelta(days=1), end=now + timedelta(days=1), selected_columns=["event_id"], groupby=None, filter_keys={"project_id": [self.project.id], "event_id": [event.event_id]}, tenant_ids={"organization_id": 1, "referrer": "r"}, ) assert len(result["data"]) == 1 @patch("sentry.eventstream.backend.insert", autospec=True) def test_multiple_groups(self, mock_eventstream_insert: MagicMock) -> None: now = timezone.now() event = self.__build_transaction_event() event.group_id = None event.groups = [self.group] insert_args = () group_state = { "is_new_group_environment": True, "is_new": True, "is_regression": False, } insert_kwargs = { "event": event, **group_state, "primary_hash": "acbd18db4cc2f85cedef654fccc4a4d8", "skip_consume": False, "received_timestamp": event.data["received"], "group_states": [{"id": event.groups[0].id, **group_state}], } self.__produce_event(*insert_args, **insert_kwargs) result = snuba.raw_query( dataset=Dataset.Transactions, start=now - timedelta(days=1), end=now + timedelta(days=1), selected_columns=["event_id", "group_ids"], groupby=None, filter_keys={"project_id": [self.project.id], "event_id": [event.event_id]}, tenant_ids={"organization_id": 1, "referrer": "r"}, ) assert len(result["data"]) == 1 assert result["data"][0]["group_ids"] == [self.group.id] @patch("sentry.eventstream.snuba.logger") def test_invalid_groupevent_passed(self, logger: MagicMock) -> None: event = self.__build_transaction_event() event.group_id = None event.group_ids = [self.group.id] insert_args = () insert_kwargs = { "event": event.for_group(self.group), "is_new_group_environment": True, "is_new": True, "is_regression": False, "primary_hash": "acbd18db4cc2f85cedef654fccc4a4d8", "skip_consume": False, "received_timestamp": event.data["received"], } self.kafka_eventstream.insert(*insert_args, **insert_kwargs) assert not self.producer_mock.produce.called logger.error.assert_called_with( "`GroupEvent` passed to `EventStream.insert`. `GroupEvent` may only be passed when " "associated with an `IssueOccurrence`", ) @patch("sentry.eventstream.backend.insert", autospec=True) def test_groupevent_occurrence_passed(self, mock_eventstream_insert: MagicMock) -> None: now = timezone.now() event = self.__build_transaction_event() event.group_id = self.group.id group_event = event.for_group(self.group) group_event.occurrence = self.build_occurrence() insert_args = () insert_kwargs = { "event": group_event, "is_new_group_environment": True, "is_new": True, "is_regression": False, "primary_hash": "acbd18db4cc2f85cedef654fccc4a4d8", "skip_consume": False, "received_timestamp": event.data["received"], "group_states": [], } self.__produce_event(*insert_args, **insert_kwargs) producer = self.producer_mock produce_args, produce_kwargs = list(producer.produce.call_args) version, type_, payload1, payload2 = json.loads(produce_kwargs["value"]) assert produce_kwargs["topic"] == "generic-events" assert produce_kwargs["key"] is None assert version == 2 assert type_ == "insert" occurrence_data = group_event.occurrence.to_dict() occurrence_data_no_evidence = { k: v for k, v in occurrence_data.items() if k not in {"evidence_data", "evidence_display"} } assert payload1["occurrence_id"] == occurrence_data["id"] assert payload1["occurrence_data"] == occurrence_data_no_evidence assert payload1["group_id"] == self.group.id assert payload1["group_first_seen"] == json.datetime_to_str(self.group.first_seen) query = Query( match=Entity(EntityKey.IssuePlatform.value), select=[ Column("event_id"), Column("group_id"), Column("occurrence_id"), ], where=[ Condition(Column("timestamp"), Op.GTE, now - timedelta(days=1)), Condition(Column("timestamp"), Op.LT, now + timedelta(days=1)), Condition(Column("project_id"), Op.EQ, self.project.id), ], ) request = Request( dataset=Dataset.IssuePlatform.value, app_id="test_eventstream", query=query, tenant_ids={"referrer": "test_eventstream", "organization_id": 1}, ) result = snuba.raw_snql_query( request, referrer="test_eventstream", ) assert len(result["data"]) == 1 assert result["data"][0]["event_id"] == event.event_id assert result["data"][0]["group_id"] == self.group.id assert result["data"][0]["occurrence_id"] == group_event.occurrence.id @patch("sentry.eventstream.backend.insert", autospec=True) def test_error(self, mock_eventstream_insert: MagicMock) -> None: now = timezone.now() event = self.__build_event(now) # verify eventstream was called by EventManager insert_args, insert_kwargs = list(mock_eventstream_insert.call_args) assert not insert_args group_state = { "is_new_group_environment": True, "is_new": True, "is_regression": False, } assert insert_kwargs == { "event": event, **group_state, "primary_hash": "acbd18db4cc2f85cedef654fccc4a4d8", "skip_consume": False, "received_timestamp": event.data["received"], "group_states": [{"id": event.groups[0].id, **group_state}], } headers, body = self.__produce_payload(*insert_args, **insert_kwargs) assert "occurrence_id" not in dict(headers) assert body @patch("sentry.eventstream.backend.insert", autospec=True) def test_transaction(self, mock_eventstream_insert: MagicMock) -> None: event = self.__build_transaction_event() event.group_id = None event.groups = [self.group] insert_args = () group_state = { "is_new_group_environment": True, "is_new": True, "is_regression": False, } insert_kwargs = { "event": event, **group_state, "primary_hash": "acbd18db4cc2f85cedef654fccc4a4d8", "skip_consume": False, "received_timestamp": event.data["received"], "group_states": [{"id": event.groups[0].id, **group_state}], } headers, body = self.__produce_payload(*insert_args, **insert_kwargs) assert "occurrence_id" not in dict(headers) assert body @patch("sentry.eventstream.backend.insert", autospec=True) def test_issue_platform(self, mock_eventstream_insert: MagicMock) -> None: event = self.__build_transaction_event() event.group_id = None event.groups = [self.group] group_event = event.for_group(self.group) group_event.occurrence = self.build_occurrence() insert_args = () group_state = { "is_new_group_environment": True, "is_new": True, "is_regression": False, } insert_kwargs = { "event": group_event, **group_state, "primary_hash": "acbd18db4cc2f85cedef654fccc4a4d8", "skip_consume": False, "received_timestamp": event.data["received"], "group_states": [{"id": event.groups[0].id, **group_state}], } headers, body = self.__produce_payload(*insert_args, **insert_kwargs) assert ("occurrence_id", group_event.occurrence.id.encode()) in headers assert body def test_insert_generic_event_contexts(self) -> None: create_default_projects() es = SnubaProtocolEventStream() profile_message = load_data("generic-event-profiling") geo_interface = {"city": "San Francisco", "country_code": "US", "region": "California"} event_data = { **profile_message["event"], "user": {"geo": geo_interface}, "timestamp": timezone.now().isoformat(), } project_id = event_data.get("project_id", self.project.id) occurrence, group_info = self.process_occurrence( event_id=event_data["event_id"], project_id=project_id, event_data=event_data, ) assert group_info is not None event = Event( event_id=occurrence.event_id, project_id=project_id, data=nodestore.backend.get(Event.generate_node_id(project_id, occurrence.event_id)), ) group_event = event.for_group(group_info.group) group_event.occurrence = occurrence with patch.object(es, "_send") as send: es.insert( group_event, True, True, False, "", 0.0, ) send_extra_data_data = send.call_args.kwargs["extra_data"][0]["data"] assert "contexts" in send_extra_data_data contexts_after_processing = send_extra_data_data["contexts"] assert contexts_after_processing == {**{"geo": geo_interface}} def test_event_forwarding_to_items(self): create_default_projects() es = self.kafka_eventstream # Prepare a generic event with a span item profile_message = load_data("generic-event-profiling") event_data = { **profile_message["event"], "contexts": {"trace": {"trace_id": uuid.uuid4().hex}}, "timestamp": timezone.now().isoformat(), } project_id = event_data.get("project_id", self.project.id) occurrence, group_info = self.process_occurrence( event_id=event_data["event_id"], project_id=project_id, event_data=event_data, ) assert group_info is not None event = Event( event_id=occurrence.event_id, project_id=project_id, data=nodestore.backend.get(Event.generate_node_id(project_id, occurrence.event_id)), ) group_event = event.for_group(group_info.group) group_event.occurrence = occurrence with self.options({"eventstream.eap_forwarding_rate": 1.0}): with patch.object(es, "_send_item") as send: es.insert( group_event, is_new=True, is_regression=True, is_new_group_environment=False, primary_hash="", skip_consume=False, received_timestamp=event_data["timestamp"], ) send.assert_called_once() trace_item = send.call_args[0][0] assert trace_item.item_id == event.event_id.encode("utf-8") assert trace_item.item_type == TRACE_ITEM_TYPE_OCCURRENCE assert trace_item.trace_id == event_data["contexts"]["trace"]["trace_id"] assert trace_item.project_id == event.project_id assert trace_item.organization_id == event.project.organization_id assert trace_item.retention_days == 90 assert trace_item.attributes["group_id"].int_value == group_info.group.id def test_snuba_event_stream_forwarding_to_items(self): create_default_projects() es = SnubaEventStream() # Prepare a generic event with a span item profile_message = load_data("generic-event-profiling") event_data = { **profile_message["event"], "contexts": {"trace": {"trace_id": uuid.uuid4().hex}}, "timestamp": timezone.now().isoformat(), } project_id = event_data.get("project_id", self.project.id) occurrence, group_info = self.process_occurrence( event_id=event_data["event_id"], project_id=project_id, event_data=event_data, ) assert group_info is not None event = Event( event_id=occurrence.event_id, project_id=project_id, data=nodestore.backend.get(Event.generate_node_id(project_id, occurrence.event_id)), ) group_event = event.for_group(group_info.group) group_event.occurrence = occurrence with self.options({"eventstream.eap_forwarding_rate": 1.0}): # Mock both _send and _send_item to avoid schema validation and verify EAP forwarding with patch.object(es, "_send"), patch.object(es, "_send_item") as mock_send_item: es.insert( group_event, is_new=True, is_regression=True, is_new_group_environment=False, primary_hash="", skip_consume=False, received_timestamp=event_data["timestamp"], ) mock_send_item.assert_called_once() trace_item = mock_send_item.call_args[0][0] assert trace_item.item_id == event.event_id.encode("utf-8") assert trace_item.item_type == TRACE_ITEM_TYPE_OCCURRENCE assert trace_item.trace_id == event_data["contexts"]["trace"]["trace_id"] assert trace_item.project_id == event.project_id assert trace_item.organization_id == event.project.organization_id assert trace_item.retention_days == 90 assert trace_item.attributes["group_id"].int_value == group_info.group.id def test_snuba_event_stream_no_forwarding_when_rate_zero(self): create_default_projects() es = SnubaEventStream() # Prepare a generic event with a span item profile_message = load_data("generic-event-profiling") event_data = { **profile_message["event"], "contexts": {"trace": {"trace_id": uuid.uuid4().hex}}, "timestamp": timezone.now().isoformat(), } project_id = event_data.get("project_id", self.project.id) occurrence, group_info = self.process_occurrence( event_id=event_data["event_id"], project_id=project_id, event_data=event_data, ) assert group_info is not None event = Event( event_id=occurrence.event_id, project_id=project_id, data=nodestore.backend.get(Event.generate_node_id(project_id, occurrence.event_id)), ) group_event = event.for_group(group_info.group) group_event.occurrence = occurrence with self.options({"eventstream.eap_forwarding_rate": 0.0}): with patch.object(es, "_send"), patch.object(es, "_send_item") as mock_send_item: es.insert( group_event, is_new=True, is_regression=True, is_new_group_environment=False, primary_hash="", skip_consume=False, received_timestamp=event_data["timestamp"], ) mock_send_item.assert_not_called()
SnubaEventStreamTest
python
walkccc__LeetCode
solutions/3201. Find the Maximum Length of Valid Subsequence I/3201.py
{ "start": 0, "end": 408 }
class ____: def maximumLength(self, nums: list[int]) -> int: # dp[i][j] := the maximum length of a valid subsequence, where the last # number mod k equal to i and the next desired number mod k equal to j dp = [[0] * 2 for _ in range(2)] # Extend the pattern xyxyxy...xy. for x in nums: for y in range(2): dp[x % 2][y] = dp[y][x % 2] + 1 return max(map(max, dp))
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType7.py
{ "start": 276, "end": 495 }
class ____(Generic[_T1]): def __init__(self, a: _T1): self._a: dict[str, _T1] = {} self._b: tuple[_T1, ...] = (a, a, a) self._c: tuple[_T1, _T1] = (a, a) self._d: list[_T1] = [a]
Class1
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 36299, "end": 36769 }
class ____(FieldValues): """ Valid and invalid values for `FloatField`. """ valid_inputs = { '1': 1.0, '0': 0.0, 1: 1.0, 0: 0.0, 1.0: 1.0, 0.0: 0.0, } invalid_inputs = { 'abc': ["A valid number is required."] } outputs = { '1': 1.0, '0': 0.0, 1: 1.0, 0: 0.0, 1.0: 1.0, 0.0: 0.0, } field = serializers.FloatField()
TestFloatField
python
networkx__networkx
networkx/generators/tests/test_ego.py
{ "start": 105, "end": 1327 }
class ____: def test_ego(self): G = nx.star_graph(3) H = nx.ego_graph(G, 0) assert nx.is_isomorphic(G, H) G.add_edge(1, 11) G.add_edge(2, 22) G.add_edge(3, 33) H = nx.ego_graph(G, 0) assert nx.is_isomorphic(nx.star_graph(3), H) G = nx.path_graph(3) H = nx.ego_graph(G, 0) assert edges_equal(H.edges(), [(0, 1)]) H = nx.ego_graph(G, 0, undirected=True) assert edges_equal(H.edges(), [(0, 1)]) H = nx.ego_graph(G, 0, center=False) assert edges_equal(H.edges(), []) def test_ego_distance(self): G = nx.Graph() G.add_edge(0, 1, weight=2, distance=1) G.add_edge(1, 2, weight=2, distance=2) G.add_edge(2, 3, weight=2, distance=1) assert nodes_equal(nx.ego_graph(G, 0, radius=3).nodes(), [0, 1, 2, 3]) eg = nx.ego_graph(G, 0, radius=3, distance="weight") assert nodes_equal(eg.nodes(), [0, 1]) eg = nx.ego_graph(G, 0, radius=3, distance="weight", undirected=True) assert nodes_equal(eg.nodes(), [0, 1]) eg = nx.ego_graph(G, 0, radius=3, distance="distance") assert nodes_equal(eg.nodes(), [0, 1, 2])
TestGeneratorEgo
python
huggingface__transformers
src/transformers/models/patchtst/modeling_patchtst.py
{ "start": 44667, "end": 45879 }
class ____(nn.Module): """ Assigns a scaling factor equal to 1 along the first dimension, and therefore applies no scaling to the input data. """ def __init__(self, config: PatchTSTConfig): super().__init__() self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1 self.keepdim = config.keepdim if hasattr(config, "keepdim") else True def forward( self, data: torch.Tensor, observed_indicator: Optional[torch.Tensor] = None ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Parameters: data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`): input for Batch norm calculation Returns: tuple of `torch.Tensor` of shapes (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`, `(batch_size, 1, num_input_channels)`) """ scale = torch.ones_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim) loc = torch.zeros_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim) return data, loc, scale
PatchTSTNOPScaler
python
apache__airflow
providers/pinecone/src/airflow/providers/pinecone/hooks/pinecone.py
{ "start": 1353, "end": 15155 }
class ____(BaseHook): """ Interact with Pinecone. This hook uses the Pinecone conn_id. :param conn_id: Optional, default connection id is `pinecone_default`. The connection id to use when connecting to Pinecone. """ conn_name_attr = "conn_id" default_conn_name = "pinecone_default" conn_type = "pinecone" hook_name = "Pinecone" @classmethod def get_connection_form_widgets(cls) -> dict[str, Any]: """Return connection widgets to add to connection form.""" from flask_appbuilder.fieldwidgets import BS3TextFieldWidget from flask_babel import lazy_gettext from wtforms import BooleanField, StringField return { "region": StringField(lazy_gettext("Pinecone Region"), widget=BS3TextFieldWidget(), default=None), "debug_curl": BooleanField(lazy_gettext("PINECONE_DEBUG_CURL"), default=False), "project_id": StringField( lazy_gettext("Project ID"), widget=BS3TextFieldWidget(), ), } @classmethod def get_ui_field_behaviour(cls) -> dict[str, Any]: """Return custom field behaviour.""" return { "hidden_fields": ["port", "schema"], "relabeling": { "login": "Pinecone Environment", "host": "Pinecone Host", "password": "Pinecone API key", }, } def __init__( self, conn_id: str = default_conn_name, environment: str | None = None, region: str | None = None ) -> None: self.conn_id = conn_id self._environment = environment self._region = region @property def api_key(self) -> str: key = self.conn.password if not key: raise LookupError("Pinecone API Key not found in connection") return key @cached_property def environment(self) -> str: if self._environment: return self._environment env = self.conn.login if not env: raise LookupError("Pinecone environment not found in connection") return env @cached_property def region(self) -> str: if self._region: return self._region region = self.conn.extra_dejson.get("region") if not region: raise LookupError("Pinecone region not found in connection") return region @cached_property def pinecone_client(self) -> Pinecone: """Pinecone object to interact with Pinecone.""" pinecone_host = self.conn.host extras = self.conn.extra_dejson pinecone_project_id = extras.get("project_id") enable_curl_debug = extras.get("debug_curl") if enable_curl_debug: os.environ["PINECONE_DEBUG_CURL"] = "true" return Pinecone( api_key=self.api_key, host=pinecone_host, project_id=pinecone_project_id, source_tag="apache_airflow", ) @cached_property def conn(self) -> Connection: return self.get_connection(self.conn_id) # type: ignore[return-value] def test_connection(self) -> tuple[bool, str]: try: self.pinecone_client.list_indexes() return True, "Connection established" except Exception as e: return False, str(e) def list_indexes(self) -> Any: """Retrieve a list of all indexes in your project.""" return self.pinecone_client.list_indexes() def upsert( self, index_name: str, vectors: list[Vector] | list[tuple] | list[dict], namespace: str = "", batch_size: int | None = None, show_progress: bool = True, **kwargs: Any, ) -> UpsertResponse: """ Write vectors into a namespace. If a new value is upserted for an existing vector id, it will overwrite the previous value. .. seealso:: https://docs.pinecone.io/reference/upsert To upsert in parallel follow .. seealso:: https://docs.pinecone.io/docs/insert-data#sending-upserts-in-parallel :param index_name: The name of the index to describe. :param vectors: A list of vectors to upsert. :param namespace: The namespace to write to. If not specified, the default namespace - "" is used. :param batch_size: The number of vectors to upsert in each batch. :param show_progress: Whether to show a progress bar using tqdm. Applied only if batch_size is provided. """ index = self.pinecone_client.Index(index_name) return index.upsert( vectors=vectors, namespace=namespace, batch_size=batch_size, show_progress=show_progress, **kwargs, ) def get_pod_spec_obj( self, *, replicas: int | None = None, shards: int | None = None, pods: int | None = None, pod_type: str | PodType = PodType.P1_X1, metadata_config: dict | None = None, source_collection: str | None = None, environment: str | None = None, ) -> PodSpec: """ Get a PodSpec object. :param replicas: The number of replicas. :param shards: The number of shards. :param pods: The number of pods. :param pod_type: The type of pod. :param metadata_config: The metadata configuration. :param source_collection: The source collection. :param environment: The environment to use when creating the index. """ return PodSpec( environment=environment or self.environment, replicas=replicas, shards=shards, pods=pods, pod_type=pod_type if isinstance(pod_type, PodType) else PodType(pod_type), metadata_config=metadata_config, source_collection=source_collection, ) def get_serverless_spec_obj(self, *, cloud: str, region: str | None = None) -> ServerlessSpec: """ Get a ServerlessSpec object. :param cloud: The cloud provider. :param region: The region to use when creating the index. """ return ServerlessSpec(cloud=cloud, region=region or self.region) def create_index( self, index_name: str, dimension: int, spec: ServerlessSpec | PodSpec, metric: str | None = "cosine", timeout: int | None = None, ) -> None: """ Create a new index. :param index_name: The name of the index. :param dimension: The dimension of the vectors to be indexed. :param spec: Pass a `ServerlessSpec` object to create a serverless index or a `PodSpec` object to create a pod index. ``get_serverless_spec_obj`` and ``get_pod_spec_obj`` can be used to create the Spec objects. :param metric: The metric to use. Defaults to cosine. :param timeout: The timeout to use. """ self.pinecone_client.create_index( name=index_name, dimension=dimension, spec=spec, metric=metric, timeout=timeout, ) def describe_index(self, index_name: str) -> Any: """ Retrieve information about a specific index. :param index_name: The name of the index to describe. """ return self.pinecone_client.describe_index(name=index_name) def delete_index(self, index_name: str, timeout: int | None = None) -> None: """ Delete a specific index. :param index_name: the name of the index. :param timeout: Timeout for wait until index gets ready. """ self.pinecone_client.delete_index(name=index_name, timeout=timeout) def configure_index( self, index_name: str, replicas: int | None = None, pod_type: str | None = "" ) -> None: """ Change the current configuration of the index. :param index_name: The name of the index to configure. :param replicas: The new number of replicas. :param pod_type: the new pod_type for the index. """ self.pinecone_client.configure_index(name=index_name, replicas=replicas, pod_type=pod_type) def create_collection(self, collection_name: str, index_name: str) -> None: """ Create a new collection from a specified index. :param collection_name: The name of the collection to create. :param index_name: The name of the source index. """ self.pinecone_client.create_collection(name=collection_name, source=index_name) def delete_collection(self, collection_name: str) -> None: """ Delete a specific collection. :param collection_name: The name of the collection to delete. """ self.pinecone_client.delete_collection(collection_name) def describe_collection(self, collection_name: str) -> Any: """ Retrieve information about a specific collection. :param collection_name: The name of the collection to describe. """ return self.pinecone_client.describe_collection(collection_name) def list_collections(self) -> Any: """Retrieve a list of all collections in the current project.""" return self.pinecone_client.list_collections() def query_vector( self, index_name: str, vector: list[Any], query_id: str | None = None, top_k: int = 10, namespace: str | None = None, query_filter: dict[str, str | float | int | bool | list[Any] | dict[Any, Any]] | None = None, include_values: bool | None = None, include_metadata: bool | None = None, sparse_vector: SparseValues | dict[str, list[float] | list[int]] | None = None, ) -> QueryResponse: """ Search a namespace using query vector. It retrieves the ids of the most similar items in a namespace, along with their similarity scores. API reference: https://docs.pinecone.io/reference/query :param index_name: The name of the index to query. :param vector: The query vector. :param query_id: The unique ID of the vector to be used as a query vector. :param top_k: The number of results to return. :param namespace: The namespace to fetch vectors from. If not specified, the default namespace is used. :param query_filter: The filter to apply. See https://www.pinecone.io/docs/metadata-filtering/ :param include_values: Whether to include the vector values in the result. :param include_metadata: Indicates whether metadata is included in the response as well as the ids. :param sparse_vector: sparse values of the query vector. Expected to be either a SparseValues object or a dict of the form: {'indices': list[int], 'values': list[float]}, where the lists each have the same length. """ index = self.pinecone_client.Index(index_name) return index.query( vector=vector, id=query_id, top_k=top_k, namespace=namespace, filter=query_filter, include_values=include_values, include_metadata=include_metadata, sparse_vector=sparse_vector, ) @staticmethod def _chunks(iterable: list[Any], batch_size: int = 100) -> Any: """Break an iterable into chunks of size batch_size.""" it = iter(iterable) chunk = tuple(itertools.islice(it, batch_size)) while chunk: yield chunk chunk = tuple(itertools.islice(it, batch_size)) def upsert_data_async( self, index_name: str, data: list[tuple[Any]], async_req: bool = False, pool_threads: int | None = None, ) -> None | list[Any]: """ Upserts (insert/update) data into the Pinecone index. :param index_name: Name of the index. :param data: List of tuples to be upserted. Each tuple is of form (id, vector, metadata). Metadata is optional. :param async_req: If True, upsert operations will be asynchronous. :param pool_threads: Number of threads for parallel upserting. If async_req is True, this must be provided. """ responses = [] with self.pinecone_client.Index(index_name, pool_threads=pool_threads) as index: if async_req and pool_threads: async_results = [index.upsert(vectors=chunk, async_req=True) for chunk in self._chunks(data)] responses = [async_result.get() for async_result in async_results] else: for chunk in self._chunks(data): response = index.upsert(vectors=chunk) responses.append(response) return responses def describe_index_stats( self, index_name: str, stats_filter: dict[str, str | float | int | bool | list[Any] | dict[Any, Any]] | None = None, **kwargs: Any, ) -> DescribeIndexStatsResponse: """ Describe the index statistics. Returns statistics about the index's contents. For example: The vector count per namespace and the number of dimensions. API reference: https://docs.pinecone.io/reference/describe_index_stats_post :param index_name: Name of the index. :param stats_filter: If this parameter is present, the operation only returns statistics for vectors that satisfy the filter. See https://www.pinecone.io/docs/metadata-filtering/ """ index = self.pinecone_client.Index(index_name) return index.describe_index_stats(filter=stats_filter, **kwargs)
PineconeHook
python
pytorch__pytorch
torch/fx/experimental/migrate_gradual_types/constraint.py
{ "start": 15479, "end": 15880 }
class ____: """ Tensor variable with no tensor constructor """ def __init__(self, tvar): """ :param tvar: tensor variable """ self.tvar = tvar def __repr__(self): return f"TV({self.tvar})" def __eq__(self, other): if isinstance(other, TVar): return self.tvar == other.tvar else: return False
TVar
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType7.py
{ "start": 1001, "end": 1220 }
class ____(Generic[_T3]): def __init__(self, a: _T3): self._a: dict[str, _T3] = {} self._b: tuple[_T3, ...] = (a, a, a) self._c: tuple[_T3, _T3] = (a, a) self._d: list[_T3] = [a]
Class3
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 5417, "end": 5573 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("LEFT", "RIGHT")
DiffSide
python
kamyu104__LeetCode-Solutions
Python/minimum-operations-to-halve-array-sum.py
{ "start": 55, "end": 537 }
class ____(object): def halveArray(self, nums): """ :type nums: List[int] :rtype: int """ target = sum(nums)/2.0 max_heap = [-x for x in nums] heapq.heapify(max_heap) result = 1 while max_heap: x = -heapq.heappop(max_heap)/2.0 target -= x if target <= 0.0: break heapq.heappush(max_heap, -x) result += 1 return result
Solution
python
PyCQA__pylint
tests/functional/u/useless/useless_parent_delegation.py
{ "start": 14006, "end": 14134 }
class ____(Egg): def __init__(self, thing: object) -> None: # [useless-parent-delegation] super().__init__(thing)
Ham
python
charliermarsh__ruff
scripts/ty_benchmark/src/benchmark/tool.py
{ "start": 2797, "end": 4128 }
class ____(Tool): path: Path | None warm: bool def __init__(self, *, warm: bool, path: Path | None = None): self.path = path self.warm = warm @override def command(self, project: Project, venv: Venv, single_threaded: bool) -> Command: path = self.path or which_tool("mypy", venv.bin) command = [ str(path), "--python-executable", str(venv.python.as_posix()), "--python-version", project.python_version, "--no-pretty", *project.include, "--check-untyped-defs", ] for exclude in project.exclude: # Mypy uses regex... # This is far from perfect, but not terrible. command.extend( [ "--exclude", exclude.replace(".", r"\.") .replace("**", ".*") .replace("*", r"\w.*"), ] ) if not self.warm: command.extend( [ "--no-incremental", "--cache-dir", os.devnull, ] ) return Command( name="mypy (warm)" if self.warm else "mypy", command=command, )
Mypy
python
aio-libs__aiohttp
aiohttp/client_reqrep.py
{ "start": 22450, "end": 30774 }
class ____: """An internal class for proxy requests.""" POST_METHODS = {hdrs.METH_PATCH, hdrs.METH_POST, hdrs.METH_PUT} auth = None proxy: URL | None = None response_class = ClientResponse server_hostname: str | None = None # Needed in connector.py version = HttpVersion11 _response = None # These class defaults help create_autospec() work correctly. # If autospec is improved in future, maybe these can be removed. url = URL() method = "GET" _writer_task: asyncio.Task[None] | None = None # async task for streaming data _skip_auto_headers: "CIMultiDict[None] | None" = None # N.B. # Adding __del__ method with self._writer closing doesn't make sense # because _writer is instance method, thus it keeps a reference to self. # Until writer has finished finalizer will not be called. def __init__( self, method: str, url: URL, *, headers: CIMultiDict[str], auth: BasicAuth | None, loop: asyncio.AbstractEventLoop, ssl: SSLContext | bool | Fingerprint, trust_env: bool = False, ): if match := _CONTAINS_CONTROL_CHAR_RE.search(method): raise ValueError( f"Method cannot contain non-token characters {method!r} " f"(found at least {match.group()!r})" ) # URL forbids subclasses, so a simple type check is enough. assert type(url) is URL, url self.original_url = url self.url = url.with_fragment(None) if url.raw_fragment else url self.method = method.upper() self.loop = loop self._ssl = ssl if loop.get_debug(): self._source_traceback = traceback.extract_stack(sys._getframe(1)) self._update_host(url) self._update_headers(headers) self._update_auth(auth, trust_env) def _reset_writer(self, _: object = None) -> None: self._writer_task = None def _get_content_length(self) -> int | None: """Extract and validate Content-Length header value. Returns parsed Content-Length value or None if not set. Raises ValueError if header exists but cannot be parsed as an integer. """ if hdrs.CONTENT_LENGTH not in self.headers: return None content_length_hdr = self.headers[hdrs.CONTENT_LENGTH] try: return int(content_length_hdr) except ValueError: raise ValueError( f"Invalid Content-Length header: {content_length_hdr}" ) from None @property def _writer(self) -> asyncio.Task[None] | None: return self._writer_task @_writer.setter def _writer(self, writer: asyncio.Task[None]) -> None: if self._writer_task is not None: self._writer_task.remove_done_callback(self._reset_writer) self._writer_task = writer writer.add_done_callback(self._reset_writer) def is_ssl(self) -> bool: return self.url.scheme in _SSL_SCHEMES @property def ssl(self) -> "SSLContext | bool | Fingerprint": return self._ssl @property def connection_key(self) -> ConnectionKey: url = self.url return tuple.__new__( ConnectionKey, ( url.raw_host or "", url.port, url.scheme in _SSL_SCHEMES, self._ssl, None, None, None, ), ) def _update_auth(self, auth: BasicAuth | None, trust_env: bool = False) -> None: """Set basic auth.""" if auth is None: auth = self.auth if auth is None: return if not isinstance(auth, BasicAuth): raise TypeError("BasicAuth() tuple is required instead") self.headers[hdrs.AUTHORIZATION] = auth.encode() def _update_host(self, url: URL) -> None: """Update destination host, port and connection type (ssl).""" # get host/port if not url.raw_host: raise InvalidURL(url) # basic auth info if url.raw_user or url.raw_password: self.auth = BasicAuth(url.user or "", url.password or "") def _update_headers(self, headers: CIMultiDict[str]) -> None: """Update request headers.""" self.headers: CIMultiDict[str] = CIMultiDict() # Build the host header host = self.url.host_port_subcomponent # host_port_subcomponent is None when the URL is a relative URL. # but we know we do not have a relative URL here. assert host is not None self.headers[hdrs.HOST] = headers.pop(hdrs.HOST, host) self.headers.extend(headers) def _create_response(self, task: asyncio.Task[None] | None) -> ClientResponse: return self.response_class( self.method, self.original_url, writer=task, continue100=None, timer=TimerNoop(), traces=(), loop=self.loop, session=None, request_headers=self.headers, original_url=self.original_url, ) def _create_writer(self, protocol: BaseProtocol) -> StreamWriter: return StreamWriter(protocol, self.loop) def _should_write(self, protocol: BaseProtocol) -> bool: return protocol.writing_paused async def _send(self, conn: "Connection") -> ClientResponse: # Specify request target: # - CONNECT request must send authority form URI # - not CONNECT proxy must send absolute form URI # - most common is origin form URI if self.method == hdrs.METH_CONNECT: connect_host = self.url.host_subcomponent assert connect_host is not None path = f"{connect_host}:{self.url.port}" elif self.proxy and not self.is_ssl(): path = str(self.url) else: path = self.url.raw_path_qs protocol = conn.protocol assert protocol is not None writer = self._create_writer(protocol) # set default content-type if ( self.method in self.POST_METHODS and ( self._skip_auto_headers is None or hdrs.CONTENT_TYPE not in self._skip_auto_headers ) and hdrs.CONTENT_TYPE not in self.headers ): self.headers[hdrs.CONTENT_TYPE] = "application/octet-stream" v = self.version if hdrs.CONNECTION not in self.headers: if conn._connector.force_close: if v == HttpVersion11: self.headers[hdrs.CONNECTION] = "close" elif v == HttpVersion10: self.headers[hdrs.CONNECTION] = "keep-alive" # status + headers status_line = f"{self.method} {path} HTTP/{v.major}.{v.minor}" # Buffer headers for potential coalescing with body await writer.write_headers(status_line, self.headers) task: asyncio.Task[None] | None if self._should_write(protocol): coro = self._write_bytes(writer, conn, self._get_content_length()) if sys.version_info >= (3, 12): # Optimization for Python 3.12, try to write # bytes immediately to avoid having to schedule # the task on the event loop. task = asyncio.Task(coro, loop=self.loop, eager_start=True) else: task = self.loop.create_task(coro) if task.done(): task = None else: self._writer = task else: # We have nothing to write because # - there is no body # - the protocol does not have writing paused # - we are not waiting for a 100-continue response protocol.start_timeout() writer.set_eof() task = None self._response = self._create_response(task) return self._response async def _write_bytes( self, writer: AbstractStreamWriter, conn: "Connection", content_length: int | None, ) -> None: # Base class never has a body, this will never be run. assert False
ClientRequestBase
python
mlflow__mlflow
mlflow/genai/judges/tools/get_span_performance_and_timing_report.py
{ "start": 1154, "end": 17473 }
class ____(JudgeTool): """ A tool that generates a span timing report for a trace. The report includes span timing hierarchy, summary statistics, longest-running spans, and concurrent operations detection. """ MAX_NAME_LENGTH = 30 MIN_OVERLAP_THRESHOLD_S = 0.01 TOP_SPANS_COUNT = 10 MAX_CONCURRENT_PAIRS = 20 @property def name(self) -> str: """Return the name of this tool. Returns: The tool name constant for the span timing report tool. """ return ToolNames.GET_SPAN_PERFORMANCE_AND_TIMING_REPORT def get_definition(self) -> ToolDefinition: """Get the tool definition for LiteLLM/OpenAI function calling. Returns: ToolDefinition object containing the tool specification. """ return ToolDefinition( function=FunctionToolDefinition( name=ToolNames.GET_SPAN_PERFORMANCE_AND_TIMING_REPORT, description=( "Generate a comprehensive span timing report for the trace, showing " "latencies, execution order, hierarchy, duration statistics, longest " "spans, and concurrent operations. Useful for analyzing system " "performance and identifying bottlenecks." ), parameters=ToolParamsSchema( type="object", properties={}, required=[], ), ), type="function", ) def invoke(self, trace: Trace) -> str: """Generate span timing report for the trace. Args: trace: The MLflow trace object to analyze. Returns: Formatted timing report as a string. """ if not trace or not trace.data or not trace.data.spans: return "No spans found in trace" spans = trace.data.spans trace_info = trace.info timing_data = self._calculate_timing_data(spans) concurrent_pairs = self._find_concurrent_operations(spans) type_summary = self._calculate_type_summary(spans) return self._format_report( trace_info=trace_info, timing_data=timing_data, concurrent_pairs=concurrent_pairs, type_summary=type_summary, ) def _calculate_timing_data(self, spans: list[Span]) -> dict[str, SpanTimingData]: """Calculate timing data for all spans. Args: spans: List of spans from the trace. Returns: Dictionary mapping span IDs to their timing data. """ children_by_parent = defaultdict(list) for span in spans: children_by_parent[span.parent_id].append(span) for parent_spans in children_by_parent.values(): parent_spans.sort(key=lambda s: s.start_time_ns) self_durations = self._calculate_self_durations(spans, children_by_parent) timing_data = {} span_counter = [0] def process_span_tree( span_id: str | None, ancestors: list[str] | None = None, depth: int = 0 ) -> None: """Recursively traverse and process the span tree. Args: span_id: ID of the current span being processed. ancestors: List of ancestor span numbers for hierarchy tracking. depth: Current depth in the span tree. """ ancestors = ancestors or [] for span in children_by_parent.get(span_id, []): span_counter[0] += 1 span_num = f"s{span_counter[0]}" total_dur_s = (span.end_time_ns - span.start_time_ns) / 1_000_000_000 self_dur_s = self_durations[span.span_id] child_dur_s = total_dur_s - self_dur_s parent_num = ( timing_data.get( span.parent_id, SpanTimingData( span_id="", name="", span_type="", total_duration_s=0, self_duration_s=0, child_duration_s=0, span_number="", parent_number=None, ancestors=[], depth=0, ), ).span_number or None ) timing_data[span.span_id] = SpanTimingData( span_id=span.span_id, name=span.name, span_type=span.span_type or "UNKNOWN", total_duration_s=total_dur_s, self_duration_s=self_dur_s, child_duration_s=child_dur_s, span_number=span_num, parent_number=parent_num, ancestors=ancestors.copy(), depth=depth, ) process_span_tree(span.span_id, ancestors + [span_num], depth + 1) process_span_tree(None) return timing_data def _calculate_self_durations( self, spans: list[Span], children_by_parent: dict[str | None, list[Span]] ) -> dict[str, float]: """Calculate self duration for each span (total minus children). Args: spans: List of all spans in the trace. children_by_parent: Dictionary mapping parent IDs to their child spans. Returns: Dictionary mapping span IDs to their self durations in seconds. """ self_durations = {} for span in spans: total_dur_ns = span.end_time_ns - span.start_time_ns children = children_by_parent.get(span.span_id, []) if not children: self_durations[span.span_id] = total_dur_ns / 1_000_000_000 continue intervals = [(child.start_time_ns, child.end_time_ns) for child in children] merged_intervals = self._merge_intervals(intervals) children_dur_ns = sum(end - start for start, end in merged_intervals) self_durations[span.span_id] = (total_dur_ns - children_dur_ns) / 1_000_000_000 return self_durations @staticmethod def _merge_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]: """Merge overlapping time intervals. Args: intervals: List of (start, end) time intervals in nanoseconds. Returns: List of merged non-overlapping intervals. """ if not intervals: return [] intervals.sort() merged = [intervals[0]] for start, end in intervals[1:]: if start <= merged[-1][1]: merged[-1] = (merged[-1][0], max(merged[-1][1], end)) else: merged.append((start, end)) return merged def _find_concurrent_operations(self, spans: list[Span]) -> list[ConcurrentPair]: """Find spans that execute concurrently. Args: spans: List of all spans to analyze for concurrency. Returns: List of concurrent span pairs with overlap information. """ concurrent_pairs = [] for i, span1 in enumerate(spans): for span2 in spans[i + 1 :]: if span1.parent_id != span2.parent_id: continue overlap_start = max(span1.start_time_ns, span2.start_time_ns) overlap_end = min(span1.end_time_ns, span2.end_time_ns) if overlap_start >= overlap_end: continue overlap_s = (overlap_end - overlap_start) / 1_000_000_000 if overlap_s > self.MIN_OVERLAP_THRESHOLD_S: concurrent_pairs.append( ConcurrentPair( span1_num="", span2_num="", span1_name=self._truncate_name(span1.name), span2_name=self._truncate_name(span2.name), overlap_s=overlap_s, ) ) if len(concurrent_pairs) >= self.MAX_CONCURRENT_PAIRS: return concurrent_pairs return concurrent_pairs def _calculate_type_summary(self, spans: list[Span]) -> dict[str, tuple[int, float]]: """Calculate summary statistics by span type. Args: spans: List of spans to summarize. Returns: Dictionary mapping span types to (count, total_duration) tuples. """ type_stats = defaultdict(lambda: [0, 0.0]) for span in spans: span_type = span.span_type or "UNKNOWN" duration_s = (span.end_time_ns - span.start_time_ns) / 1_000_000_000 type_stats[span_type][0] += 1 type_stats[span_type][1] += duration_s return {k: tuple(v) for k, v in type_stats.items()} def _truncate_name(self, name: str) -> str: """Truncate long names for display. Args: name: The span name to potentially truncate. Returns: Truncated name if it exceeds MAX_NAME_LENGTH, otherwise original name. """ if len(name) <= self.MAX_NAME_LENGTH: return name return name[: self.MAX_NAME_LENGTH - 3] + "..." def _format_report( self, trace_info: TraceInfo, timing_data: dict[str, SpanTimingData], concurrent_pairs: list[ConcurrentPair], type_summary: dict[str, tuple[int, float]], ) -> str: """Format the complete timing report. Args: trace_info: Trace metadata information. timing_data: Calculated timing data for all spans. concurrent_pairs: List of concurrent span pairs. type_summary: Summary statistics by span type. Returns: Formatted report as a string. """ lines = [] self._add_header(lines, trace_info, len(timing_data)) self._add_column_definitions(lines) self._add_span_table(lines, timing_data) self._add_type_summary(lines, type_summary) self._add_top_spans(lines, timing_data) self._add_concurrent_operations(lines, concurrent_pairs, timing_data) return "\n".join(lines) def _add_header(self, lines: list[str], trace_info: TraceInfo, span_count: int) -> None: """Add report header. Args: lines: List to append header lines to. trace_info: Trace metadata for header information. span_count: Total number of spans in the trace. """ lines.extend( [ f"SPAN TIMING REPORT FOR TRACE: {trace_info.trace_id}", f"Total Duration: {trace_info.execution_duration / 1000:.2f}s", f"Total Spans: {span_count}", "", ] ) def _add_column_definitions(self, lines: list[str]) -> None: """Add column definitions section. Args: lines: List to append column definition lines to. """ lines.extend( [ "COLUMN DEFINITIONS:", " self_dur: Time spent in this span excluding its children (actual work)", " total_dur: Total time from span start to end (includes waiting for children)", " child_dur: Time spent waiting for child spans to complete", " parent: The immediate parent span number", " ancestors: Complete chain from root to parent", "", ] ) def _add_span_table(self, lines: list[str], timing_data: dict[str, SpanTimingData]) -> None: """Add the main span timing table. Args: lines: List to append table lines to. timing_data: Timing data for all spans to display. """ lines.extend( [ "SPAN TABLE:", "-" * 200, f"{'span_num':<8} {'span_id':<20} {'name':<30} " f"{'type':<12} {'self_dur':>9} {'total_dur':>10} {'child_dur':>10} " f"{'parent':<8} {'ancestors':<60}", "-" * 200, ] ) sorted_data = sorted( timing_data.values(), key=lambda x: int(x.span_number[1:]) if x.span_number else 0 ) for data in sorted_data: if not data.span_number: continue name = self._truncate_name(data.name) parent = data.parent_number or "-" ancestors_str = "→".join(data.ancestors) if data.ancestors else "root" lines.append( f"{data.span_number:<8} {data.span_id:<20} {name:<30} " f"{data.span_type:<12} {data.self_duration_s:>9.3f} " f"{data.total_duration_s:>10.3f} {data.child_duration_s:>10.3f} " f"{parent:<8} {ancestors_str:<60}" ) def _add_type_summary( self, lines: list[str], type_summary: dict[str, tuple[int, float]] ) -> None: """Add summary by span type. Args: lines: List to append summary lines to. type_summary: Summary statistics organized by span type. """ lines.extend( [ "", "SUMMARY BY TYPE:", "-" * 80, f"{'type':<20} {'count':>8} {'total_dur':>12} {'avg_dur':>12}", "-" * 80, ] ) for span_type in sorted(type_summary.keys()): count, total_dur = type_summary[span_type] avg_dur = total_dur / count lines.append(f"{span_type:<20} {count:>8} {total_dur:>12.3f}s {avg_dur:>12.3f}s") def _add_top_spans(self, lines: list[str], timing_data: dict[str, SpanTimingData]) -> None: """Add top spans by self duration. Args: lines: List to append top spans section to. timing_data: Timing data for all spans to rank. """ lines.extend( [ "", "TOP 10 SPANS BY SELF DURATION (actual work, not including children):", "-" * 110, f"{'rank':<6} {'span_num':<10} {'span_id':<20} {'name':<30} " f"{'type':<12} {'self_dur':>12}", "-" * 110, ] ) sorted_spans = sorted(timing_data.values(), key=lambda x: x.self_duration_s, reverse=True)[ : self.TOP_SPANS_COUNT ] for i, data in enumerate(sorted_spans): name = self._truncate_name(data.name) lines.append( f"{i + 1:<6} {data.span_number:<10} {data.span_id:<20} {name:<30} " f"{data.span_type:<12} {data.self_duration_s:>12.3f}s" ) def _add_concurrent_operations( self, lines: list[str], concurrent_pairs: list[ConcurrentPair], timing_data: dict[str, SpanTimingData], ) -> None: """Add concurrent operations section. Args: lines: List to append concurrent operations section to. concurrent_pairs: List of detected concurrent span pairs. timing_data: Timing data (currently unused but kept for consistency). """ lines.extend( [ "", "CONCURRENT OPERATIONS:", "-" * 100, ] ) if not concurrent_pairs: lines.append("No significant concurrent operations detected.") return lines.extend( [ f"{'span1':<10} {'span2':<10} {'name1':<30} {'name2':<30} {'overlap':>10}", "-" * 100, ] ) lines.extend( f"{pair.span1_num:<10} {pair.span2_num:<10} " f"{pair.span1_name:<30} {pair.span2_name:<30} " f"{pair.overlap_s:>10.3f}s" for pair in concurrent_pairs )
GetSpanPerformanceAndTimingReportTool
python
dask__distributed
distributed/utils.py
{ "start": 12969, "end": 13799 }
class ____: def __init__(self, target: Callable[[], None], daemon: bool, name: str): self._exception: BaseException | None = None def wrapper() -> None: try: target() except BaseException as e: self._exception = e self._thread = thread = threading.Thread( target=wrapper, daemon=daemon, name=name ) thread.start() def join(self, timeout: float | None = None) -> None: thread = self._thread thread.join(timeout=timeout) if thread.is_alive(): raise TimeoutError("join timed out") if self._exception is not None: try: raise self._exception finally: # remove a reference cycle del self._exception
_CollectErrorThread
python
ray-project__ray
python/ray/autoscaler/_private/vsphere/node_provider.py
{ "start": 457, "end": 4696 }
class ____(NodeProvider): max_terminate_nodes = 1000 cluster_config = None def __init__(self, provider_config, cluster_name): NodeProvider.__init__(self, provider_config, cluster_name) self.tag_cache = {} self.tag_cache_lock = threading.Lock() self.client = ClusterOperatorClient( cluster_name, provider_config, VsphereWcpNodeProvider.cluster_config ) @staticmethod def bootstrap_config(cluster_config): config = bootstrap_vsphere(cluster_config) VsphereWcpNodeProvider.cluster_config = config return config def non_terminated_nodes(self, tag_filters): nodes, tag_cache = self.client.list_vms(tag_filters) with self.tag_cache_lock: for node_id in nodes: for k, v in tag_cache[node_id].items(): if node_id in self.tag_cache.keys(): self.tag_cache[node_id][k] = v else: self.tag_cache[node_id] = {} self.tag_cache[node_id][k] = v logger.info(f"Non terminated nodes' tags are {self.tag_cache}") return nodes def is_running(self, node_id): return self.client.is_vm_power_on(node_id) def is_terminated(self, node_id): if self.client.is_vm_power_on(node_id): return False else: # If the node is not powered on but has the creating tag, then it could # be under reconfiguration, such as plugging the GPU. In this case we # should consider the node is not terminated, it will be turned on later return not self.client.is_vm_creating(node_id) def node_tags(self, node_id): with self.tag_cache_lock: return self.tag_cache[node_id] def external_ip(self, node_id): return self.client.get_vm_external_ip(node_id) def internal_ip(self, node_id): # Currently vSphere VMs do not show an internal IP. So we just return the # external IP return self.client.get_vm_external_ip(node_id) def set_node_tags(self, node_id, tags): # This method gets called from the Ray and it passes # node_id. It updates old tags (if present) with new values. with self.tag_cache_lock: for k, v in tags.items(): # update tags for node_id self.tag_cache[node_id][k] = v logger.info(f"Updated tags for {node_id} to: {self.tag_cache[node_id]}") def create_node(self, node_config, tags, count) -> Dict[str, Any]: """Creates instances. Returns dict mapping instance id to VM object for the created instances. """ to_be_launched_node_count = count created_nodes_dict = {} if to_be_launched_node_count > 0: created_nodes_dict = self.client.create_nodes( tags, to_be_launched_node_count, node_config ) # make sure to mark newly created nodes as ready # so autoscaler shouldn't provision new ones with self.tag_cache_lock: for node_id in created_nodes_dict.keys(): self.tag_cache[node_id] = tags.copy() self.tag_cache[node_id][TAG_RAY_NODE_STATUS] = STATUS_SETTING_UP self.tag_cache[node_id][TAG_RAY_NODE_NAME] = node_id self.tag_cache[node_id][TAG_RAY_CLUSTER_NAME] = self.cluster_name logger.info( f"Node {node_id} created with tags: {self.tag_cache[node_id]}" ) return created_nodes_dict def terminate_node(self, node_id): if not node_id or self.client.is_vm_creating(node_id): return # Delete node iff it is either in a running or a failure state self.client.delete_node(node_id) with self.tag_cache_lock: if node_id in self.tag_cache: self.tag_cache.pop(node_id) def terminate_nodes(self, node_ids): if not node_ids: return for node_id in node_ids: self.terminate_node(node_id) def safe_to_scale(self) -> bool: return self.client.safe_to_scale()
VsphereWcpNodeProvider
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 150971, "end": 151358 }
class ____(str, Enum): """ Same as `ChunkedMmap`, but vectors are forced to be locked in RAM In this way we avoid cold requests to disk, but risk to run out of memory Designed as a replacement for `Memory`, which doesn&#x27;t depend on RocksDB """ def __str__(self) -> str: return str(self.value) INRAMCHUNKEDMMAP = "InRamChunkedMmap"
VectorStorageTypeOneOf3
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/ndb/async/shopping_cart.py
{ "start": 653, "end": 690 }
class ____(ndb.Model): pass
Account
python
getsentry__sentry
src/sentry/backup/helpers.py
{ "start": 812, "end": 1303 }
class ____(DjangoJSONEncoder): """ A wrapper around the default `DjangoJSONEncoder` that always retains milliseconds, even when their implicit value is `.000`. This is necessary because the ECMA-262 compatible `DjangoJSONEncoder` drops these by default. """ def default(self, obj): if isinstance(obj, datetime): return obj.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" return super().default(obj)
DatetimeSafeDjangoJSONEncoder
python
realpython__materials
django-pagination/terms/migrations/0001_initial.py
{ "start": 92, "end": 489 }
class ____(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Keyword', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=30)), ], ), ]
Migration
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/events.py
{ "start": 28547, "end": 28703 }
class ____(Enum): SET_OBJECT = "SET_OBJECT" GET_OBJECT = "GET_OBJECT" RM_OBJECT = "RM_OBJECT" CP_OBJECT = "CP_OBJECT"
ObjectStoreOperationType
python
plotly__plotly.py
plotly/graph_objs/carpet/_aaxis.py
{ "start": 233, "end": 60421 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "carpet" _path_str = "carpet.aaxis" _valid_props = { "arraydtick", "arraytick0", "autorange", "autotypenumbers", "categoryarray", "categoryarraysrc", "categoryorder", "cheatertype", "color", "dtick", "endline", "endlinecolor", "endlinewidth", "exponentformat", "fixedrange", "gridcolor", "griddash", "gridwidth", "labelalias", "labelpadding", "labelprefix", "labelsuffix", "linecolor", "linewidth", "minexponent", "minorgridcolor", "minorgridcount", "minorgriddash", "minorgridwidth", "nticks", "range", "rangemode", "separatethousands", "showexponent", "showgrid", "showline", "showticklabels", "showtickprefix", "showticksuffix", "smoothing", "startline", "startlinecolor", "startlinewidth", "tick0", "tickangle", "tickfont", "tickformat", "tickformatstopdefaults", "tickformatstops", "tickmode", "tickprefix", "ticksuffix", "ticktext", "ticktextsrc", "tickvals", "tickvalssrc", "title", "type", } @property def arraydtick(self): """ The stride between grid lines along the axis The 'arraydtick' 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["arraydtick"] @arraydtick.setter def arraydtick(self, val): self["arraydtick"] = val @property def arraytick0(self): """ The starting index of grid lines along the axis The 'arraytick0' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [0, 9223372036854775807] Returns ------- int """ return self["arraytick0"] @arraytick0.setter def arraytick0(self, val): self["arraytick0"] = val @property def autorange(self): """ Determines whether or not the range of this axis is computed in relation to the input data. See `rangemode` for more info. If `range` is provided, then `autorange` is set to False. The 'autorange' property is an enumeration that may be specified as: - One of the following enumeration values: [True, False, 'reversed'] Returns ------- Any """ return self["autorange"] @autorange.setter def autorange(self, val): self["autorange"] = val @property def autotypenumbers(self): """ Using "strict" a numeric string in trace data is not converted to a number. Using *convert types* a numeric string in trace data may be treated as a number during automatic axis `type` detection. Defaults to layout.autotypenumbers. The 'autotypenumbers' property is an enumeration that may be specified as: - One of the following enumeration values: ['convert types', 'strict'] Returns ------- Any """ return self["autotypenumbers"] @autotypenumbers.setter def autotypenumbers(self, val): self["autotypenumbers"] = val @property def categoryarray(self): """ Sets the order in which categories on this axis appear. Only has an effect if `categoryorder` is set to "array". Used with `categoryorder`. The 'categoryarray' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["categoryarray"] @categoryarray.setter def categoryarray(self, val): self["categoryarray"] = val @property def categoryarraysrc(self): """ Sets the source reference on Chart Studio Cloud for `categoryarray`. The 'categoryarraysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["categoryarraysrc"] @categoryarraysrc.setter def categoryarraysrc(self, val): self["categoryarraysrc"] = val @property def categoryorder(self): """ Specifies the ordering logic for the case of categorical variables. By default, plotly uses "trace", which specifies the order that is present in the data supplied. Set `categoryorder` to *category ascending* or *category descending* if order should be determined by the alphanumerical order of the category names. Set `categoryorder` to "array" to derive the ordering from the attribute `categoryarray`. If a category is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to the "trace" mode. The unspecified categories will follow the categories in `categoryarray`. The 'categoryorder' property is an enumeration that may be specified as: - One of the following enumeration values: ['trace', 'category ascending', 'category descending', 'array'] Returns ------- Any """ return self["categoryorder"] @categoryorder.setter def categoryorder(self, val): self["categoryorder"] = val @property def cheatertype(self): """ The 'cheatertype' property is an enumeration that may be specified as: - One of the following enumeration values: ['index', 'value'] Returns ------- Any """ return self["cheatertype"] @cheatertype.setter def cheatertype(self, val): self["cheatertype"] = val @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): """ The stride between grid lines along the axis The 'dtick' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["dtick"] @dtick.setter def dtick(self, val): self["dtick"] = val @property def endline(self): """ Determines whether or not a line is drawn at along the final value of this axis. If True, the end line is drawn on top of the grid lines. The 'endline' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["endline"] @endline.setter def endline(self, val): self["endline"] = val @property def endlinecolor(self): """ Sets the line color of the end line. The 'endlinecolor' 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["endlinecolor"] @endlinecolor.setter def endlinecolor(self, val): self["endlinecolor"] = val @property def endlinewidth(self): """ Sets the width (in px) of the end line. The 'endlinewidth' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["endlinewidth"] @endlinewidth.setter def endlinewidth(self, val): self["endlinewidth"] = 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. 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 fixedrange(self): """ Determines whether or not this axis is zoom-able. If true, then zoom is disabled. The 'fixedrange' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["fixedrange"] @fixedrange.setter def fixedrange(self, val): self["fixedrange"] = val @property def gridcolor(self): """ Sets the axis line color. 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 axis line. 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 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 labelpadding(self): """ Extra padding between label and the axis The 'labelpadding' property is a integer and may be specified as: - An int (or float that will be cast to an int) Returns ------- int """ return self["labelpadding"] @labelpadding.setter def labelpadding(self, val): self["labelpadding"] = val @property def labelprefix(self): """ Sets a axis label prefix. The 'labelprefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["labelprefix"] @labelprefix.setter def labelprefix(self, val): self["labelprefix"] = val @property def labelsuffix(self): """ Sets a axis label suffix. The 'labelsuffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["labelsuffix"] @labelsuffix.setter def labelsuffix(self, val): self["labelsuffix"] = 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 minexponent(self): """ Hide SI prefix for 10^n if |n| is below this number 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 minorgridcolor(self): """ Sets the color of the grid lines. The 'minorgridcolor' 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["minorgridcolor"] @minorgridcolor.setter def minorgridcolor(self, val): self["minorgridcolor"] = val @property def minorgridcount(self): """ Sets the number of minor grid ticks per major grid tick The 'minorgridcount' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [0, 9223372036854775807] Returns ------- int """ return self["minorgridcount"] @minorgridcount.setter def minorgridcount(self, val): self["minorgridcount"] = val @property def minorgriddash(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 'minorgriddash' 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["minorgriddash"] @minorgriddash.setter def minorgriddash(self, val): self["minorgriddash"] = val @property def minorgridwidth(self): """ Sets the width (in px) of the grid lines. The 'minorgridwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["minorgridwidth"] @minorgridwidth.setter def minorgridwidth(self, val): self["minorgridwidth"] = 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 [0, 9223372036854775807] Returns ------- int """ return self["nticks"] @nticks.setter def nticks(self, val): self["nticks"] = val @property def range(self): """ Sets the range of this axis. If the axis `type` is "log", then you must take the log of your desired range (e.g. to set the range from 1 to 100, set the range from 0 to 2). If the axis `type` is "date", it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis `type` is "category", it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears. The 'range' property is an info array that may be specified as: * a list or tuple of 2 elements where: (0) The 'range[0]' property accepts values of any type (1) The 'range[1]' property accepts values of any type Returns ------- list """ return self["range"] @range.setter def range(self, val): self["range"] = val @property def rangemode(self): """ If "normal", the range is computed in relation to the extrema of the input data. If "tozero", the range extends to 0, regardless of the input data If "nonnegative", the range is non-negative, regardless of the input data. The 'rangemode' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'tozero', 'nonnegative'] Returns ------- Any """ return self["rangemode"] @rangemode.setter def rangemode(self, val): self["rangemode"] = 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 axis labels are drawn on the low side, the high side, both, or neither side of the axis. The 'showticklabels' property is an enumeration that may be specified as: - One of the following enumeration values: ['start', 'end', 'both', 'none'] Returns ------- Any """ 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 smoothing(self): """ The 'smoothing' property is a number and may be specified as: - An int or float in the interval [0, 1.3] Returns ------- int|float """ return self["smoothing"] @smoothing.setter def smoothing(self, val): self["smoothing"] = val @property def startline(self): """ Determines whether or not a line is drawn at along the starting value of this axis. If True, the start line is drawn on top of the grid lines. The 'startline' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["startline"] @startline.setter def startline(self, val): self["startline"] = val @property def startlinecolor(self): """ Sets the line color of the start line. The 'startlinecolor' 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["startlinecolor"] @startlinecolor.setter def startlinecolor(self, val): self["startlinecolor"] = val @property def startlinewidth(self): """ Sets the width (in px) of the start line. The 'startlinewidth' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["startlinewidth"] @startlinewidth.setter def startlinewidth(self, val): self["startlinewidth"] = val @property def tick0(self): """ The starting index of grid lines along the axis The 'tick0' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ 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 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.carpet.aaxis.Tickfont` - A dict of string/value properties that will be passed to the Tickfont constructor Returns ------- plotly.graph_objs.carpet.aaxis.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.carpet.aaxis.Tickformatstop - A list or tuple of dicts of string/value properties that will be passed to the Tickformatstop constructor Returns ------- tuple[plotly.graph_objs.carpet.aaxis.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.data.carpet.aaxis.tickformatstopdefaults), sets the default property values to use for elements of carpet.aaxis.tickformatstops The 'tickformatstopdefaults' property is an instance of Tickformatstop that may be specified as: - An instance of :class:`plotly.graph_objs.carpet.aaxis.Tickformatstop` - A dict of string/value properties that will be passed to the Tickformatstop constructor Returns ------- plotly.graph_objs.carpet.aaxis.Tickformatstop """ return self["tickformatstopdefaults"] @tickformatstopdefaults.setter def tickformatstopdefaults(self, val): self["tickformatstopdefaults"] = val @property def tickmode(self): """ The 'tickmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['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 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 title(self): """ The 'title' property is an instance of Title that may be specified as: - An instance of :class:`plotly.graph_objs.carpet.aaxis.Title` - A dict of string/value properties that will be passed to the Title constructor Returns ------- plotly.graph_objs.carpet.aaxis.Title """ return self["title"] @title.setter def title(self, val): self["title"] = val @property def type(self): """ Sets the axis type. By default, plotly attempts to determined the axis type by looking into the data of the traces that referenced the axis in question. The 'type' property is an enumeration that may be specified as: - One of the following enumeration values: ['-', 'linear', 'date', 'category'] Returns ------- Any """ return self["type"] @type.setter def type(self, val): self["type"] = val @property def _prop_descriptions(self): return """\ arraydtick The stride between grid lines along the axis arraytick0 The starting index of grid lines along the axis autorange Determines whether or not the range of this axis is computed in relation to the input data. See `rangemode` for more info. If `range` is provided, then `autorange` is set to False. autotypenumbers Using "strict" a numeric string in trace data is not converted to a number. Using *convert types* a numeric string in trace data may be treated as a number during automatic axis `type` detection. Defaults to layout.autotypenumbers. categoryarray Sets the order in which categories on this axis appear. Only has an effect if `categoryorder` is set to "array". Used with `categoryorder`. categoryarraysrc Sets the source reference on Chart Studio Cloud for `categoryarray`. categoryorder Specifies the ordering logic for the case of categorical variables. By default, plotly uses "trace", which specifies the order that is present in the data supplied. Set `categoryorder` to *category ascending* or *category descending* if order should be determined by the alphanumerical order of the category names. Set `categoryorder` to "array" to derive the ordering from the attribute `categoryarray`. If a category is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to the "trace" mode. The unspecified categories will follow the categories in `categoryarray`. cheatertype 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 The stride between grid lines along the axis endline Determines whether or not a line is drawn at along the final value of this axis. If True, the end line is drawn on top of the grid lines. endlinecolor Sets the line color of the end line. endlinewidth Sets the width (in px) of the end line. 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. fixedrange Determines whether or not this axis is zoom-able. If true, then zoom is disabled. gridcolor Sets the axis line color. 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 axis line. 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. labelpadding Extra padding between label and the axis labelprefix Sets a axis label prefix. labelsuffix Sets a axis label suffix. linecolor Sets the axis line color. linewidth Sets the width (in px) of the axis line. minexponent Hide SI prefix for 10^n if |n| is below this number minorgridcolor Sets the color of the grid lines. minorgridcount Sets the number of minor grid ticks per major grid tick minorgriddash 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"). minorgridwidth Sets the width (in px) of the grid lines. 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". range Sets the range of this axis. If the axis `type` is "log", then you must take the log of your desired range (e.g. to set the range from 1 to 100, set the range from 0 to 2). If the axis `type` is "date", it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis `type` is "category", it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears. rangemode If "normal", the range is computed in relation to the extrema of the input data. If "tozero", the range extends to 0, regardless of the input data If "nonnegative", the range is non-negative, regardless of the input data. 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 axis labels are drawn on the low side, the high side, both, or neither side of the axis. 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. smoothing startline Determines whether or not a line is drawn at along the starting value of this axis. If True, the start line is drawn on top of the grid lines. startlinecolor Sets the line color of the start line. startlinewidth Sets the width (in px) of the start line. tick0 The starting index of grid lines along the axis tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. 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.carpet.aaxis.Ti ckformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.carpet .aaxis.tickformatstopdefaults), sets the default property values to use for elements of carpet.aaxis.tickformatstops tickmode tickprefix Sets a tick label prefix. 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`. title :class:`plotly.graph_objects.carpet.aaxis.Title` instance or dict with compatible properties type Sets the axis type. By default, plotly attempts to determined the axis type by looking into the data of the traces that referenced the axis in question. """ def __init__( self, arg=None, arraydtick=None, arraytick0=None, autorange=None, autotypenumbers=None, categoryarray=None, categoryarraysrc=None, categoryorder=None, cheatertype=None, color=None, dtick=None, endline=None, endlinecolor=None, endlinewidth=None, exponentformat=None, fixedrange=None, gridcolor=None, griddash=None, gridwidth=None, labelalias=None, labelpadding=None, labelprefix=None, labelsuffix=None, linecolor=None, linewidth=None, minexponent=None, minorgridcolor=None, minorgridcount=None, minorgriddash=None, minorgridwidth=None, nticks=None, range=None, rangemode=None, separatethousands=None, showexponent=None, showgrid=None, showline=None, showticklabels=None, showtickprefix=None, showticksuffix=None, smoothing=None, startline=None, startlinecolor=None, startlinewidth=None, tick0=None, tickangle=None, tickfont=None, tickformat=None, tickformatstops=None, tickformatstopdefaults=None, tickmode=None, tickprefix=None, ticksuffix=None, ticktext=None, ticktextsrc=None, tickvals=None, tickvalssrc=None, title=None, type=None, **kwargs, ): """ Construct a new Aaxis object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.carpet.Aaxis` arraydtick The stride between grid lines along the axis arraytick0 The starting index of grid lines along the axis autorange Determines whether or not the range of this axis is computed in relation to the input data. See `rangemode` for more info. If `range` is provided, then `autorange` is set to False. autotypenumbers Using "strict" a numeric string in trace data is not converted to a number. Using *convert types* a numeric string in trace data may be treated as a number during automatic axis `type` detection. Defaults to layout.autotypenumbers. categoryarray Sets the order in which categories on this axis appear. Only has an effect if `categoryorder` is set to "array". Used with `categoryorder`. categoryarraysrc Sets the source reference on Chart Studio Cloud for `categoryarray`. categoryorder Specifies the ordering logic for the case of categorical variables. By default, plotly uses "trace", which specifies the order that is present in the data supplied. Set `categoryorder` to *category ascending* or *category descending* if order should be determined by the alphanumerical order of the category names. Set `categoryorder` to "array" to derive the ordering from the attribute `categoryarray`. If a category is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to the "trace" mode. The unspecified categories will follow the categories in `categoryarray`. cheatertype 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 The stride between grid lines along the axis endline Determines whether or not a line is drawn at along the final value of this axis. If True, the end line is drawn on top of the grid lines. endlinecolor Sets the line color of the end line. endlinewidth Sets the width (in px) of the end line. 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. fixedrange Determines whether or not this axis is zoom-able. If true, then zoom is disabled. gridcolor Sets the axis line color. 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 axis line. 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. labelpadding Extra padding between label and the axis labelprefix Sets a axis label prefix. labelsuffix Sets a axis label suffix. linecolor Sets the axis line color. linewidth Sets the width (in px) of the axis line. minexponent Hide SI prefix for 10^n if |n| is below this number minorgridcolor Sets the color of the grid lines. minorgridcount Sets the number of minor grid ticks per major grid tick minorgriddash 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"). minorgridwidth Sets the width (in px) of the grid lines. 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". range Sets the range of this axis. If the axis `type` is "log", then you must take the log of your desired range (e.g. to set the range from 1 to 100, set the range from 0 to 2). If the axis `type` is "date", it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis `type` is "category", it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears. rangemode If "normal", the range is computed in relation to the extrema of the input data. If "tozero", the range extends to 0, regardless of the input data If "nonnegative", the range is non-negative, regardless of the input data. 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 axis labels are drawn on the low side, the high side, both, or neither side of the axis. 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. smoothing startline Determines whether or not a line is drawn at along the starting value of this axis. If True, the start line is drawn on top of the grid lines. startlinecolor Sets the line color of the start line. startlinewidth Sets the width (in px) of the start line. tick0 The starting index of grid lines along the axis tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. 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.carpet.aaxis.Ti ckformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.carpet .aaxis.tickformatstopdefaults), sets the default property values to use for elements of carpet.aaxis.tickformatstops tickmode tickprefix Sets a tick label prefix. 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`. title :class:`plotly.graph_objects.carpet.aaxis.Title` instance or dict with compatible properties type Sets the axis type. By default, plotly attempts to determined the axis type by looking into the data of the traces that referenced the axis in question. Returns ------- Aaxis """ super().__init__("aaxis") 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.carpet.Aaxis constructor must be a dict or an instance of :class:`plotly.graph_objs.carpet.Aaxis`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("arraydtick", arg, arraydtick) self._set_property("arraytick0", arg, arraytick0) self._set_property("autorange", arg, autorange) self._set_property("autotypenumbers", arg, autotypenumbers) self._set_property("categoryarray", arg, categoryarray) self._set_property("categoryarraysrc", arg, categoryarraysrc) self._set_property("categoryorder", arg, categoryorder) self._set_property("cheatertype", arg, cheatertype) self._set_property("color", arg, color) self._set_property("dtick", arg, dtick) self._set_property("endline", arg, endline) self._set_property("endlinecolor", arg, endlinecolor) self._set_property("endlinewidth", arg, endlinewidth) self._set_property("exponentformat", arg, exponentformat) self._set_property("fixedrange", arg, fixedrange) self._set_property("gridcolor", arg, gridcolor) self._set_property("griddash", arg, griddash) self._set_property("gridwidth", arg, gridwidth) self._set_property("labelalias", arg, labelalias) self._set_property("labelpadding", arg, labelpadding) self._set_property("labelprefix", arg, labelprefix) self._set_property("labelsuffix", arg, labelsuffix) self._set_property("linecolor", arg, linecolor) self._set_property("linewidth", arg, linewidth) self._set_property("minexponent", arg, minexponent) self._set_property("minorgridcolor", arg, minorgridcolor) self._set_property("minorgridcount", arg, minorgridcount) self._set_property("minorgriddash", arg, minorgriddash) self._set_property("minorgridwidth", arg, minorgridwidth) self._set_property("nticks", arg, nticks) self._set_property("range", arg, range) self._set_property("rangemode", arg, rangemode) 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("smoothing", arg, smoothing) self._set_property("startline", arg, startline) self._set_property("startlinecolor", arg, startlinecolor) self._set_property("startlinewidth", arg, startlinewidth) self._set_property("tick0", arg, tick0) self._set_property("tickangle", arg, tickangle) 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("tickmode", arg, tickmode) self._set_property("tickprefix", arg, tickprefix) 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("title", arg, title) self._set_property("type", arg, type) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Aaxis
python
pytorch__pytorch
test/torch_np/test_random.py
{ "start": 631, "end": 2054 }
class ____(TestCase): @parametrize("use_numpy", [True, False]) @parametrize( "func", [ tnp.random.normal, tnp.random.rand, partial(tnp.random.randint, 0, 5), tnp.random.randn, subtest(tnp.random.random, name="random_random"), subtest(tnp.random.random_sample, name="random_sample"), tnp.random.sample, tnp.random.uniform, ], ) def test_rndm_scalar(self, func, use_numpy): # default `size` means a python scalar return with control_stream(use_numpy): r = func() assert isinstance(r, (int, float)) @parametrize("use_numpy", [True, False]) @parametrize( "func", [ tnp.random.normal, tnp.random.rand, partial(tnp.random.randint, 0, 5), tnp.random.randn, subtest(tnp.random.random, name="random_random"), subtest(tnp.random.random_sample, name="random_sample"), tnp.random.sample, tnp.random.uniform, ], ) def test_rndm_array(self, func, use_numpy): with control_stream(use_numpy): if func in (tnp.random.rand, tnp.random.randn): r = func(10) else: r = func(size=10) assert isinstance(r, tnp.ndarray) @instantiate_parametrized_tests
TestScalarReturn
python
readthedocs__readthedocs.org
readthedocs/settings/docker_compose.py
{ "start": 67, "end": 9894 }
class ____(CommunityBaseSettings): """Settings for local development with Docker""" DEBUG = bool(os.environ.get("RTD_DJANGO_DEBUG", False)) DOCKER_ENABLE = True RTD_DOCKER_COMPOSE = True RTD_DOCKER_COMPOSE_NETWORK = "community_readthedocs" RTD_DOCKER_COMPOSE_VOLUME = "community_build-user-builds" RTD_DOCKER_USER = f"{os.geteuid()}:{os.getegid()}" BUILD_MEMORY_LIMIT = "2g" PRODUCTION_DOMAIN = os.environ.get("RTD_PRODUCTION_DOMAIN", "devthedocs.org") PUBLIC_DOMAIN = os.environ.get("RTD_PUBLIC_DOMAIN", "devthedocs.org") PUBLIC_API_URL = f"http://{PRODUCTION_DOMAIN}" SLUMBER_API_HOST = "http://web:8000" RTD_EXTERNAL_VERSION_DOMAIN = "build.devthedocs.org" # When using ngrok + HTTPS, forms are blocked because the schema from the final URL # doesn't match the one from the origin header. # Previously only the host was checked, this was changed in 4.0: # https://docs.djangoproject.com/en/4.2/releases/4.0/#csrf # # Reference: https://docs.djangoproject.com/en/4.2/ref/settings/#secure-proxy-ssl-header SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") STATIC_URL = "/static/" # In the local docker environment, nginx should be trusted to set the host correctly USE_X_FORWARDED_HOST = True # https://docs.docker.com/engine/reference/commandline/run/#add-entries-to-container-hosts-file---add-host # export HOSTIP=`ip -4 addr show scope global dev wlp4s0 | grep inet | awk '{print \$2}' | cut -d / -f 1` HOSTIP = os.environ.get("HOSTIP") # If the host IP is not specified, try to get it from the socket address list _, __, ips = socket.gethostbyname_ex(socket.gethostname()) if ips and not HOSTIP: HOSTIP = ips[0][:-1] + "1" # Turn this on to test ads USE_PROMOS = os.environ.get("RTD_USE_PROMOS") is not None ADSERVER_API_BASE = f"http://{HOSTIP}:5000" # Create a Token for an admin User and set it here. ADSERVER_API_KEY = None ADSERVER_API_TIMEOUT = 2 # seconds - Docker for Mac is very slow @property def DOCROOT(self): # Add an extra directory level using the container's hostname. # This allows us to run development environment with multiple builders (`--scale-build=2` or more), # and avoid the builders overwritting each others when building the same project/version return os.path.join(super().DOCROOT, socket.gethostname()) # New templates RTD_EXT_THEME_DEV_SERVER_ENABLED = True @property def RTD_EXT_THEME_DEV_SERVER(self): if self.RTD_EXT_THEME_DEV_SERVER_ENABLED: return "http://assets.devthedocs.org:10001" # Enable auto syncing elasticsearch documents ELASTICSEARCH_DSL_AUTOSYNC = "SEARCH" in os.environ RTD_CLEAN_AFTER_BUILD = True # Disable password validators on development AUTH_PASSWORD_VALIDATORS = [] @property def RTD_EMBED_API_EXTERNAL_DOMAINS(self): domains = super().RTD_EMBED_API_EXTERNAL_DOMAINS domains.extend( [ r"^.*\.readthedocs\.io$", r"^.*\.org\.readthedocs\.build$", r"^.*\.readthedocs-hosted\.com$", r"^.*\.com\.readthedocs\.build$", ] ) return domains @property def LOGGING(self): logging = super().LOGGING logging["handlers"]["console"]["level"] = os.environ.get( "RTD_LOGGING_LEVEL", "INFO" ) logging["formatters"]["default"]["format"] = "[%(asctime)s] " + self.LOG_FORMAT # Allow Sphinx and other tools to create loggers logging["disable_existing_loggers"] = False logging["handlers"]["console"]["formatter"] = "colored_console" logging["loggers"].update( { # Disable Django access requests logging (e.g. GET /path/to/url) # https://github.com/django/django/blob/ca9872905559026af82000e46cde6f7dedc897b6/django/core/servers/basehttp.py#L24 "django.server": { "handlers": ["null"], "propagate": False, }, # Disable S3 logging "boto3": { "handlers": ["null"], "propagate": False, }, "botocore": { "handlers": ["null"], "propagate": False, }, "s3transfer": { "handlers": ["null"], "propagate": False, }, # Disable Docker API logging "urllib3": { "handlers": ["null"], "propagate": False, }, # Disable gitpython logging "git.cmd": { "handlers": ["null"], "propagate": False, }, } ) return logging @property def DATABASES(self): # noqa return { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "docs_db", "USER": os.environ.get("DB_USER", "docs_user"), "PASSWORD": os.environ.get("DB_PWD", "docs_pwd"), "HOST": os.environ.get("DB_HOST", "database"), "PORT": "", }, "telemetry": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "telemetry", "USER": os.environ.get("DB_USER", "docs_user"), "PASSWORD": os.environ.get("DB_PWD", "docs_pwd"), "HOST": os.environ.get("DB_HOST", "database"), "PORT": "", }, } ACCOUNT_EMAIL_VERIFICATION = "none" SESSION_COOKIE_DOMAIN = None CACHES = { "default": { "BACKEND": "django.core.cache.backends.redis.RedisCache", "LOCATION": "redis://:redispassword@cache:6379", }, } BROKER_URL = f"redis://:redispassword@cache:6379/0" CELERY_ALWAYS_EAGER = False EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" RTD_BUILD_MEDIA_STORAGE = "readthedocs.storage.s3_storage.S3BuildMediaStorage" # Storage backend for build languages RTD_BUILD_TOOLS_STORAGE = "readthedocs.storage.s3_storage.S3BuildToolsStorage" # Storage for static files (those collected with `collectstatic`) RTD_STATICFILES_STORAGE = "readthedocs.storage.s3_storage.NoManifestS3StaticStorage" AWS_ACCESS_KEY_ID = os.environ.get("RTD_AWS_ACCESS_KEY_ID", "admin") AWS_SECRET_ACCESS_KEY = os.environ.get("RTD_AWS_SECRET_ACCESS_KEY", "password") S3_MEDIA_STORAGE_BUCKET = os.environ.get("RTD_S3_MEDIA_STORAGE_BUCKET", "media") S3_BUILD_COMMANDS_STORAGE_BUCKET = os.environ.get("RTD_S3_BUILD_COMMANDS_STORAGE_BUCKET", "builds") S3_BUILD_TOOLS_STORAGE_BUCKET = os.environ.get("RTD_S3_BUILD_TOOLS_STORAGE_BUCKET", "build-tools") S3_STATIC_STORAGE_BUCKET = os.environ.get("RTD_S3_STATIC_STORAGE_BUCKET", "static") S3_STATIC_STORAGE_OVERRIDE_HOSTNAME = PRODUCTION_DOMAIN S3_MEDIA_STORAGE_OVERRIDE_HOSTNAME = PRODUCTION_DOMAIN S3_PROVIDER = os.environ.get("RTD_S3_PROVIDER", "minio") AWS_S3_ENCRYPTION = False AWS_S3_SECURE_URLS = False AWS_S3_USE_SSL = False AWS_STS_ASSUME_ROLE_ARN = os.environ.get("RTD_AWS_STS_ASSUME_ROLE_ARN", None) AWS_S3_REGION_NAME = os.environ.get("RTD_AWS_S3_REGION_NAME", None) @property def AWS_S3_ENDPOINT_URL(self): if self.S3_PROVIDER == "minio": return "http://storage:9000/" return None AWS_QUERYSTRING_AUTH = False @property def SOCIALACCOUNT_PROVIDERS(self): """Allow settings social account settigs from the host system.""" providers = self._SOCIALACCOUNT_PROVIDERS for provider in providers.keys(): try: for setting in ["client_id", "secret"]: value = os.environ.get( f"RTD_SOCIALACCOUNT_PROVIDERS_{provider.upper()}_{setting.upper()}" ) if value is not None: providers[provider]['APPS'][0][setting] = value except KeyError: pass return providers GITHUB_APP_ID = os.environ.get("RTD_GITHUB_APP_ID") GITHUB_APP_NAME = os.environ.get("RTD_GITHUB_APP_NAME") GITHUB_APP_WEBHOOK_SECRET = os.environ.get("RTD_GITHUB_APP_WEBHOOK_SECRET") GITHUB_APP_PRIVATE_KEY = os.environ.get("RTD_GITHUB_APP_PRIVATE_KEY") RTD_SAVE_BUILD_COMMANDS_TO_STORAGE = True RTD_BUILD_COMMANDS_STORAGE = "readthedocs.storage.s3_storage.S3BuildCommandsStorage" BUILD_COLD_STORAGE_URL = "http://storage:9000/builds" STATICFILES_DIRS = [ os.path.join(CommunityBaseSettings.SITE_ROOT, "media"), ] # Remove the checks on the number of fields being submitted # This limit is mostly hit on large forms in the Django admin DATA_UPLOAD_MAX_NUMBER_FIELDS = None SUPPORT_EMAIL = "support@example.com" RTD_FILETREEDIFF_ALL = "RTD_FILETREEDIFF_ALL" in os.environ @property def STORAGES(self): return { "staticfiles": { "BACKEND": "readthedocs.storage.s3_storage.S3StaticStorage" }, "usercontent": { "BACKEND": "storages.backends.s3.S3Storage", "OPTIONS": { "bucket_name": os.environ.get("RTD_S3_USER_CONTENT_STORAGE_BUCKET", "usercontent"), "url_protocol": "http:", "custom_domain": self.PRODUCTION_DOMAIN + "/usercontent", }, }, } DockerBaseSettings.load_settings(__name__)
DockerBaseSettings
python
getsentry__sentry
src/sentry/monitors/endpoints/organization_monitor_environment_details.py
{ "start": 780, "end": 2404 }
class ____( MonitorEndpoint, MonitorEnvironmentDetailsMixin ): publish_status = { "DELETE": ApiPublishStatus.EXPERIMENTAL, "PUT": ApiPublishStatus.EXPERIMENTAL, } owner = ApiOwner.CRONS @extend_schema( operation_id="Update a Monitor Environment", parameters=[ GlobalParams.ORG_ID_OR_SLUG, MonitorParams.MONITOR_ID_OR_SLUG, MonitorParams.ENVIRONMENT, ], responses={ 200: MonitorSerializer, 400: RESPONSE_BAD_REQUEST, 401: RESPONSE_UNAUTHORIZED, 403: RESPONSE_FORBIDDEN, 404: RESPONSE_NOT_FOUND, }, ) def put( self, request: Request, organization, project, monitor, monitor_environment ) -> Response: """ Update a monitor environment. """ return self.update_monitor_environment(request, project, monitor, monitor_environment) @extend_schema( operation_id="Delete a Monitor Environments", parameters=[ GlobalParams.ORG_ID_OR_SLUG, MonitorParams.MONITOR_ID_OR_SLUG, MonitorParams.ENVIRONMENT, ], responses={ 202: RESPONSE_ACCEPTED, 401: RESPONSE_UNAUTHORIZED, 403: RESPONSE_FORBIDDEN, 404: RESPONSE_NOT_FOUND, }, ) def delete( self, request: Request, organization, project, monitor, monitor_environment ) -> Response: return self.delete_monitor_environment(request, project, monitor, monitor_environment)
OrganizationMonitorEnvironmentDetailsEndpoint
python
getsentry__sentry
tests/sentry/sentry_metrics/consumers/test_last_seen_updater.py
{ "start": 5060, "end": 6089 }
class ____: @pytest.fixture def message_filter(self): return LastSeenUpdaterMessageFilter(DummyMetricsBackend()) def empty_message_with_headers(self, headers: list[tuple[str, bytes]]): payload = KafkaPayload(headers=headers, key=Mock(), value=Mock()) return Message( BrokerValue(payload=payload, partition=Mock(), offset=0, timestamp=timezone.now()) ) def test_message_filter_no_header(self, message_filter) -> None: message = self.empty_message_with_headers([]) assert not message_filter.should_drop(message) def test_message_filter_header_contains_d(self, message_filter) -> None: message = self.empty_message_with_headers([("mapping_sources", b"hcd")]) assert not message_filter.should_drop(message) def test_message_filter_header_contains_no_d(self, message_filter) -> None: message = self.empty_message_with_headers([("mapping_sources", b"fhc")]) assert message_filter.should_drop(message)
TestFilterMethod
python
tensorflow__tensorflow
tensorflow/python/saved_model/nested_structure_coder.py
{ "start": 7215, "end": 7664 }
class ____: """Codec for floats.""" def can_encode(self, pyobj): return isinstance(pyobj, float) def do_encode(self, float64_value, encode_fn): del encode_fn value = struct_pb2.StructuredValue() value.float64_value = float64_value return value def can_decode(self, value): return value.HasField("float64_value") def do_decode(self, value, decode_fn): del decode_fn return value.float64_value
_Float64Codec
python
dask__distributed
distributed/process.py
{ "start": 1700, "end": 12887 }
class ____: """ A coroutine-compatible multiprocessing.Process-alike. All normally blocking methods are wrapped in Tornado coroutines. """ _process: multiprocessing.Process def __init__(self, loop=None, target=None, name=None, args=(), kwargs=None): kwargs = kwargs or {} if not callable(target): raise TypeError(f"`target` needs to be callable, not {type(target)!r}") self._state = _ProcessState() self._loop = loop or IOLoop.current(instance=False) # _keep_child_alive is the write side of a pipe, which, when it is # closed, causes the read side of the pipe to unblock for reading. Note # that it is never closed directly. The write side is closed by the # kernel when our process exits, or possibly by the garbage collector # closing the file descriptor when the last reference to # _keep_child_alive goes away. We can take advantage of this fact to # monitor from the child and exit when the parent goes away unexpectedly # (for example due to SIGKILL). This variable is otherwise unused except # for the assignment here. parent_alive_pipe, self._keep_child_alive = get_mp_context().Pipe(duplex=False) self._process = get_mp_context().Process( target=self._run, name=name, args=( target, args, kwargs, parent_alive_pipe, self._keep_child_alive, dask.config.global_config, ), ) self._name = self._process.name self._proc_finalizer = weakref.finalize( self, _asyncprocess_finalizer, self._process ) self._watch_q = PyQueue() self._exit_future = Future() self._exit_callback = None self._closed = False self._start_threads() def __repr__(self): return f"<{self.__class__.__name__} {self._name}>" def _check_closed(self): if self._closed: raise ValueError("invalid operation on closed AsyncProcess") def _start_threads(self): self._watch_message_thread = threading.Thread( target=self._watch_message_queue, name="AsyncProcess %s watch message queue" % self.name, args=( weakref.ref(self), self._process, self._loop, self._state, self._watch_q, self._exit_future, ), ) self._watch_message_thread.daemon = True self._watch_message_thread.start() def stop_thread(q): q.put_nowait({"op": "stop"}) # We don't join the thread here as a finalizer can be called # asynchronously from anywhere self._thread_finalizer = weakref.finalize(self, stop_thread, q=self._watch_q) self._thread_finalizer.atexit = False def _on_exit(self, exitcode: int) -> None: # Called from the event loop when the child process exited self._process = None # type: ignore[assignment] if self._exit_callback is not None: self._exit_callback(self) self._exit_future.set_result(exitcode) @classmethod def _immediate_exit_when_closed(cls, parent_alive_pipe): """ Immediately exit the process when parent_alive_pipe is closed. """ def monitor_parent(): try: # The parent_alive_pipe should be held open as long as the # parent is alive and wants us to stay alive. Nothing writes to # it, so the read will block indefinitely. parent_alive_pipe.recv() except EOFError: # Parent process went away unexpectedly. Exit immediately. Could # consider other exiting approaches here. My initial preference # is to unconditionally and immediately exit. If we're in this # state it is possible that a "clean" process exit won't work # anyway - if, for example, the system is getting bogged down # due to the running out of memory, exiting sooner rather than # later might be needed to restore normal system function. # If this is in appropriate for your use case, please file a # bug. os._exit(-1) else: # If we get here, something odd is going on. File descriptors # got crossed? raise RuntimeError("unexpected state: should be unreachable") t = threading.Thread(target=monitor_parent) t.daemon = True t.start() @classmethod def _run( cls, target, args, kwargs, parent_alive_pipe, _keep_child_alive, inherit_config ): _keep_child_alive.close() # Child process entry point cls._immediate_exit_when_closed(parent_alive_pipe) threading.current_thread().name = "MainThread" # Update the global config given priority to the existing global config dask.config.update(dask.config.global_config, inherit_config, priority="old") target(*args, **kwargs) @classmethod def _watch_message_queue( # type: ignore[no-untyped-def] cls, selfref, process: multiprocessing.Process, loop, state, q, exit_future ): # As multiprocessing.Process is not thread-safe, we run all # blocking operations from this single loop and ship results # back to the caller when needed. r = repr(selfref()) name = selfref().name def _start(): process.start() thread = threading.Thread( target=AsyncProcess._watch_process, name="AsyncProcess %s watch process join" % name, args=(selfref, process, state, q), ) thread.daemon = True thread.start() state.is_alive = True state.pid = process.pid logger.debug(f"[{r}] created process with pid {state.pid!r}") while True: msg = q.get() logger.debug(f"[{r}] got message {msg!r}") op = msg["op"] if op == "start": _call_and_set_future(loop, msg["future"], _start) elif op == "terminate": # Send SIGTERM _call_and_set_future(loop, msg["future"], process.terminate) elif op == "kill": # Send SIGKILL _call_and_set_future(loop, msg["future"], process.kill) elif op == "stop": break else: assert 0, msg @classmethod def _watch_process(cls, selfref, process, state, q): r = repr(selfref()) process.join() exitcode = original_exit_code = process.exitcode if exitcode is None: # The child process is already reaped # (may happen if waitpid() is called elsewhere). exitcode = 255 state.is_alive = False state.exitcode = exitcode # Make sure the process is removed from the global list # (see _children in multiprocessing/process.py) # Then notify the Process object self = selfref() # only keep self alive when required try: if self is not None: _loop_add_callback(self._loop, self._on_exit, exitcode) finally: self = None # lose reference # logging may fail - defer calls to after the callback is added if original_exit_code is None: logger.warning( "[%s] process %r exit status was already read will report exitcode 255", r, state.pid, ) else: logger.debug("[%s] process %r exited with code %r", r, state.pid, exitcode) def start(self): """ Start the child process. This method returns a future. """ self._check_closed() fut = Future() self._watch_q.put_nowait({"op": "start", "future": fut}) return fut def terminate(self) -> asyncio.Future[None]: """Terminate the child process. This method returns a future. See also -------- multiprocessing.Process.terminate """ self._check_closed() fut: Future[None] = Future() self._watch_q.put_nowait({"op": "terminate", "future": fut}) return fut def kill(self) -> asyncio.Future[None]: """Send SIGKILL to the child process. On Windows, this is the same as terminate(). This method returns a future. See also -------- multiprocessing.Process.kill """ self._check_closed() fut: Future[None] = Future() self._watch_q.put_nowait({"op": "kill", "future": fut}) return fut async def join(self, timeout=None): """ Wait for the child process to exit. This method returns a coroutine. """ self._check_closed() assert self._state.pid is not None, "can only join a started process" if self._state.exitcode is not None: return # Shield otherwise the timeout cancels the future and our # on_exit callback will try to set a result on a canceled future await wait_for(asyncio.shield(self._exit_future), timeout) def close(self): """ Stop helper thread and release resources. This method returns immediately and does not ensure the child process has exited. """ if not self._closed: self._thread_finalizer() self._process = None self._closed = True def set_exit_callback(self: Self, func: Callable[[Self], None]) -> None: """ Set a function to be called by the event loop when the process exits. The function is called with the AsyncProcess as sole argument. The function may not be a coroutine function. """ # XXX should this be a property instead? assert not inspect.iscoroutinefunction( func ), "exit callback may not be a coroutine function" assert callable(func), "exit callback should be callable" assert ( self._state.pid is None ), "cannot set exit callback when process already started" self._exit_callback = func def is_alive(self): return self._state.is_alive @property def pid(self): return self._state.pid @property def exitcode(self): return self._state.exitcode @property def name(self): return self._name @property def daemon(self): return self._process.daemon @daemon.setter def daemon(self, value): self._process.daemon = value def _asyncprocess_finalizer(proc): if proc.is_alive(): try: logger.info(f"reaping stray process {proc}") proc.terminate() except OSError: pass
AsyncProcess
python
django__django
tests/update/models.py
{ "start": 492, "end": 557 }
class ____(models.Model): x = models.IntegerField(default=10)
A
python
scikit-image__scikit-image
benchmarks/benchmark_registration.py
{ "start": 1121, "end": 3164 }
class ____: """Benchmarks for registration.phase_cross_correlation in scikit-image""" param_names = ["ndims", "image_size", "upsample_factor", "dtype"] params = [(2, 3), (32, 100), (1, 5, 10), (np.complex64, np.complex128)] def setup(self, ndims, image_size, upsample_factor, dtype, *args): if phase_cross_correlation is None: raise NotImplementedError("phase_cross_correlation unavailable") shifts = (-2.3, 1.7, 5.4, -3.2)[:ndims] phantom = img_as_float(data.binary_blobs(length=image_size, n_dim=ndims)) self.reference_image = np.fft.fftn(phantom).astype(dtype, copy=False) self.shifted_image = ndi.fourier_shift(self.reference_image, shifts) self.shifted_image = self.shifted_image.astype(dtype, copy=False) def time_phase_cross_correlation(self, ndims, image_size, upsample_factor, *args): phase_cross_correlation( self.reference_image, self.shifted_image, upsample_factor=upsample_factor, space="fourier", ) def peakmem_reference(self, *args): """Provide reference for memory measurement with empty benchmark. Peakmem benchmarks measure the maximum amount of RAM used by a function. However, this maximum also includes the memory used during the setup routine (as of asv 0.2.1; see [1]_). Measuring an empty peakmem function might allow us to disambiguate between the memory used by setup and the memory used by target (see other ``peakmem_`` functions below). References ---------- .. [1]: https://asv.readthedocs.io/en/stable/writing_benchmarks.html#peak-memory """ pass def peakmem_phase_cross_correlation( self, ndims, image_size, upsample_factor, *args ): phase_cross_correlation( self.reference_image, self.shifted_image, upsample_factor=upsample_factor, space="fourier", )
PhaseCrossCorrelationRegistration
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/base_env.py
{ "start": 12769, "end": 17470 }
class ____(NamedTuple): """ A NamedTuple containing utility functions and information about the action spaces for a group of Agents under the same behavior. - num_continuous_actions is an int corresponding to the number of floats which constitute the action. - discrete_branch_sizes is a Tuple of int where each int corresponds to the number of discrete actions available to the agent on an independent action branch. """ continuous_size: int discrete_branches: Tuple[int, ...] def __eq__(self, other): return ( self.continuous_size == other.continuous_size and self.discrete_branches == other.discrete_branches ) def __str__(self): return f"Continuous: {self.continuous_size}, Discrete: {self.discrete_branches}" # For backwards compatibility def is_discrete(self) -> bool: """ Returns true if this Behavior uses discrete actions """ return self.discrete_size > 0 and self.continuous_size == 0 # For backwards compatibility def is_continuous(self) -> bool: """ Returns true if this Behavior uses continuous actions """ return self.discrete_size == 0 and self.continuous_size > 0 @property def discrete_size(self) -> int: """ Returns a an int corresponding to the number of discrete branches. """ return len(self.discrete_branches) def empty_action(self, n_agents: int) -> ActionTuple: """ Generates ActionTuple corresponding to an empty action (all zeros) for a number of agents. :param n_agents: The number of agents that will have actions generated """ _continuous = np.zeros((n_agents, self.continuous_size), dtype=np.float32) _discrete = np.zeros((n_agents, self.discrete_size), dtype=np.int32) return ActionTuple(continuous=_continuous, discrete=_discrete) def random_action(self, n_agents: int) -> ActionTuple: """ Generates ActionTuple corresponding to a random action (either discrete or continuous) for a number of agents. :param n_agents: The number of agents that will have actions generated """ _continuous = np.random.uniform( low=-1.0, high=1.0, size=(n_agents, self.continuous_size) ) _discrete = np.zeros((n_agents, self.discrete_size), dtype=np.int32) if self.discrete_size > 0: _discrete = np.column_stack( [ np.random.randint( 0, self.discrete_branches[i], # type: ignore size=(n_agents), dtype=np.int32, ) for i in range(self.discrete_size) ] ) return ActionTuple(continuous=_continuous, discrete=_discrete) def _validate_action( self, actions: ActionTuple, n_agents: int, name: str ) -> ActionTuple: """ Validates that action has the correct action dim for the correct number of agents and ensures the type. """ _expected_shape = (n_agents, self.continuous_size) if actions.continuous.shape != _expected_shape: raise UnityActionException( f"The behavior {name} needs a continuous input of dimension " f"{_expected_shape} for (<number of agents>, <action size>) but " f"received input of dimension {actions.continuous.shape}" ) _expected_shape = (n_agents, self.discrete_size) if actions.discrete.shape != _expected_shape: raise UnityActionException( f"The behavior {name} needs a discrete input of dimension " f"{_expected_shape} for (<number of agents>, <action size>) but " f"received input of dimension {actions.discrete.shape}" ) return actions @staticmethod def create_continuous(continuous_size: int) -> "ActionSpec": """ Creates an ActionSpec that is homogenously continuous """ return ActionSpec(continuous_size, ()) @staticmethod def create_discrete(discrete_branches: Tuple[int]) -> "ActionSpec": """ Creates an ActionSpec that is homogenously discrete """ return ActionSpec(0, discrete_branches) @staticmethod def create_hybrid( continuous_size: int, discrete_branches: Tuple[int] ) -> "ActionSpec": """ Creates a hybrid ActionSpace """ return ActionSpec(continuous_size, discrete_branches)
ActionSpec
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType8.py
{ "start": 225, "end": 463 }
class ____(Generic[T_A, T]): def __init__( self, p1: Type[T_A] = ClassA, p2: List[T] = [], # This should generate an error. p3: List[T_A] = [2], p4: List[T] = [2], ): pass
ClassB
python
getsentry__sentry
tests/sentry/utils/test_sdk.py
{ "start": 8920, "end": 10593 }
class ____(TestCase): @patch("sentry.utils.sdk.LEGACY_RESOLVER.resolve", return_value="/dogs/{name}/") def test_scope_has_correct_transaction(self, mock_resolve: MagicMock) -> None: mock_scope = Scope() mock_scope._transaction = "/dogs/{name}/" with patch("sentry.utils.sdk.sentry_sdk.get_current_scope", return_value=mock_scope): mismatch = check_current_scope_transaction(Request(HttpRequest())) assert mismatch is None @patch("sentry.utils.sdk.LEGACY_RESOLVER.resolve", return_value="/dogs/{name}/") def test_scope_has_wrong_transaction(self, mock_resolve: MagicMock) -> None: mock_scope = Scope() mock_scope._transaction = "/tricks/{trick_name}/" with patch("sentry.utils.sdk.sentry_sdk.get_current_scope", return_value=mock_scope): mismatch = check_current_scope_transaction(Request(HttpRequest())) assert mismatch == { "scope_transaction": "/tricks/{trick_name}/", "request_transaction": "/dogs/{name}/", } @patch("sentry.utils.sdk.LEGACY_RESOLVER.resolve", return_value="/dogs/{name}/") def test_custom_transaction_name(self, mock_resolve: MagicMock) -> None: with patch_isolation_scope() as mock_scope: mock_scope._transaction = "/tricks/{trick_name}/" mock_scope._transaction_info["source"] = "custom" mismatch = check_current_scope_transaction(Request(HttpRequest())) # custom transaction names shouldn't be flagged even if they don't match assert mismatch is None @patch("sentry_sdk.capture_exception")
CheckScopeTransactionTest
python
huggingface__transformers
src/transformers/models/yoso/modeling_yoso.py
{ "start": 39871, "end": 42687 }
class ____(YosoPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.yoso = YosoModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, config.num_labels) # 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, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple, TokenClassifierOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.yoso( 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] sequence_output = self.dropout(sequence_output) logits = self.classifier(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss() # Only keep active parts of the loss if attention_mask is not None: active_loss = attention_mask.view(-1) == 1 active_logits = logits.view(-1, self.num_labels) active_labels = torch.where( active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) loss = loss_fct(active_logits, active_labels) else: loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring
YosoForTokenClassification
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py
{ "start": 142475, "end": 143002 }
class ____(nn.Module): def __init__(self, dim, mult=4, dropout=0.0): super().__init__() inner_dim = int(dim * mult) self.ff = nn.ModuleList( [ nn.Linear(dim, inner_dim), nn.GELU(approximate="tanh"), nn.Dropout(dropout), nn.Linear(inner_dim, dim), ] ) def forward(self, hidden_states): for layer in self.ff: hidden_states = layer(hidden_states) return hidden_states
DiTMLP
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-ibm/llama_index/embeddings/ibm/base.py
{ "start": 548, "end": 8474 }
class ____(BaseEmbedding): """ IBM watsonx.ai embeddings. Example: `pip install llama-index-embeddings-ibm` ```python from llama_index.embeddings.ibm import WatsonxEmbeddings watsonx_llm = WatsonxEmbeddings( model_id="ibm/slate-125m-english-rtrvr", url="https://us-south.ml.cloud.ibm.com", apikey="*****", project_id="*****", ) ``` """ model_id: str = Field( default=DEFAULT_EMBED_MODEL, description="Type of model to use.", allow_mutation=False, ) truncate_input_tokens: Optional[int] = Field( default=None, description="Represents the maximum number of input tokens accepted.", ) project_id: Optional[str] = Field( default=None, description="ID of the Watson Studio project.", allow_mutation=False, ) space_id: Optional[str] = Field( default=None, description="ID of the Watson Studio space.", allow_mutation=False, ) url: Optional[SecretStr] = Field( default=None, description="Url to the IBM watsonx.ai for IBM Cloud or the IBM watsonx.ai software instance.", allow_mutation=False, ) apikey: Optional[SecretStr] = Field( default=None, description="API key to the IBM watsonx.ai for IBM Cloud or the IBM watsonx.ai software instance.", allow_mutation=False, ) token: Optional[SecretStr] = Field( default=None, description="Token to the IBM watsonx.ai software instance.", allow_mutation=False, ) password: Optional[SecretStr] = Field( default=None, description="Password to the IBM watsonx.ai software instance.", allow_mutation=False, ) username: Optional[SecretStr] = Field( default=None, description="Username to the IBM watsonx.ai software instance.", allow_mutation=False, ) instance_id: Optional[SecretStr] = Field( default=None, description="Instance_id of the IBM watsonx.ai software instance.", allow_mutation=False, deprecated="The `instance_id` parameter is deprecated and will no longer be utilized for logging to the IBM watsonx.ai software instance.", ) version: Optional[SecretStr] = Field( default=None, description="Version of the IBM watsonx.ai software instance.", allow_mutation=False, ) verify: Union[str, bool, None] = Field( default=None, description="""User can pass as verify one of following: the path to a CA_BUNDLE file the path of directory with certificates of trusted CAs True - default path to truststore will be taken False - no verification will be made""", allow_mutation=False, ) # Enabled by default since IBM watsonx SDK 1.1.2 but it can cause problems # in environments where long-running connections are not supported. persistent_connection: bool = Field( default=True, description="Use persistent connection" ) _embed_model: Embeddings = PrivateAttr() def __init__( self, model_id: str, truncate_input_tokens: Optional[int] = None, embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE, project_id: Optional[str] = None, space_id: Optional[str] = None, url: Optional[str] = None, apikey: Optional[str] = None, token: Optional[str] = None, password: Optional[str] = None, username: Optional[str] = None, version: Optional[str] = None, verify: Union[str, bool, None] = None, api_client: Optional[APIClient] = None, persistent_connection: bool = True, callback_manager: Optional[CallbackManager] = None, **kwargs: Any, ): callback_manager = callback_manager or CallbackManager([]) if isinstance(api_client, APIClient): project_id = api_client.default_project_id or project_id space_id = api_client.default_space_id or space_id creds = {} else: creds = resolve_watsonx_credentials( url=url, apikey=apikey, token=token, username=username, password=password, ) url = creds.get("url").get_secret_value() if creds.get("url") else None apikey = creds.get("apikey").get_secret_value() if creds.get("apikey") else None token = creds.get("token").get_secret_value() if creds.get("token") else None password = ( creds.get("password").get_secret_value() if creds.get("password") else None ) username = ( creds.get("username").get_secret_value() if creds.get("username") else None ) super().__init__( model_id=model_id, truncate_input_tokens=truncate_input_tokens, project_id=project_id, space_id=space_id, url=url, apikey=apikey, token=token, password=password, username=username, version=version, verify=verify, persistent_connection=persistent_connection, callback_manager=callback_manager, embed_batch_size=embed_batch_size, **kwargs, ) self._embed_model = Embeddings( model_id=model_id, params=self.params, credentials=( Credentials.from_dict( { key: value.get_secret_value() if value else None for key, value in self._get_credential_kwargs().items() }, _verify=self.verify, ) if creds else None ), project_id=self.project_id, space_id=self.space_id, api_client=api_client, persistent_connection=self.persistent_connection, ) class Config: validate_assignment = True @classmethod def class_name(cls) -> str: return "WatsonxEmbedding" def _get_credential_kwargs(self) -> Dict[str, SecretStr | None]: return { "url": self.url, "apikey": self.apikey, "token": self.token, "password": self.password, "username": self.username, "version": self.version, } @property def params(self) -> Dict[str, int] | None: return ( {"truncate_input_tokens": self.truncate_input_tokens} if self.truncate_input_tokens else None ) def _get_query_embedding(self, query: str) -> List[float]: """Get query embedding.""" return self._embed_model.embed_query(text=query, params=self.params) def _get_text_embedding(self, text: str) -> List[float]: """Get text embedding.""" return self._get_query_embedding(query=text) def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]: """Get text embeddings.""" return self._embed_model.embed_documents(texts=texts, params=self.params) ### Async methods # Asynchronous evaluation is not yet supported for watsonx.ai embeddings async def _aget_query_embedding(self, query: str) -> List[float]: """The asynchronous version of _get_query_embedding.""" return self._get_query_embedding(query) async def _aget_text_embedding(self, text: str) -> List[float]: """Asynchronously get text embedding.""" return self._get_text_embedding(text) async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]: """Asynchronously get text embeddings.""" return self._get_text_embeddings(texts)
WatsonxEmbeddings
python
ray-project__ray
rllib/connectors/module_to_env/listify_data_for_vector_env.py
{ "start": 503, "end": 3427 }
class ____(ConnectorV2): """Performs conversion from ConnectorV2-style format to env/episode insertion. Note: This is one of the default module-to-env ConnectorV2 pieces that are added automatically by RLlib into every module-to-env connector pipeline, unless `config.add_default_connectors_to_module_to_env_pipeline` is set to False. The default module-to-env connector pipeline is: [ GetActions, TensorToNumpy, UnBatchToIndividualItems, ModuleToAgentUnmapping, # only in multi-agent setups! RemoveSingleTsTimeRankFromBatch, [0 or more user defined ConnectorV2 pieces], NormalizeAndClipActions, ListifyDataForVectorEnv, ] Single agent case: Convert from: [col] -> [(episode_id,)] -> [list of items]. To: [col] -> [list of items]. Multi-agent case: Convert from: [col] -> [(episode_id, agent_id, module_id)] -> list of items. To: [col] -> [list of multi-agent dicts]. """ @override(ConnectorV2) def __call__( self, *, rl_module: RLModule, batch: Dict[str, Any], episodes: List[EpisodeType], explore: Optional[bool] = None, shared_data: Optional[dict] = None, **kwargs, ) -> Any: for column, column_data in batch.copy().items(): # Multi-agent case: Create lists of multi-agent dicts under each column. if isinstance(episodes[0], MultiAgentEpisode): # For each environment/episode one entry. new_column_data = [{} for _ in episodes] episode_map_structure = shared_data.get("old_episode_ids", {}) for key, value in batch[column].items(): assert len(value) == 1 eps_id, agent_id, module_id = key # Get the episode index that corresponds to the ID in the batch. # Note, the order in the `EnvRunner`s episode list needs to be # kept for each batch column. eps_id = episode_map_structure.get(eps_id, eps_id) eps_index = next( (i for i, eps in enumerate(episodes) if eps.id_ == eps_id), 0 ) new_column_data[eps_index][agent_id] = value[0] batch[column] = new_column_data # Single-agent case: Create simple lists under each column. else: batch[column] = [ d for key in batch[column].keys() for d in batch[column][key] ] # Batch actions for (single-agent) gym.vector.Env. # All other columns, leave listify'ed. if column in [Columns.ACTIONS_FOR_ENV, Columns.ACTIONS]: batch[column] = batch_fn(batch[column]) return batch
ListifyDataForVectorEnv
python
bokeh__bokeh
src/bokeh/core/property/datetime.py
{ "start": 2474, "end": 3918 }
class ____(Property[str | datetime.date | datetime.datetime]): """ Accept ISO format Datetime values. """ def __init__(self, default: Init[str | datetime.date | datetime.datetime] = Undefined, *, help: str | None = None) -> None: super().__init__(default=default, help=help) def transform(self, value: Any) -> Any: value = super().transform(value) if isinstance(value, str): value = datetime.datetime.fromisoformat(value) # Handled by serialization in protocol.py for now, except for Date if isinstance(value, datetime.date): value = convert_date_to_datetime(value) return value def validate(self, value: Any, detail: bool = True) -> None: super().validate(value, detail) if is_datetime_type(value): return if isinstance(value, datetime.date): return if Datetime.is_timestamp(value): return if isinstance(value, str): try: datetime.datetime.fromisoformat(value).date() return except Exception: pass msg = "" if not detail else f"Expected a date, datetime object, or timestamp, got {value!r}" raise ValueError(msg) @staticmethod def is_timestamp(value: Any) -> bool: return isinstance(value, (float, *bokeh_integer_types)) and not isinstance(value, bool)
Datetime
python
getsentry__sentry
src/sentry/db/router.py
{ "start": 8827, "end": 9442 }
class ____(SiloRouter): """Silo router used in CI""" secondary_db_models = { "sentry_monitor", "sentry_monitorcheckin", "sentry_monitorenvironment", "sentry_monitorincident", "sentry_monitorlocation", "sentry_monitorenvbrokendetection", } def _resolve_silo_connection(self, silo_modes: Iterable[SiloMode], table: str) -> str | None: connection = super()._resolve_silo_connection(silo_modes=silo_modes, table=table) if table in self.secondary_db_models: return "secondary" return connection
TestSiloMultiDatabaseRouter
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_header02.py
{ "start": 315, "end": 946 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("header02.xlsx") self.ignore_elements = { "xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"] } def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_header("&L&P", {"align_with_margins": False}) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
django-compressor__django-compressor
compressor/offline/django.py
{ "start": 3819, "end": 6128 }
class ____: def __init__(self, charset): self.charset = charset def parse(self, template_name): try: return get_template(template_name).template except template.TemplateSyntaxError as e: raise TemplateSyntaxError(str(e)) except template.TemplateDoesNotExist as e: raise TemplateDoesNotExist(str(e)) def process_template(self, template, context): return True def get_init_context(self, offline_context): return offline_context def process_node(self, template, context, node): pass def render_nodelist(self, template, context, node): context.template = template return node.nodelist.render(context) def render_node(self, template, context, node): return node.render(context, forced=True) def get_nodelist(self, node, original, context=None): if isinstance(node, ExtendsNode): try: if context is None: context = Context() context.template = original return handle_extendsnode(node, context) except template.TemplateSyntaxError as e: raise TemplateSyntaxError(str(e)) except template.TemplateDoesNotExist as e: raise TemplateDoesNotExist(str(e)) # Check if node is an ```if``` switch with true and false branches nodelist = [] if isinstance(node, Node): for attr in node.child_nodelists: # see https://github.com/django-compressor/django-compressor/pull/825 # and linked issues/PRs for a discussion on the `None) or []` part nodelist += getattr(node, attr, None) or [] else: nodelist = getattr(node, "nodelist", []) return nodelist def walk_nodes(self, node, original=None, context=None): if original is None: original = node for node in self.get_nodelist(node, original, context): if isinstance(node, CompressorNode) and node.is_offline_compression_enabled( forced=True ): yield node else: for node in self.walk_nodes(node, original, context): yield node
DjangoParser
python
tensorflow__tensorflow
tensorflow/compiler/mlir/quantization/tensorflow/python/representative_dataset_test.py
{ "start": 9847, "end": 10214 }
class ____(test.TestCase): """Test cases for RepresentativeDatasetSaver.""" def test_save_raises_error(self): saver = repr_dataset.RepresentativeDatasetSaver() repr_ds = {'serving_default': []} with self.assertRaisesRegex( NotImplementedError, 'Method "save" is not implemented.' ): saver.save(repr_ds)
RepresentativeDatasetSaverTest
python
ray-project__ray
rllib/utils/exploration/stochastic_sampling.py
{ "start": 637, "end": 5427 }
class ____(Exploration): """An exploration that simply samples from a distribution. The sampling can be made deterministic by passing explore=False into the call to `get_exploration_action`. Also allows for scheduled parameters for the distributions, such as lowering stddev, temperature, etc.. over time. """ def __init__( self, action_space: gym.spaces.Space, *, framework: str, model: ModelV2, random_timesteps: int = 0, **kwargs ): """Initializes a StochasticSampling Exploration object. Args: action_space: The gym action space used by the environment. framework: One of None, "tf", "torch". model: The ModelV2 used by the owning Policy. random_timesteps: The number of timesteps for which to act completely randomly. Only after this number of timesteps, actual samples will be drawn to get exploration actions. """ assert framework is not None super().__init__(action_space, model=model, framework=framework, **kwargs) # Create the Random exploration module (used for the first n # timesteps). self.random_timesteps = random_timesteps self.random_exploration = Random( action_space, model=self.model, framework=self.framework, **kwargs ) # The current timestep value (tf-var or python int). self.last_timestep = get_variable( np.array(0, np.int64), framework=self.framework, tf_name="timestep", dtype=np.int64, ) @override(Exploration) def get_exploration_action( self, *, action_distribution: ActionDistribution, timestep: Optional[Union[int, TensorType]] = None, explore: bool = True ): if self.framework == "torch": return self._get_torch_exploration_action( action_distribution, timestep, explore ) else: return self._get_tf_exploration_action_op( action_distribution, timestep, explore ) def _get_tf_exploration_action_op(self, action_dist, timestep, explore): ts = self.last_timestep + 1 stochastic_actions = tf.cond( pred=tf.convert_to_tensor(ts < self.random_timesteps), true_fn=lambda: ( self.random_exploration.get_tf_exploration_action_op( action_dist, explore=True )[0] ), false_fn=lambda: action_dist.sample(), ) deterministic_actions = action_dist.deterministic_sample() action = tf.cond( tf.constant(explore) if isinstance(explore, bool) else explore, true_fn=lambda: stochastic_actions, false_fn=lambda: deterministic_actions, ) logp = tf.cond( tf.math.logical_and( explore, tf.convert_to_tensor(ts >= self.random_timesteps) ), true_fn=lambda: action_dist.sampled_action_logp(), false_fn=functools.partial(zero_logps_from_actions, deterministic_actions), ) # Increment `last_timestep` by 1 (or set to `timestep`). if self.framework == "tf2": self.last_timestep.assign_add(1) return action, logp else: assign_op = ( tf1.assign_add(self.last_timestep, 1) if timestep is None else tf1.assign(self.last_timestep, timestep) ) with tf1.control_dependencies([assign_op]): return action, logp def _get_torch_exploration_action( self, action_dist: ActionDistribution, timestep: Union[TensorType, int], explore: Union[TensorType, bool], ): # Set last timestep or (if not given) increase by one. self.last_timestep = ( timestep if timestep is not None else self.last_timestep + 1 ) # Apply exploration. if explore: # Random exploration phase. if self.last_timestep < self.random_timesteps: action, logp = self.random_exploration.get_torch_exploration_action( action_dist, explore=True ) # Take a sample from our distribution. else: action = action_dist.sample() logp = action_dist.sampled_action_logp() # No exploration -> Return deterministic actions. else: action = action_dist.deterministic_sample() logp = torch.zeros_like(action_dist.sampled_action_logp()) return action, logp
StochasticSampling
python
py-pdf__pypdf
pypdf/_protocols.py
{ "start": 200, "end": 885 }
class ____(Protocol): indirect_reference: Any def clone( self, pdf_dest: Any, force_duplicate: bool = False, ignore_fields: Union[tuple[str, ...], list[str], None] = (), ) -> Any: ... # pragma: no cover def _reference_clone(self, clone: Any, pdf_dest: Any) -> Any: ... # pragma: no cover def get_object(self) -> Optional["PdfObjectProtocol"]: ... # pragma: no cover def hash_value(self) -> bytes: ... # pragma: no cover def write_to_stream( self, stream: StreamType, encryption_key: Union[None, str, bytes] = None ) -> None: ... # pragma: no cover
PdfObjectProtocol
python
astropy__astropy
astropy/time/formats.py
{ "start": 34286, "end": 35085 }
class ____(TimeFromEpoch): """GPS time: seconds from 1980-01-06 00:00:00 UTC For example, 630720013.0 is midnight on January 1, 2000. Notes ----- This implementation is strictly a representation of the number of seconds (including leap seconds) since midnight UTC on 1980-01-06. GPS can also be considered as a time scale which is ahead of TAI by a fixed offset (to within about 100 nanoseconds). For details, see https://www.usno.navy.mil/USNO/time/gps/usno-gps-time-transfer """ name = "gps" unit = 1.0 / erfa.DAYSEC # in days (1 day == 86400 seconds) epoch_val = "1980-01-06 00:00:19" # above epoch is the same as Time('1980-01-06 00:00:00', scale='utc').tai epoch_val2 = None epoch_scale = "tai" epoch_format = "iso"
TimeGPS
python
kubernetes-client__python
kubernetes/client/models/v1_endpoint_slice.py
{ "start": 383, "end": 10586 }
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 = { 'address_type': 'str', 'api_version': 'str', 'endpoints': 'list[V1Endpoint]', 'kind': 'str', 'metadata': 'V1ObjectMeta', 'ports': 'list[DiscoveryV1EndpointPort]' } attribute_map = { 'address_type': 'addressType', 'api_version': 'apiVersion', 'endpoints': 'endpoints', 'kind': 'kind', 'metadata': 'metadata', 'ports': 'ports' } def __init__(self, address_type=None, api_version=None, endpoints=None, kind=None, metadata=None, ports=None, local_vars_configuration=None): # noqa: E501 """V1EndpointSlice - 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._address_type = None self._api_version = None self._endpoints = None self._kind = None self._metadata = None self._ports = None self.discriminator = None self.address_type = address_type if api_version is not None: self.api_version = api_version self.endpoints = endpoints if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata if ports is not None: self.ports = ports @property def address_type(self): """Gets the address_type of this V1EndpointSlice. # noqa: E501 addressType specifies the type of address carried by this EndpointSlice. All addresses in this slice must be the same type. This field is immutable after creation. The following address types are currently supported: * IPv4: Represents an IPv4 Address. * IPv6: Represents an IPv6 Address. * FQDN: Represents a Fully Qualified Domain Name. (Deprecated) The EndpointSlice controller only generates, and kube-proxy only processes, slices of addressType \"IPv4\" and \"IPv6\". No semantics are defined for the \"FQDN\" type. # noqa: E501 :return: The address_type of this V1EndpointSlice. # noqa: E501 :rtype: str """ return self._address_type @address_type.setter def address_type(self, address_type): """Sets the address_type of this V1EndpointSlice. addressType specifies the type of address carried by this EndpointSlice. All addresses in this slice must be the same type. This field is immutable after creation. The following address types are currently supported: * IPv4: Represents an IPv4 Address. * IPv6: Represents an IPv6 Address. * FQDN: Represents a Fully Qualified Domain Name. (Deprecated) The EndpointSlice controller only generates, and kube-proxy only processes, slices of addressType \"IPv4\" and \"IPv6\". No semantics are defined for the \"FQDN\" type. # noqa: E501 :param address_type: The address_type of this V1EndpointSlice. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and address_type is None: # noqa: E501 raise ValueError("Invalid value for `address_type`, must not be `None`") # noqa: E501 self._address_type = address_type @property def api_version(self): """Gets the api_version of this V1EndpointSlice. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1EndpointSlice. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1EndpointSlice. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :param api_version: The api_version of this V1EndpointSlice. # noqa: E501 :type: str """ self._api_version = api_version @property def endpoints(self): """Gets the endpoints of this V1EndpointSlice. # noqa: E501 endpoints is a list of unique endpoints in this slice. Each slice may include a maximum of 1000 endpoints. # noqa: E501 :return: The endpoints of this V1EndpointSlice. # noqa: E501 :rtype: list[V1Endpoint] """ return self._endpoints @endpoints.setter def endpoints(self, endpoints): """Sets the endpoints of this V1EndpointSlice. endpoints is a list of unique endpoints in this slice. Each slice may include a maximum of 1000 endpoints. # noqa: E501 :param endpoints: The endpoints of this V1EndpointSlice. # noqa: E501 :type: list[V1Endpoint] """ if self.local_vars_configuration.client_side_validation and endpoints is None: # noqa: E501 raise ValueError("Invalid value for `endpoints`, must not be `None`") # noqa: E501 self._endpoints = endpoints @property def kind(self): """Gets the kind of this V1EndpointSlice. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1EndpointSlice. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1EndpointSlice. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1EndpointSlice. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this V1EndpointSlice. # noqa: E501 :return: The metadata of this V1EndpointSlice. # noqa: E501 :rtype: V1ObjectMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1EndpointSlice. :param metadata: The metadata of this V1EndpointSlice. # noqa: E501 :type: V1ObjectMeta """ self._metadata = metadata @property def ports(self): """Gets the ports of this V1EndpointSlice. # noqa: E501 ports specifies the list of network ports exposed by each endpoint in this slice. Each port must have a unique name. Each slice may include a maximum of 100 ports. Services always have at least 1 port, so EndpointSlices generated by the EndpointSlice controller will likewise always have at least 1 port. EndpointSlices used for other purposes may have an empty ports list. # noqa: E501 :return: The ports of this V1EndpointSlice. # noqa: E501 :rtype: list[DiscoveryV1EndpointPort] """ return self._ports @ports.setter def ports(self, ports): """Sets the ports of this V1EndpointSlice. ports specifies the list of network ports exposed by each endpoint in this slice. Each port must have a unique name. Each slice may include a maximum of 100 ports. Services always have at least 1 port, so EndpointSlices generated by the EndpointSlice controller will likewise always have at least 1 port. EndpointSlices used for other purposes may have an empty ports list. # noqa: E501 :param ports: The ports of this V1EndpointSlice. # noqa: E501 :type: list[DiscoveryV1EndpointPort] """ self._ports = ports 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, V1EndpointSlice): 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, V1EndpointSlice): return True return self.to_dict() != other.to_dict()
V1EndpointSlice
python
gevent__gevent
src/gevent/select.py
{ "start": 2071, "end": 7332 }
class ____(object): __slots__ = () @staticmethod def _make_callback(ready_collection, event, mask): def cb(fd, watcher): ready_collection.append(fd) watcher.close() event.set() cb.mask = mask return cb @classmethod def _make_watchers(cls, watchers, *fd_cb): loop = get_hub().loop io = loop.io MAXPRI = loop.MAXPRI for fdlist, callback in fd_cb: for fd in fdlist: watcher = io(get_fileno(fd), callback.mask) watcher.priority = MAXPRI watchers.append(watcher) watcher.start(callback, fd, watcher) @staticmethod def _closeall(watchers): for watcher in watchers: watcher.stop() watcher.close() del watchers[:] def select(self, rlist, wlist, timeout): watchers = [] # read and write are the collected ready objects, accumulated # by the callback. Note that we could get spurious callbacks # if the socket is closed while we're blocked. We can't easily # detect that (libev filters the events passed so we can't # pass arbitrary events). After an iteration of polling for # IO, libev will invoke all the pending IO watchers, and then # any newly added (fed) events, and then we will invoke added # callbacks. With libev 4.27+ and EV_VERIFY, it's critical to # close our watcher immediately once we get an event. That # could be the close event (coming just before the actual # close happens), and once the FD is closed, libev will abort # the process if we stop the watcher. read = [] write = [] event = Event() add_read = self._make_callback(read, event, _EV_READ) add_write = self._make_callback(write, event, _EV_WRITE) try: self._make_watchers(watchers, (rlist, add_read), (wlist, add_write)) event.wait(timeout=timeout) return read, write, [] finally: self._closeall(watchers) def select(rlist, wlist, xlist, timeout=None): # pylint:disable=unused-argument """An implementation of :obj:`select.select` that blocks only the current greenlet. .. caution:: *xlist* is ignored. .. versionchanged:: 1.2a1 Raise a :exc:`ValueError` if timeout is negative. This matches Python 3's behaviour (Python 2 would raise a ``select.error``). Previously gevent had undefined behaviour. .. versionchanged:: 1.2a1 Raise an exception if any of the file descriptors are invalid. """ if timeout is not None and timeout < 0: # Raise an error like the real implementation; which error # depends on the version. Python 3, where select.error is OSError, # raises a ValueError (which makes sense). Older pythons raise # the error from the select syscall...but we don't actually get there. # We choose to just raise the ValueError as it makes more sense and is # forward compatible raise ValueError("timeout must be non-negative") # since rlist and wlist can be any iterable we will have to first # copy them into a list, so we can use them in both _original_select # and in SelectResult.select. We don't need to do it for xlist, since # that one will only be passed into _original_select rlist = rlist if isinstance(rlist, (list, tuple)) else list(rlist) wlist = wlist if isinstance(wlist, (list, tuple)) else list(wlist) # First, do a poll with the original select system call. This is # the most efficient way to check to see if any of the file # descriptors have previously been closed and raise the correct # corresponding exception. (Because libev tends to just return # them as ready, or, if built with EV_VERIFY >= 2 and libev >= # 4.27, crash the process. And libuv also tends to crash the # process.) # # We accept the *xlist* here even though we can't # below because this is all about error handling. # Since Python 3.5, we don't need to worry about EINTR handling. sel_results = _original_select(rlist, wlist, xlist, 0) if sel_results[0] or sel_results[1] or sel_results[2] or (timeout is not None and timeout == 0): # If we actually had stuff ready, go ahead and return it. No need # to go through the trouble of doing our own stuff. # Likewise, if the timeout is 0, we already did a 0 timeout # select and we don't need to do it again. Note that in libuv, # zero duration timers may be called immediately, without # cycling the event loop at all. 2.7/test_telnetlib.py "hangs" # calling zero-duration timers if we go to the loop here. # However, because this is typically a place where scheduling switches # can occur, we need to make sure that's still the case; otherwise a single # consumer could monopolize the thread. (shows up in test_ftplib.) _g_sleep() return sel_results result = SelectResult() return result.select(rlist, wlist, timeout)
SelectResult
python
pallets__werkzeug
src/werkzeug/debug/__init__.py
{ "start": 3589, "end": 6754 }
class ____: """Helper class so that we can reuse the frame console code for the standalone console. """ def __init__(self, namespace: dict[str, t.Any]): self.console = Console(namespace) self.id = 0 def eval(self, code: str) -> t.Any: return self.console.eval(code) def get_pin_and_cookie_name( app: WSGIApplication, ) -> tuple[str, str] | tuple[None, None]: """Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`. Second item in the resulting tuple is the cookie name for remembering. """ pin = os.environ.get("WERKZEUG_DEBUG_PIN") rv = None num = None # Pin was explicitly disabled if pin == "off": return None, None # Pin was provided explicitly if pin is not None and pin.replace("-", "").isdecimal(): # If there are separators in the pin, return it directly if "-" in pin: rv = pin else: num = pin modname = getattr(app, "__module__", t.cast(object, app).__class__.__module__) username: str | None try: # getuser imports the pwd module, which does not exist in Google # App Engine. It may also raise a KeyError if the UID does not # have a username, such as in Docker. username = getpass.getuser() # Python >= 3.13 only raises OSError except (ImportError, KeyError, OSError): username = None mod = sys.modules.get(modname) # This information only exists to make the cookie unique on the # computer, not as a security feature. probably_public_bits = [ username, modname, getattr(app, "__name__", type(app).__name__), getattr(mod, "__file__", None), ] # This information is here to make it harder for an attacker to # guess the cookie name. They are unlikely to be contained anywhere # within the unauthenticated debug page. private_bits = [str(uuid.getnode()), get_machine_id()] h = hashlib.sha1() for bit in chain(probably_public_bits, private_bits): if not bit: continue if isinstance(bit, str): bit = bit.encode() h.update(bit) h.update(b"cookiesalt") cookie_name = f"__wzd{h.hexdigest()[:20]}" # If we need to generate a pin we salt it a bit more so that we don't # end up with the same value and generate out 9 digits if num is None: h.update(b"pinsalt") num = f"{int(h.hexdigest(), 16):09d}"[:9] # Format the pincode in groups of digits for easier remembering if # we don't have a result yet. if rv is None: for group_size in 5, 4, 3: if len(num) % group_size == 0: rv = "-".join( num[x : x + group_size].rjust(group_size, "0") for x in range(0, len(num), group_size) ) break else: rv = num return rv, cookie_name
_ConsoleFrame
python
rapidsai__cudf
python/dask_cudf/dask_cudf/_expr/groupby.py
{ "start": 12636, "end": 13914 }
class ____(GroupbyAggregation): @functools.cached_property def spec_info(self): return _get_spec_info(self) @functools.cached_property def _meta(self): return _get_meta(self) def _lower(self): return DecomposableCudfGroupbyAgg( self.frame, self.arg, self.observed, self.dropna, self.split_every, self.split_out, self.sort, self.shuffle_method, self._slice, *self.by, ) def _maybe_get_custom_expr( gb, aggs, split_every=None, split_out=None, shuffle_method=None, **kwargs, ): if kwargs: # Unsupported key-word arguments return None if not hasattr(gb.obj._meta, "to_pandas"): # Not cuDF-backed data return None _aggs = _redirect_aggs(aggs) if not _aggs_optimized(_aggs, OPTIMIZED_AGGS): # One or more aggregations are unsupported return None return CudfGroupbyAgg( gb.obj.expr, _aggs, gb.observed, gb.dropna, split_every, split_out, gb.sort, shuffle_method, gb._slice, *gb.by, ) ## ## Custom groupby classes ##
CudfGroupbyAgg
python
catalyst-team__catalyst
catalyst/contrib/layers/lama.py
{ "start": 886, "end": 1301 }
class ____(nn.Module): """@TODO: Docs. Contribution is welcome.""" def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor: """Forward call.""" if mask is not None: x_mask = (~mask.bool()).float() * (-x.max()).float() x = torch.sum(x + x_mask, dim=1, keepdim=True) x_out = x.max(1, keepdim=True)[0] return x_out
TemporalMaxPooling
python
ethereum__web3.py
web3/exceptions.py
{ "start": 2534, "end": 2692 }
class ____(Web3Exception): """ Raised when a caller provides an Ethereum Name Service name that does not resolve to an address. """
NameNotFound
python
has2k1__plotnine
plotnine/facets/strips.py
{ "start": 475, "end": 4552 }
class ____: """ A strip This class exists to have in one place all that is required to draw strip text onto an axes. As Matplotlib does not have a layout manager that makes it easy to adorn an axes with artists, we have to compute the space required for the text and the background strip on which it is drawn. This is very finicky and fails once the facets become complicated. """ position: StripPosition label_info: strip_label_details def __init__( self, vars: Sequence[str], layout_info: layout_details, facet: facet, ax: Axes, position: StripPosition, ): self.vars = vars self.ax = ax self.position = position self.facet = facet self.figure = facet.figure self.theme = facet.theme self.layout_info = layout_info label_info = strip_label_details.make(layout_info, vars, position) self.label_info = facet.labeller(label_info) def get_draw_info(self) -> strip_draw_info: """ Get information required to draw strips Returns ------- out : A structure with all the coordinates (x, y) required to draw the strip text and the background box (box_x, box_y, box_width, box_height). """ theme = self.theme position = self.position if position == "top": # The x & y values are just starting locations # The final location is determined by the layout manager. bg_y = 1 ha = theme.getp(("strip_text_x", "ha"), "center") va = theme.getp(("strip_text_x", "va"), "center") rotation = theme.getp(("strip_text_x", "rotation")) bg_height = 0 # Determined by the text size margin = theme.getp(("strip_text_x", "margin")).to("lines") strip_align = theme.getp("strip_align_x") # x & width properties of the background slide and # shrink the strip horizontally. bg_x = theme.getp(("strip_text_x", "x"), 0) bg_width = theme.getp(("strip_background_x", "width"), 1) elif position == "right": # The x & y values are just starting locations # The final location is determined by the layout manager. bg_x = 1 ha = theme.getp(("strip_text_y", "ha"), "center") va = theme.getp(("strip_text_y", "va"), "center") rotation = theme.getp(("strip_text_y", "rotation")) bg_width = 0 # Determine by the text height margin = theme.getp(("strip_text_y", "margin")).to("lines") strip_align = theme.getp("strip_align_y") # y & height properties of the background slide and # shrink the strip vertically. bg_y = theme.getp(("strip_text_y", "y"), 0) bg_height = theme.getp(("strip_background_y", "height"), 1) else: raise ValueError(f"Unknown position for strip text: {position!r}") return strip_draw_info( bg_x=bg_x, bg_y=bg_y, ha=ha, va=va, bg_width=bg_width, bg_height=bg_height, margin=margin, strip_align=strip_align, position=position, label=self.label_info.text(), ax=self.ax, rotation=rotation, layout=self.layout_info, ) def draw(self): """ Create a background patch and put a label on it """ from .._mpl.text import StripText targets = self.theme.targets draw_info = self.get_draw_info() text = StripText(draw_info) rect = text.patch self.figure.add_artist(text) if draw_info.position == "right": targets.strip_background_y.append(rect) targets.strip_text_y.append(text) else: targets.strip_background_x.append(rect) targets.strip_text_x.append(text)
strip
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/NonUniformImage.py
{ "start": 207, "end": 5481 }
class ____(GraphicsObject): """ **Bases:** :class:`GraphicsObject <pyqtgraph.GraphicsObject>` GraphicsObject displaying an image with non-uniform sample points. It's commonly used to display 2-d or slices of higher dimensional data that have a regular but non-uniform grid e.g. measurements or simulation results. """ def __init__(self, x, y, z, border=None): GraphicsObject.__init__(self) # convert to numpy arrays x = np.asarray(x, dtype=np.float64) y = np.asarray(y, dtype=np.float64) z = np.asarray(z, dtype=np.float64) if x.ndim != 1 or y.ndim != 1: raise Exception("x and y must be 1-d arrays.") if np.any(np.diff(x) < 0) or np.any(np.diff(y) < 0): raise Exception("The values in x and y must be monotonically increasing.") if len(z.shape) != 2 or z.shape != (x.size, y.size): raise Exception("The length of x and y must match the shape of z.") # default colormap (black - white) self.cmap = ColorMap(None, [0.0, 1.0]) self.lut = self.cmap.getLookupTable(nPts=256) self.data = (x, y, z) self.levels = None self.border = border self.picture = None self.update() def setLookupTable(self, lut, update=True, **kwargs): self.cmap = None # invalidate since no longer consistent with lut self.lut = lut self.picture = None if update: self.update() def setColorMap(self, cmap): self.setLookupTable(cmap.getLookupTable(nPts=256), update=True) self.cmap = cmap def getHistogram(self, **kwds): """Returns x and y arrays containing the histogram values for the current image. For an explanation of the return format, see numpy.histogram(). """ z = self.data[2] z = z[np.isfinite(z)] hist = np.histogram(z, **kwds) return hist[1][:-1], hist[0] def setLevels(self, levels): self.levels = levels self.picture = None self.update() def getLevels(self): if self.levels is None: z = self.data[2] z = z[np.isfinite(z)] self.levels = z.min(), z.max() return self.levels def generatePicture(self): x, y, z = self.data # pad x and y so that we don't need to special-case the edges x = np.pad(x, 1, mode='edge') y = np.pad(y, 1, mode='edge') x = (x[:-1] + x[1:]) / 2 y = (y[:-1] + y[1:]) / 2 X, Y = np.meshgrid(x[:-1], y[:-1], indexing='ij') W, H = np.meshgrid(np.diff(x), np.diff(y), indexing='ij') Z = z # get colormap if callable(self.lut): lut = self.lut(z) else: lut = self.lut if lut is None: # lut can be None for a few reasons: # 1) self.lut(z) can also return None on error # 2) if a trivial gradient is being used, HistogramLUTItem calls # setLookupTable(None) as an optimization for ImageItem cmap = ColorMap(None, [0.0, 1.0]) lut = cmap.getLookupTable(nPts=256) # normalize and quantize mn, mx = self.getLevels() rng = mx - mn if rng == 0: rng = 1 scale = len(lut) / rng Z = fn.rescaleData(Z, scale, mn, dtype=int, clip=(0, len(lut)-1)) # replace nans positions with invalid lut index invalid_coloridx = len(lut) Z[np.isnan(z)] = invalid_coloridx # pre-allocate to the largest array needed color_indices, counts = np.unique(Z, return_counts=True) rectarray = Qt.internals.PrimitiveArray(QtCore.QRectF, 4) rectarray.resize(counts.max()) # sorted_indices effectively groups together the # (flattened) indices of the same coloridx together. sorted_indices = np.argsort(Z, axis=None) X = X.ravel() Y = Y.ravel() W = W.ravel() H = H.ravel() self.picture = QtGui.QPicture() painter = QtGui.QPainter(self.picture) painter.setPen(fn.mkPen(None)) # draw the tiles grouped by coloridx offset = 0 for coloridx, cnt in zip(color_indices, counts): if coloridx == invalid_coloridx: continue indices = sorted_indices[offset:offset+cnt] offset += cnt rectarray.resize(cnt) memory = rectarray.ndarray() memory[:,0] = X[indices] memory[:,1] = Y[indices] memory[:,2] = W[indices] memory[:,3] = H[indices] brush = fn.mkBrush(lut[coloridx]) painter.setBrush(brush) painter.drawRects(*rectarray.drawargs()) if self.border is not None: painter.setPen(self.border) painter.setBrush(fn.mkBrush(None)) painter.drawRect(self.boundingRect()) painter.end() def paint(self, p, *args): if self.picture is None: self.generatePicture() p.drawPicture(0, 0, self.picture) def boundingRect(self): x, y, _ = self.data return QtCore.QRectF(x[0], y[0], x[-1]-x[0], y[-1]-y[0])
NonUniformImage
python
tensorflow__tensorflow
tensorflow/compiler/tests/xla_ops_test.py
{ "start": 1572, "end": 29248 }
class ____(xla_test.XLATestCase, parameterized.TestCase): def _assertOpOutputMatchesExpected( self, op, args, expected, equality_fn=None ): with self.session() as session: with self.test_scope(): placeholders = [ array_ops.placeholder(dtypes.as_dtype(arg.dtype), arg.shape) for arg in args ] feeds = {placeholders[i]: args[i] for i in range(0, len(args))} output = op(*placeholders) result = session.run(output, feeds) if not equality_fn: equality_fn = lambda x, y: self.assertAllClose(x, y, rtol=1e-3) equality_fn(result, expected) def testAdd(self): if xla_test.test.is_built_with_rocm(): self.skipTest('Broken with rocm') for dtype in self.numeric_types: self._assertOpOutputMatchesExpected( xla.add, args=( np.array([1, 2, 3], dtype=dtype), np.array([4, 5, 6], dtype=dtype), ), expected=np.array([5, 7, 9], dtype=dtype), ) self._assertOpOutputMatchesExpected( lambda x, y: xla.add(x, y, broadcast_dims=(0,)), args=( np.array([[1, 2], [3, 4]], dtype=dtype), np.array([7, 11], dtype=dtype), ), expected=np.array([[8, 9], [14, 15]], dtype=dtype), ) self._assertOpOutputMatchesExpected( lambda x, y: xla.add(x, y, broadcast_dims=(1,)), args=( np.array([[1, 2], [3, 4]], dtype=dtype), np.array([7, 11], dtype=dtype), ), expected=np.array([[8, 13], [10, 15]], dtype=dtype), ) def testBroadcast(self): for dtype in self.numeric_types: v = np.arange(4, dtype=np.int32).astype(dtype).reshape([2, 2]) self._assertOpOutputMatchesExpected( lambda x: xla.broadcast(x, (7, 42)), args=(v,), expected=np.tile(v, (7, 42, 1, 1)), ) @test_util.disable_mlir_bridge('Not supported yet') def testGather(self): operand = np.arange(10, dtype=np.int32).reshape([2, 5]) start_indices = np.array([2], np.int32) slice_sizes = np.array([1, 3], np.int32) def gather(operand, start_indices): dimension_numbers = xla_data_pb2.GatherDimensionNumbers() dimension_numbers.offset_dims.extend([1]) dimension_numbers.collapsed_slice_dims.extend([0]) dimension_numbers.start_index_map.extend([0]) dimension_numbers.index_vector_dim = 1 return xla.gather(operand, start_indices, dimension_numbers, slice_sizes) self._assertOpOutputMatchesExpected( gather, args=(operand, start_indices), expected=np.array([[5, 6, 7]]) ) def testShiftRightLogical(self): self._assertOpOutputMatchesExpected( xla.shift_right_logical, args=(np.array([-1, 16], dtype=np.int32), np.int32(4)), expected=np.array([0x0FFFFFFF, 1], dtype=np.int32), ) self._assertOpOutputMatchesExpected( xla.shift_right_logical, args=(np.array([0xFFFFFFFF, 16], dtype=np.uint32), np.uint32(4)), expected=np.array([0x0FFFFFFF, 1], dtype=np.uint32), ) def testShiftRightArithmetic(self): self._assertOpOutputMatchesExpected( xla.shift_right_arithmetic, args=(np.array([-1, 16], dtype=np.int32), np.int32(4)), expected=np.array([-1, 1], dtype=np.int32), ) self._assertOpOutputMatchesExpected( xla.shift_right_arithmetic, args=(np.array([0xFFFFFFFF, 16], dtype=np.uint32), np.uint32(4)), expected=np.array([0xFFFFFFFF, 1], dtype=np.uint32), ) PRECISION_VALUES = ( None, xla_data_pb2.PrecisionConfig.DEFAULT, xla_data_pb2.PrecisionConfig.HIGH, xla_data_pb2.PrecisionConfig.HIGHEST, ) @parameterized.parameters(*PRECISION_VALUES) def testConv(self, precision): for dtype in set(self.float_types).intersection( set([dtypes.bfloat16.as_numpy_dtype, np.float32]) ): def conv_1d_fn(lhs, rhs): dnums = xla_data_pb2.ConvolutionDimensionNumbers() num_spatial_dims = 1 dnums.input_batch_dimension = 0 dnums.input_feature_dimension = 1 dnums.output_batch_dimension = 0 dnums.output_feature_dimension = 1 dnums.kernel_output_feature_dimension = 0 dnums.kernel_input_feature_dimension = 1 dnums.input_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) dnums.kernel_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) dnums.output_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) precision_config = None if precision: precision_config = xla_data_pb2.PrecisionConfig() precision_config.operand_precision.extend([precision, precision]) return xla.conv( lhs, rhs, window_strides=(1,), padding=((2, 1),), lhs_dilation=(1,), rhs_dilation=(2,), dimension_numbers=dnums, precision_config=precision_config, ) self._assertOpOutputMatchesExpected( conv_1d_fn, args=( np.array([[[3, 4, 5, 6]]], dtype=dtype), np.array([[[-2, -3]]], dtype=dtype), ), expected=np.array([[[-9, -12, -21, -26, -10]]], dtype=dtype), ) def testConvPreferredElementType(self): dtype = np.float16 preferred_element_type = np.float32 def conv_1d_fn(lhs, rhs): dnums = xla_data_pb2.ConvolutionDimensionNumbers() num_spatial_dims = 1 dnums.input_batch_dimension = 0 dnums.input_feature_dimension = 1 dnums.output_batch_dimension = 0 dnums.output_feature_dimension = 1 dnums.kernel_output_feature_dimension = 0 dnums.kernel_input_feature_dimension = 1 dnums.input_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) dnums.kernel_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) dnums.output_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) precision_config = None return xla.conv( lhs, rhs, window_strides=(1,), padding=((2, 1),), lhs_dilation=(1,), rhs_dilation=(2,), dimension_numbers=dnums, precision_config=precision_config, preferred_element_type=preferred_element_type, ) self._assertOpOutputMatchesExpected( conv_1d_fn, args=( np.array([[[3, 4, 5, 6]]], dtype=dtype), np.array([[[-2, -3]]], dtype=dtype), ), expected=np.array( [[[-9, -12, -21, -26, -10]]], dtype=preferred_element_type ), ) @parameterized.parameters(*PRECISION_VALUES) def testDotGeneral(self, precision): for dtype in self.float_types: def dot_fn(lhs, rhs): dnums = xla_data_pb2.DotDimensionNumbers() dnums.lhs_contracting_dimensions.append(2) dnums.rhs_contracting_dimensions.append(1) dnums.lhs_batch_dimensions.append(0) dnums.rhs_batch_dimensions.append(0) precision_config = None if precision: precision_config = xla_data_pb2.PrecisionConfig() precision_config.operand_precision.extend([precision, precision]) return xla.dot_general( lhs, rhs, dimension_numbers=dnums, precision_config=precision_config ) lhs = np.array( [ [[1, 2], [3, 4]], [[5, 6], [7, 8]], ], dtype=dtype, ) rhs = np.array( [ [[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], ], dtype=dtype, ) self._assertOpOutputMatchesExpected( dot_fn, args=(lhs, rhs), expected=np.array( [ [[9, 12, 15], [19, 26, 33]], [[95, 106, 117], [129, 144, 159]], ], dtype=dtype, ), ) def testDotGeneralInt8xInt8ToInt32(self): def dot_fn(lhs, rhs): dnums = xla_data_pb2.DotDimensionNumbers() dnums.lhs_contracting_dimensions.append(2) dnums.rhs_contracting_dimensions.append(1) dnums.lhs_batch_dimensions.append(0) dnums.rhs_batch_dimensions.append(0) return xla.dot_general( lhs, rhs, dimension_numbers=dnums, preferred_element_type=np.int32 ) lhs = np.array( [ [[1, 2], [3, 4]], [[5, 6], [7, 8]], ], dtype=np.int8, ) rhs = np.array( [ [[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], ], dtype=np.int8, ) self._assertOpOutputMatchesExpected( dot_fn, args=(lhs, rhs), expected=np.array( [ [[9, 12, 15], [19, 26, 33]], [[95, 106, 117], [129, 144, 159]], ], dtype=np.int32, ), ) def testNeg(self): for dtype in self.numeric_types - {np.uint8, np.int8}: self._assertOpOutputMatchesExpected( xla.neg, args=(np.array([1, 2, 3], dtype=dtype),), expected=np.array([-1, -2, -3], dtype=dtype), ) def testPad(self): for dtype in self.numeric_types: def pad_fn(x): return xla.pad( x, padding_value=7, padding_low=[2, 1], padding_high=[1, 2], padding_interior=[1, 0], ) self._assertOpOutputMatchesExpected( pad_fn, args=(np.arange(4, dtype=np.int32).astype(dtype).reshape([2, 2]),), expected=np.array( [ [7, 7, 7, 7, 7], [7, 7, 7, 7, 7], [7, 0, 1, 7, 7], [7, 7, 7, 7, 7], [7, 2, 3, 7, 7], [7, 7, 7, 7, 7], ], dtype=dtype, ), ) def testSetDynamicDimensionSize(self): dynamic_size = 7 # XLA doesn't support this for bfloat16. for dtype in set(self.numeric_types).intersection( set([np.int32, np.float32, np.float64, np.complex64]) ): def xla_set_dynamic_dimension_size_fn(x): # Tell XLA to cut the array to size=dynamic_size. return gen_xla_ops.xla_set_dynamic_dimension_size( x, dim_index=0, size=dynamic_size ) a = np.arange(10, dtype=np.int32).astype(dtype) expected = a[:dynamic_size] self._assertOpOutputMatchesExpected( xla_set_dynamic_dimension_size_fn, args=(a,), expected=expected ) def testPadNegative(self): for dtype in self.numeric_types: def pad_fn(x): return xla.pad( x, padding_value=7, padding_low=[0, -1], padding_high=[1, -2], padding_interior=[1, 2], ) self._assertOpOutputMatchesExpected( pad_fn, args=(np.arange(6, dtype=np.int32).astype(dtype).reshape([2, 3]),), expected=np.array( [[7, 7, 1, 7], [7, 7, 7, 7], [7, 7, 4, 7], [7, 7, 7, 7]], dtype=dtype, ), ) @parameterized.parameters( random_ops_util.Algorithm.THREEFRY, random_ops_util.Algorithm.PHILOX, random_ops_util.Algorithm.AUTO_SELECT, ) def testRngBitGeneratorIsDeterministic(self, algorithm): dtype = np.uint32 key = np.array([1, 2], dtype=np.uint64) shape = (10, 12) def rng_fun_is_deterministic(k): res1 = xla.rng_bit_generator(algorithm, k, shape, dtype=dtype) res2 = xla.rng_bit_generator(algorithm, k, shape, dtype=dtype) return (res1[0] - res2[0], res1[1] - res2[1]) self._assertOpOutputMatchesExpected( rng_fun_is_deterministic, args=(key,), expected=( np.zeros(key.shape, dtype=key.dtype), np.zeros(shape, dtype=dtype), ), ) def testReduce(self): for dtype in set(self.numeric_types).intersection( set([dtypes.bfloat16.as_numpy_dtype, np.float32]) ): @function.Defun(dtype, dtype) # pylint: disable=cell-var-from-loop def sum_reducer(x, y): return x + y def sum_reduction(dims): def fn(x): return xla.reduce( x, init_value=0, dimensions_to_reduce=dims, reducer=sum_reducer # pylint: disable=cell-var-from-loop ) return fn self._assertOpOutputMatchesExpected( sum_reduction(dims=[]), args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),), expected=np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]), ) self._assertOpOutputMatchesExpected( sum_reduction(dims=[0]), args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),), expected=np.array([12, 15, 18, 21], dtype=dtype), ) self._assertOpOutputMatchesExpected( sum_reduction(dims=[1]), args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),), expected=np.array([6, 22, 38], dtype=dtype), ) self._assertOpOutputMatchesExpected( sum_reduction(dims=[0, 1]), args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),), expected=dtype(66), ) @function.Defun(dtype, dtype) # pylint: disable=cell-var-from-loop def mul_reducer(x, y): return x * y def mul_reduction(dims): def fn(x): return xla.reduce( x, init_value=1, dimensions_to_reduce=dims, reducer=mul_reducer # pylint: disable=cell-var-from-loop ) return fn self._assertOpOutputMatchesExpected( mul_reduction(dims=[0]), args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),), expected=np.array([0, 45, 120, 231], dtype=dtype), ) IS_XLA_VARIADIC_REDUCE_V2 = [True, False] @parameterized.parameters(IS_XLA_VARIADIC_REDUCE_V2) def testVariadicReduceKahanSum(self, is_v2): for dtype in set(self.numeric_types).intersection( set([np.float32, np.complex64]) ): @def_function.function def kahan_sum_reducer(t0, t1): (s0, c0), (s1, c1) = t0, t1 s0minusc = s0 - (c0 + c1) t = s1 + s0minusc c = (t - s1) - s0minusc s = t return s, c def kahan_sum_reduction(dims, output_idx): def fn(x): arg = array_ops.zeros([], dtype) # pylint: disable=cell-var-from-loop reducer = kahan_sum_reducer.get_concrete_function( # pylint: disable=cell-var-from-loop (arg, arg), (arg, arg) ) if is_v2: return xla.variadic_reduce( (x, array_ops.zeros_like(x)), init_values=(arg, arg), dimensions_to_reduce=dims, reducer=reducer, )[output_idx] else: return gen_xla_ops.xla_variadic_reduce( (x, array_ops.zeros_like(x)), init_value=(arg, arg), dimensions_to_reduce=dims, reducer=reducer, )[output_idx] return fn xs = np.array([1e5, np.pi, -1e5, np.exp(1.0)]) xs = np.array([xs, xs[::-1] / 3, xs / 7], dtype) self._assertOpOutputMatchesExpected( kahan_sum_reduction(dims=[], output_idx=0), args=(xs,), expected=xs ) self._assertOpOutputMatchesExpected( kahan_sum_reduction(dims=[], output_idx=1), args=(xs,), expected=np.zeros_like(xs), ) shuffle_indices = np.argsort(np.random.randn(xs.shape[0])) self._assertOpOutputMatchesExpected( kahan_sum_reduction(dims=[0], output_idx=0), args=(xs[shuffle_indices],), expected=np.array( [ np.exp(1) / 3 + 1e5 * 8 / 7, np.pi * 8 / 7 - 1e5 / 3, -1e5 * 8 / 7 + np.pi / 3, np.exp(1) * 8 / 7 + 1e5 / 3, ], dtype=dtype, ), ) error_term_equality = functools.partial( self.assertAllClose, rtol=1e-3, atol=0.005 ) self._assertOpOutputMatchesExpected( kahan_sum_reduction(dims=[0], output_idx=1), args=(xs[shuffle_indices],), expected=np.zeros_like(xs[0]), equality_fn=error_term_equality, ) shuffle_indices = np.argsort(np.random.randn(xs.shape[1])) self._assertOpOutputMatchesExpected( kahan_sum_reduction(dims=[1], output_idx=0), args=(xs[:, shuffle_indices],), expected=np.array( [ np.pi + np.exp(1.0), (np.pi + np.exp(1.0)) / 3, (np.pi + np.exp(1.0)) / 7, ], dtype=dtype, ), ) self._assertOpOutputMatchesExpected( kahan_sum_reduction(dims=[1], output_idx=1), args=(xs[:, shuffle_indices],), expected=np.zeros_like(xs[:, 0]), equality_fn=error_term_equality, ) # Now, shuffle both dims. xs = xs[np.argsort(np.random.randn(xs.shape[0]))] xs = xs[:, np.argsort(np.random.randn(xs.shape[1]))] self._assertOpOutputMatchesExpected( kahan_sum_reduction(dims=[0, 1], output_idx=0), args=(xs,), expected=dtype((np.pi + np.exp(1.0)) * 31 / 21), ) self._assertOpOutputMatchesExpected( kahan_sum_reduction(dims=[0, 1], output_idx=1), args=(xs,), expected=dtype(0), equality_fn=error_term_equality, ) @parameterized.parameters(IS_XLA_VARIADIC_REDUCE_V2) def testVariadicReduceSingleOp(self, is_v2): @def_function.function def reducer_add(op_element, acc_val): return (op_element + acc_val,) for dtype in set(self.numeric_types): values = np.array([[1, 3, 5], [4, 6, 8]], dtype=dtype) init_val = np.array(0, dtype=dtype) arg_spec = array_ops.zeros([], dtype) # pylint: disable=cell-var-from-loop reducer_func = reducer_add.get_concrete_function(arg_spec, arg_spec) def reduce(values, *, dimensions_to_reduce): if is_v2: return xla.variadic_reduce( (values,), (init_val,), # pylint: disable=cell-var-from-loop dimensions_to_reduce=dimensions_to_reduce, reducer=reducer_func, # pylint: disable=cell-var-from-loop )[0] else: return gen_xla_ops.xla_variadic_reduce( (values,), (init_val,), # pylint: disable=cell-var-from-loop dimensions_to_reduce=dimensions_to_reduce, reducer=reducer_func, # pylint: disable=cell-var-from-loop )[0] # Reduce dimension 0 self._assertOpOutputMatchesExpected( functools.partial(reduce, dimensions_to_reduce=(0,)), args=(values,), expected=np.array([5, 9, 13], dtype=dtype), ) # Reduce dimension 1 self._assertOpOutputMatchesExpected( functools.partial(reduce, dimensions_to_reduce=(1,)), args=(values,), expected=np.array([9, 18], dtype=dtype), ) # Reduce dimensions 0 and 1 self._assertOpOutputMatchesExpected( functools.partial(reduce, dimensions_to_reduce=(0, 1)), args=(values,), expected=np.array(27, dtype=dtype), ) def testVariadicReduceV2DifferentTypes(self): # Two ops, with different dtypes @def_function.function def reducer_add(op_element_1, op_element_2, acc_val_1, acc_val_2): return (op_element_1 + acc_val_1, op_element_2 + acc_val_2) for dtype in set(self.numeric_types): values_1 = np.array([[1, 3, 5], [4, 6, 8]], dtype=dtype) values_2 = values_1.astype(np.int32) init_val_1 = np.array(0, dtype=dtype) # pylint: disable=cell-var-from-loop init_val_2 = init_val_1.astype(np.int32) arg_spec_1 = array_ops.zeros([], dtype) # pylint: disable=cell-var-from-loop arg_spec_2 = array_ops.zeros([], np.int32) reducer_func = reducer_add.get_concrete_function( arg_spec_1, arg_spec_2, arg_spec_1, arg_spec_2 ) # pylint: disable=cell-var-from-loop def reduce(*values, dimensions_to_reduce): return xla.variadic_reduce( values, ( init_val_1, # pylint: disable=cell-var-from-loop init_val_2, # pylint: disable=cell-var-from-loop ), dimensions_to_reduce=dimensions_to_reduce, reducer=reducer_func, # pylint: disable=cell-var-from-loop ) # Reduce dimension 0 self._assertOpOutputMatchesExpected( functools.partial(reduce, dimensions_to_reduce=(0,)), args=(values_1, values_2), expected=( np.array([5, 9, 13], dtype=dtype), np.array([5, 9, 13], dtype=np.int32), ), ) # Reduce dimension 1 self._assertOpOutputMatchesExpected( functools.partial(reduce, dimensions_to_reduce=(1,)), args=(values_1, values_2), expected=( np.array([9, 18], dtype=dtype), np.array([9, 18], dtype=np.int32), ), ) # Reduce dimensions 0 and 1 self._assertOpOutputMatchesExpected( functools.partial(reduce, dimensions_to_reduce=(0, 1)), args=(values_1, values_2), expected=(np.array(27, dtype=dtype), np.array(27, dtype=np.int32)), ) # Reduce not dimensions self._assertOpOutputMatchesExpected( functools.partial(reduce, dimensions_to_reduce=()), args=(values_1, values_2), expected=(values_1, values_2), ) @test_util.disable_mlir_bridge('Not supported yet') def testScatter(self): test_array = np.arange(9).astype(np.int32).reshape((3, 3)) scatter_indices = np.array([0, 2], dtype=np.int32) updates = np.array([[10, 20, 30], [70, 80, 90]], dtype=np.int32) dnums = xla_data_pb2.ScatterDimensionNumbers() dnums.update_window_dims.append(1) dnums.inserted_window_dims.append(0) dnums.scatter_dims_to_operand_dims.append(0) dnums.index_vector_dim = 1 add_numbers = function.Defun(np.int32, np.int32)(lambda x, y: x + y) def test_fn( scatter_input, scatter_indices, scatter_updates, ): return gen_xla_ops.xla_scatter( scatter_input, scatter_indices, scatter_updates, add_numbers, dnums.SerializeToString(), indices_are_sorted=False, ) expected = np.array([[10, 21, 32], [3, 4, 5], [76, 87, 98]], dtype=np.int32) self._assertOpOutputMatchesExpected( test_fn, args=(test_array, scatter_indices, updates), expected=expected, ) def testSelectAndScatter(self): for dtype in set(self.numeric_types).intersection( set([dtypes.bfloat16.as_numpy_dtype, np.float32]) ): @function.Defun(dtype, dtype) # pylint: disable=cell-var-from-loop def add_scatter(x, y): return x + y @function.Defun(dtype, dtype) # pylint: disable=cell-var-from-loop def ge_select(x, y): return x >= y def test_fn(operand, source): return xla.select_and_scatter( operand, window_dimensions=[2, 3, 1, 1], window_strides=[2, 2, 1, 1], padding=[[0, 0]] * 4, source=source, init_value=0, select=ge_select, # pylint: disable=cell-var-from-loop scatter=add_scatter, # pylint: disable=cell-var-from-loop ) self._assertOpOutputMatchesExpected( test_fn, args=( np.array( [ [7, 2, 5, 3, 8], [3, 8, 9, 3, 4], [1, 5, 7, 5, 6], [0, 6, 2, 10, 2], ], dtype=dtype, ).reshape((4, 5, 1, 1)), np.array([[2, 6], [3, 1]], dtype=dtype).reshape((2, 2, 1, 1)), ), expected=np.array( [ [0, 0, 0, 0, 0], [0, 0, 8, 0, 0], [0, 0, 3, 0, 0], [0, 0, 0, 1, 0], ], dtype=dtype, ).reshape((4, 5, 1, 1)), ) def testTranspose(self): for dtype in self.numeric_types: v = np.arange(4, dtype=np.int32).astype(dtype).reshape([2, 2]) self._assertOpOutputMatchesExpected( lambda x: xla.transpose(x, [1, 0]), args=(v,), expected=v.T ) def testDynamicSlice(self): for dtype in self.numeric_types: self._assertOpOutputMatchesExpected( xla.dynamic_slice, args=( np.arange(1000, dtype=np.int32) .astype(dtype) .reshape([10, 10, 10]), np.array([5, 7, 3]), np.array([2, 3, 2]), ), expected=np.array( np.array([ [[573, 574], [583, 584], [593, 594]], [[673, 674], [683, 684], [693, 694]], ]), dtype=dtype, ), ) def testDynamicSliceWithIncorrectStartIndicesShape(self): with self.session() as session: with self.test_scope(): output = xla.dynamic_slice( np.arange(1000, dtype=np.int32).reshape([10, 10, 10]), np.array([5, 7]), np.array([2, 3, 4]), ) with self.assertRaises(errors.InvalidArgumentError) as invalid_arg_error: session.run(output) self.assertRegex( invalid_arg_error.exception.message, ( r'has mismatched number of slice sizes \(3\) and number of start' r' indices \(2\)' ), ) def testDynamicSliceWithIncorrectSizeIndicesShape(self): with self.session() as session: with self.test_scope(): output = xla.dynamic_slice( np.arange(1000, dtype=np.int32).reshape([10, 10, 10]), np.array([5, 7, 3]), np.array([2, 3]), ) with self.assertRaises(errors.InvalidArgumentError) as invalid_arg_error: session.run(output) self.assertRegex( invalid_arg_error.exception.message, ( r'has mismatched number of slice sizes \(2\) and number of start' r' indices \(3\)' ), ) def test_optimization_barrier(self): args = ( np.array([[5, 6, 7]], dtype=np.float32), np.array([[1, 2, 3]], dtype=int), ) self._assertOpOutputMatchesExpected( xla.optimization_barrier, args=args, expected=args ) def test_reduce_precision(self): arg = np.array([1 + 2**-2 + 2**-4, 128, 256], dtype=np.float32) expected = np.array([1 + 2**-2, 128, float('Inf')], dtype=np.float32) exponent_bits = 4 mantissa_bits = 2 self._assertOpOutputMatchesExpected( lambda x: xla.reduce_precision(x, exponent_bits, mantissa_bits), args=(arg,), expected=expected, equality_fn=self.assertAllEqual, ) arg = np.array([4], dtype=np.float32) expected = np.array([4], dtype=np.float32) # Test passing numbers that cannot fit in a 32-bit integer. exponent_bits = 2**33 mantissa_bits = 2**33 self._assertOpOutputMatchesExpected( lambda x: xla.reduce_precision(x, exponent_bits, mantissa_bits), args=(arg,), expected=expected, equality_fn=self.assertAllEqual, )
XlaOpsNumericalTest
python
plotly__plotly.py
plotly/graph_objs/cone/_stream.py
{ "start": 233, "end": 3484 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "cone" _path_str = "cone.stream" _valid_props = {"maxpoints", "token"} @property def maxpoints(self): """ Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. The 'maxpoints' property is a number and may be specified as: - An int or float in the interval [0, 10000] Returns ------- int|float """ return self["maxpoints"] @maxpoints.setter def maxpoints(self, val): self["maxpoints"] = val @property def token(self): """ The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. The 'token' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["token"] @token.setter def token(self, val): self["token"] = val @property def _prop_descriptions(self): return """\ maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. """ def __init__(self, arg=None, maxpoints=None, token=None, **kwargs): """ Construct a new Stream object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.cone.Stream` maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. Returns ------- Stream """ super().__init__("stream") 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.cone.Stream constructor must be a dict or an instance of :class:`plotly.graph_objs.cone.Stream`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("maxpoints", arg, maxpoints) self._set_property("token", arg, token) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Stream
python
Textualize__textual
src/textual/widgets/_data_table.py
{ "start": 7106, "end": 7771 }
class ____: """Metadata for a column in the DataTable.""" key: ColumnKey label: Text width: int = 0 content_width: int = 0 auto_width: bool = False def get_render_width(self, data_table: DataTable[Any]) -> int: """Width, in cells, required to render the column with padding included. Args: data_table: The data table where the column will be rendered. Returns: The width, in cells, required to render the column with padding included. """ return 2 * data_table.cell_padding + ( self.content_width if self.auto_width else self.width ) @dataclass
Column
python
apache__airflow
airflow-core/tests/unit/jobs/test_base_job.py
{ "start": 1525, "end": 11871 }
class ____: def test_state_success(self): job = Job() job_runner = MockJobRunner(job=job) run_job(job=job, execute_callable=job_runner._execute) assert job.state == State.SUCCESS assert job.end_date is not None def test_state_sysexit(self): import sys job = Job() job_runner = MockJobRunner(job=job, func=lambda: sys.exit(0)) run_job(job=job, execute_callable=job_runner._execute) assert job.state == State.SUCCESS assert job.end_date is not None def test_base_job_respects_plugin_hooks(self): import sys job = Job() job_runner = MockJobRunner(job=job, func=lambda: sys.exit(0)) run_job(job=job, execute_callable=job_runner._execute) assert job.state == State.SUCCESS assert job.end_date is not None def test_base_job_respects_plugin_lifecycle(self, dag_maker): """ Test if DagRun is successful, and if Success callbacks is defined, it is sent to DagFileProcessor. """ get_listener_manager().add_listener(lifecycle_listener) job = Job() job_runner = MockJobRunner(job=job, func=lambda: sys.exit(0)) run_job(job=job, execute_callable=job_runner._execute) assert lifecycle_listener.started_component is job assert lifecycle_listener.stopped_component is job def test_state_failed(self): def abort(): raise RuntimeError("fail") job = Job() job_runner = MockJobRunner(job=job, func=abort) with pytest.raises(RuntimeError): run_job(job=job, execute_callable=job_runner._execute) assert job.state == State.FAILED assert job.end_date is not None @pytest.mark.parametrize( ("job_runner", "job_type", "job_heartbeat_sec"), [(SchedulerJobRunner, "scheduler", "11"), (TriggererJobRunner, "triggerer", "9")], ) def test_heart_rate_after_fetched_from_db(self, job_runner, job_type, job_heartbeat_sec): """Ensure heartrate is set correctly after jobs are queried from the DB""" if job_type == "scheduler": config_name = "scheduler_heartbeat_sec" else: config_name = "job_heartbeat_sec" with create_session() as session, conf_vars({(job_type.lower(), config_name): job_heartbeat_sec}): job = Job() job_runner(job=job) session.add(job) session.commit() most_recent = most_recent_job(job_runner.job_type, session=session) assert most_recent.heartrate == float(job_heartbeat_sec) session.rollback() @pytest.mark.parametrize( ("job_runner", "job_type", "job_heartbeat_sec"), [(SchedulerJobRunner, "scheduler", "11"), (TriggererJobRunner, "triggerer", "9")], ) def test_heart_rate_via_constructor_persists(self, job_runner, job_type, job_heartbeat_sec): """Ensure heartrate passed via constructor is set correctly""" with conf_vars({(job_type.lower(), "job_heartbeat_sec"): job_heartbeat_sec}): job = Job(heartrate=12) job_runner(job) # heartrate should be 12 since we passed that to the constructor directly assert job.heartrate == 12 def _compare_jobs(self, job1: Job, job2: Job): """Helper to compare two jobs where one can by Pydantic and the other not.""" assert job1.id == job2.id assert job1.dag_id == job2.dag_id assert job1.state == job2.state assert job1.job_type == job2.job_type assert job1.start_date == job2.start_date assert job1.end_date == job2.end_date assert job1.latest_heartbeat == job2.latest_heartbeat assert job1.executor_class == job2.executor_class assert job1.hostname == job2.hostname assert job1.unixname == job2.unixname def test_most_recent_job(self): with create_session() as session: old_job = Job(heartrate=10) MockJobRunner(job=old_job) old_job.latest_heartbeat = old_job.latest_heartbeat - datetime.timedelta(seconds=20) job = Job(heartrate=10) MockJobRunner(job=job) session.add(job) session.add(old_job) session.commit() self._compare_jobs(most_recent_job(MockJobRunner.job_type, session=session), job) self._compare_jobs(old_job.most_recent_job(session=session), job) session.rollback() def test_most_recent_job_running_precedence(self): with create_session() as session: old_running_state_job = Job(heartrate=10) MockJobRunner(job=old_running_state_job) old_running_state_job.latest_heartbeat = timezone.utcnow() old_running_state_job.state = State.RUNNING new_failed_state_job = Job(heartrate=10) MockJobRunner(job=new_failed_state_job) new_failed_state_job.latest_heartbeat = timezone.utcnow() new_failed_state_job.state = State.FAILED new_null_state_job = Job(heartrate=10) MockJobRunner(job=new_null_state_job) new_null_state_job.latest_heartbeat = timezone.utcnow() new_null_state_job.state = None session.add(old_running_state_job) session.add(new_failed_state_job) session.add(new_null_state_job) session.commit() self._compare_jobs( most_recent_job(MockJobRunner.job_type, session=session), old_running_state_job ) session.rollback() def test_is_alive(self): job = Job(heartrate=10, state=State.RUNNING) assert job.is_alive() is True job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=20) assert job.is_alive() is True job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=21) assert job.is_alive() is False # test because .seconds was used before instead of total_seconds # internal repr of datetime is (days, seconds) job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(days=1) assert job.is_alive() is False job.state = State.SUCCESS job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=10) assert job.is_alive() is False, "Completed jobs even with recent heartbeat should not be alive" @pytest.mark.parametrize("job_type", ["SchedulerJob", "TriggererJob"]) def test_is_alive_scheduler(self, job_type): job = Job(heartrate=10, state=State.RUNNING, job_type=job_type) assert job.is_alive() is True job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=20) assert job.is_alive() is True # default health-check grace period for scheduler job is not heartrate*2.1 but 30 seconds job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=21) assert job.is_alive() is True job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=31) assert job.is_alive() is False # test because .seconds was used before instead of total_seconds # internal repr of datetime is (days, seconds) job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(days=1) assert job.is_alive() is False job.state = State.SUCCESS job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=10) assert job.is_alive() is False, "Completed jobs even with recent heartbeat should not be alive" @patch("airflow.jobs.job.create_session") def test_heartbeat_failed(self, mock_create_session, caplog): when = timezone.utcnow() - datetime.timedelta(seconds=60) with create_session() as session: mock_session = Mock(spec_set=session, name="MockSession") mock_create_session.return_value.__enter__.return_value = mock_session mock_session.commit.side_effect = OperationalError("Force fail", {}, None) job = Job(heartrate=10, state=State.RUNNING) job.latest_heartbeat = when with caplog.at_level(logging.ERROR): job.heartbeat(heartbeat_callback=lambda _: None, session=mock_session) assert "heartbeat failed with error" in caplog.text assert job.latest_heartbeat == when, "attribute not updated when heartbeat fails" assert job.heartbeat_failed @conf_vars( { ("scheduler", "max_tis_per_query"): "100", } ) @patch("airflow.jobs.job.ExecutorLoader.get_default_executor") @patch("airflow.jobs.job.ExecutorLoader.init_executors") @patch("airflow.jobs.job.get_hostname") @patch("airflow.jobs.job.getuser") def test_essential_attr(self, mock_getuser, mock_hostname, mock_init_executors, mock_default_executor): mock_local_executor = LocalExecutor() mock_hostname.return_value = "test_hostname" mock_getuser.return_value = "testuser" mock_default_executor.return_value = mock_local_executor mock_init_executors.return_value = [mock_local_executor] test_job = Job(heartrate=10, dag_id="example_dag", state=State.RUNNING) MockJobRunner(job=test_job) assert test_job.heartrate == 10 assert test_job.dag_id == "example_dag" assert test_job.hostname == "test_hostname" assert test_job.max_tis_per_query == 100 assert test_job.unixname == "testuser" assert test_job.state == "running" assert test_job.executor == mock_local_executor assert test_job.executors == [mock_local_executor] def test_heartbeat(self, frozen_sleep, monkeypatch): monkeypatch.setattr("airflow.jobs.job.sleep", frozen_sleep) with create_session() as session: job = Job(heartrate=10) job.latest_heartbeat = timezone.utcnow() session.add(job) session.commit() hb_callback = Mock() job.heartbeat(heartbeat_callback=hb_callback) hb_callback.assert_called_once_with(ANY) hb_callback.reset_mock() perform_heartbeat(job=job, heartbeat_callback=hb_callback, only_if_necessary=True) assert hb_callback.called is False
TestJob
python
pytest-dev__pytest
testing/test_assertrewrite.py
{ "start": 27859, "end": 38755 }
class ____: def test_pycache_is_a_file(self, pytester: Pytester) -> None: pytester.path.joinpath("__pycache__").write_text("Hello", encoding="utf-8") pytester.makepyfile( """ def test_rewritten(): assert "@py_builtins" in globals()""" ) assert pytester.runpytest().ret == 0 def test_pycache_is_readonly(self, pytester: Pytester) -> None: cache = pytester.mkdir("__pycache__") old_mode = cache.stat().st_mode cache.chmod(old_mode ^ stat.S_IWRITE) pytester.makepyfile( """ def test_rewritten(): assert "@py_builtins" in globals()""" ) try: assert pytester.runpytest().ret == 0 finally: cache.chmod(old_mode) def test_zipfile(self, pytester: Pytester) -> None: z = pytester.path.joinpath("myzip.zip") z_fn = str(z) f = zipfile.ZipFile(z_fn, "w") try: f.writestr("test_gum/__init__.py", "") f.writestr("test_gum/test_lizard.py", "") finally: f.close() z.chmod(256) pytester.makepyfile( f""" import sys sys.path.append({z_fn!r}) import test_gum.test_lizard""" ) assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED def test_load_resource_via_files_with_rewrite(self, pytester: Pytester) -> None: example = pytester.path.joinpath("demo") / "example" init = pytester.path.joinpath("demo") / "__init__.py" pytester.makepyfile( **{ "demo/__init__.py": """ from importlib.resources import files def load(): return files(__name__) """, "test_load": f""" pytest_plugins = ["demo"] def test_load(): from demo import load found = {{str(i) for i in load().iterdir() if i.name != "__pycache__"}} assert found == {{{str(example)!r}, {str(init)!r}}} """, } ) example.mkdir() assert pytester.runpytest("-vv").ret == ExitCode.OK def test_readonly(self, pytester: Pytester) -> None: sub = pytester.mkdir("testing") sub.joinpath("test_readonly.py").write_bytes( b""" def test_rewritten(): assert "@py_builtins" in globals() """, ) old_mode = sub.stat().st_mode sub.chmod(320) try: assert pytester.runpytest().ret == 0 finally: sub.chmod(old_mode) def test_dont_write_bytecode(self, pytester: Pytester, monkeypatch) -> None: monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False) pytester.makepyfile( """ import os def test_no_bytecode(): assert "__pycache__" in __cached__ assert not os.path.exists(__cached__) assert not os.path.exists(os.path.dirname(__cached__))""" ) monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "1") assert pytester.runpytest_subprocess().ret == 0 def test_orphaned_pyc_file(self, pytester: Pytester, monkeypatch) -> None: monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False) monkeypatch.setattr(sys, "pycache_prefix", None, raising=False) pytester.makepyfile( """ import orphan def test_it(): assert orphan.value == 17 """ ) pytester.makepyfile( orphan=""" value = 17 """ ) py_compile.compile("orphan.py") os.remove("orphan.py") # Python 3 puts the .pyc files in a __pycache__ directory, and will # not import from there without source. It will import a .pyc from # the source location though. if not os.path.exists("orphan.pyc"): pycs = glob.glob("__pycache__/orphan.*.pyc") assert len(pycs) == 1 os.rename(pycs[0], "orphan.pyc") assert pytester.runpytest().ret == 0 def test_cached_pyc_includes_pytest_version( self, pytester: Pytester, monkeypatch ) -> None: """Avoid stale caches (#1671)""" monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False) monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False) pytester.makepyfile( test_foo=""" def test_foo(): assert True """ ) result = pytester.runpytest_subprocess() assert result.ret == 0 found_names = glob.glob(f"__pycache__/*-pytest-{pytest.__version__}.pyc") assert found_names, "pyc with expected tag not found in names: {}".format( glob.glob("__pycache__/*.pyc") ) @pytest.mark.skipif('"__pypy__" in sys.modules') def test_pyc_vs_pyo( self, pytester: Pytester, monkeypatch: pytest.MonkeyPatch, ) -> None: pytester.makepyfile( """ import pytest def test_optimized(): "hello" assert test_optimized.__doc__ is None""" ) p = make_numbered_dir(root=Path(pytester.path), prefix="runpytest-") tmp = f"--basetemp={p}" with monkeypatch.context() as mp: mp.setenv("PYTHONOPTIMIZE", "2") mp.delenv("PYTHONDONTWRITEBYTECODE", raising=False) mp.delenv("PYTHONPYCACHEPREFIX", raising=False) assert pytester.runpytest_subprocess(tmp).ret == 0 tagged = "test_pyc_vs_pyo." + PYTEST_TAG assert tagged + ".pyo" in os.listdir("__pycache__") monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False) monkeypatch.delenv("PYTHONPYCACHEPREFIX", raising=False) assert pytester.runpytest_subprocess(tmp).ret == 1 assert tagged + ".pyc" in os.listdir("__pycache__") def test_package(self, pytester: Pytester) -> None: pkg = pytester.path.joinpath("pkg") pkg.mkdir() pkg.joinpath("__init__.py") pkg.joinpath("test_blah.py").write_text( """ def test_rewritten(): assert "@py_builtins" in globals()""", encoding="utf-8", ) assert pytester.runpytest().ret == 0 def test_translate_newlines(self, pytester: Pytester) -> None: content = "def test_rewritten():\r\n assert '@py_builtins' in globals()" b = content.encode("utf-8") pytester.path.joinpath("test_newlines.py").write_bytes(b) assert pytester.runpytest().ret == 0 def test_package_without__init__py(self, pytester: Pytester) -> None: pkg = pytester.mkdir("a_package_without_init_py") pkg.joinpath("module.py").touch() pytester.makepyfile("import a_package_without_init_py.module") assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED def test_rewrite_warning(self, pytester: Pytester) -> None: pytester.makeconftest( """ import pytest pytest.register_assert_rewrite("_pytest") """ ) # needs to be a subprocess because pytester explicitly disables this warning result = pytester.runpytest_subprocess() result.stdout.fnmatch_lines(["*Module already imported*; _pytest"]) def test_rewrite_warning_ignore(self, pytester: Pytester) -> None: pytester.makeconftest( """ import pytest pytest.register_assert_rewrite("_pytest") """ ) # needs to be a subprocess because pytester explicitly disables this warning result = pytester.runpytest_subprocess( "-W", "ignore:Module already imported so cannot be rewritten; _pytest:pytest.PytestAssertRewriteWarning", ) # Previously, when the message pattern used to contain an extra `:`, an error was raised. assert not result.stderr.str().strip() result.stdout.no_fnmatch_line("*Module already imported*; _pytest") def test_rewrite_module_imported_from_conftest(self, pytester: Pytester) -> None: pytester.makeconftest( """ import test_rewrite_module_imported """ ) pytester.makepyfile( test_rewrite_module_imported=""" def test_rewritten(): assert "@py_builtins" in globals() """ ) assert pytester.runpytest_subprocess().ret == 0 def test_remember_rewritten_modules( self, pytestconfig, pytester: Pytester, monkeypatch ) -> None: """`AssertionRewriteHook` should remember rewritten modules so it doesn't give false positives (#2005).""" monkeypatch.syspath_prepend(pytester.path) pytester.makepyfile(test_remember_rewritten_modules="") warnings = [] hook = AssertionRewritingHook(pytestconfig) monkeypatch.setattr( hook, "_warn_already_imported", lambda code, msg: warnings.append(msg) ) spec = hook.find_spec("test_remember_rewritten_modules") assert spec is not None module = importlib.util.module_from_spec(spec) hook.exec_module(module) hook.mark_rewrite("test_remember_rewritten_modules") hook.mark_rewrite("test_remember_rewritten_modules") assert warnings == [] def test_rewrite_warning_using_pytest_plugins(self, pytester: Pytester) -> None: pytester.makepyfile( **{ "conftest.py": "pytest_plugins = ['core', 'gui', 'sci']", "core.py": "", "gui.py": "pytest_plugins = ['core', 'sci']", "sci.py": "pytest_plugins = ['core']", "test_rewrite_warning_pytest_plugins.py": "def test(): pass", } ) pytester.chdir() result = pytester.runpytest_subprocess() result.stdout.fnmatch_lines(["*= 1 passed in *=*"]) result.stdout.no_fnmatch_line("*pytest-warning summary*") def test_rewrite_warning_using_pytest_plugins_env_var( self, pytester: Pytester, monkeypatch ) -> None: monkeypatch.setenv("PYTEST_PLUGINS", "plugin") pytester.makepyfile( **{ "plugin.py": "", "test_rewrite_warning_using_pytest_plugins_env_var.py": """ import plugin pytest_plugins = ['plugin'] def test(): pass """, } ) pytester.chdir() result = pytester.runpytest_subprocess() result.stdout.fnmatch_lines(["*= 1 passed in *=*"]) result.stdout.no_fnmatch_line("*pytest-warning summary*")
TestRewriteOnImport
python
etianen__django-reversion
tests/test_app/tests/test_models.py
{ "start": 6857, "end": 8654 }
class ____(TestModelMixin, TestBase): databases = {"default", "mysql", "postgres"} def testGetDeleted(self): with reversion.create_revision(): obj = TestModel.objects.create() with reversion.create_revision(): obj.save() obj.delete() self.assertEqual(Version.objects.get_deleted(TestModel).count(), 1) def testGetDeletedEmpty(self): with reversion.create_revision(): TestModel.objects.create() self.assertEqual(Version.objects.get_deleted(TestModel).count(), 0) def testGetDeletedOrdering(self): with reversion.create_revision(): obj_1 = TestModel.objects.create() with reversion.create_revision(): obj_2 = TestModel.objects.create() pk_1 = obj_1.pk obj_1.delete() pk_2 = obj_2.pk obj_2.delete() self.assertEqual(Version.objects.get_deleted(TestModel)[0].object_id, str(pk_2)) self.assertEqual(Version.objects.get_deleted(TestModel)[1].object_id, str(pk_1)) def testGetDeletedPostgres(self): with reversion.create_revision(using="postgres"): obj = TestModel.objects.using("postgres").create() with reversion.create_revision(using="postgres"): obj.save() obj.delete() self.assertEqual(Version.objects.using("postgres").get_deleted(TestModel, model_db="postgres").count(), 1) def testGetDeletedMySQL(self): with reversion.create_revision(using="mysql"): obj = TestModel.objects.using("mysql").create() with reversion.create_revision(using="mysql"): obj.save() obj.delete() self.assertEqual(Version.objects.using("mysql").get_deleted(TestModel, model_db="mysql").count(), 1)
GetDeletedTest
python
scipy__scipy
scipy/integrate/tests/test_tanhsinh.py
{ "start": 1437, "end": 28324 }
class ____: # Test problems from [1] Section 6 def f1(self, t): return t * np.log(1 + t) f1.ref = 0.25 f1.b = 1 def f2(self, t): return t ** 2 * np.arctan(t) f2.ref = (np.pi - 2 + 2 * np.log(2)) / 12 f2.b = 1 def f3(self, t): return np.exp(t) * np.cos(t) f3.ref = (np.exp(np.pi / 2) - 1) / 2 f3.b = np.pi / 2 def f4(self, t): a = np.sqrt(2 + t ** 2) return np.arctan(a) / ((1 + t ** 2) * a) f4.ref = 5 * np.pi ** 2 / 96 f4.b = 1 def f5(self, t): return np.sqrt(t) * np.log(t) f5.ref = -4 / 9 f5.b = 1 def f6(self, t): return np.sqrt(1 - t ** 2) f6.ref = np.pi / 4 f6.b = 1 def f7(self, t): return np.sqrt(t) / np.sqrt(1 - t ** 2) f7.ref = 2 * np.sqrt(np.pi) * special.gamma(3 / 4) / special.gamma(1 / 4) f7.b = 1 def f8(self, t): return np.log(t) ** 2 f8.ref = 2 f8.b = 1 def f9(self, t): return np.log(np.cos(t)) f9.ref = -np.pi * np.log(2) / 2 f9.b = np.pi / 2 def f10(self, t): return np.sqrt(np.tan(t)) f10.ref = np.pi * np.sqrt(2) / 2 f10.b = np.pi / 2 def f11(self, t): return 1 / (1 + t ** 2) f11.ref = np.pi / 2 f11.b = np.inf def f12(self, t): return np.exp(-t) / np.sqrt(t) f12.ref = np.sqrt(np.pi) f12.b = np.inf def f13(self, t): return np.exp(-t ** 2 / 2) f13.ref = np.sqrt(np.pi / 2) f13.b = np.inf def f14(self, t): return np.exp(-t) * np.cos(t) f14.ref = 0.5 f14.b = np.inf def f15(self, t): return np.sin(t) / t f15.ref = np.pi / 2 f15.b = np.inf def error(self, res, ref, log=False, xp=None): xp = array_namespace(res, ref) if xp is None else xp err = abs(res - ref) if not log: return err with np.errstate(divide='ignore'): return xp.log10(err) def test_input_validation(self, xp): f = self.f1 zero = xp.asarray(0) f_b = xp.asarray(f.b) message = '`f` must be callable.' with pytest.raises(ValueError, match=message): _tanhsinh(42, zero, f_b) message = '...must be True or False.' with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, log=2) message = '...must be real numbers.' with pytest.raises(ValueError, match=message): _tanhsinh(f, xp.asarray(1+1j), f_b) with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, atol='ekki') with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, rtol=pytest) message = '...must be non-negative and finite.' with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, rtol=-1) with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, atol=xp.inf) message = '...may not be positive infinity.' with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, rtol=xp.inf, log=True) with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, atol=xp.inf, log=True) message = '...must be integers.' with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, maxlevel=object()) # with pytest.raises(ValueError, match=message): # unused for now # _tanhsinh(f, zero, f_b, maxfun=1+1j) with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, minlevel="migratory coconut") message = '...must be non-negative.' with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, maxlevel=-1) # with pytest.raises(ValueError, match=message): # unused for now # _tanhsinh(f, zero, f_b, maxfun=-1) with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, minlevel=-1) message = '...must be True or False.' with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, preserve_shape=2) message = '...must be callable.' with pytest.raises(ValueError, match=message): _tanhsinh(f, zero, f_b, callback='elderberry') @pytest.mark.parametrize("limits, ref", [ [(0, math.inf), 0.5], # b infinite [(-math.inf, 0), 0.5], # a infinite [(-math.inf, math.inf), 1.], # a and b infinite [(math.inf, -math.inf), -1.], # flipped limits [(1, -1), stats.norm.cdf(-1.) - stats.norm.cdf(1.)], # flipped limits ]) def test_integral_transforms(self, limits, ref, xp): # Check that the integral transforms are behaving for both normal and # log integration limits = [xp.asarray(limit) for limit in limits] dtype = xp.asarray(float(limits[0])).dtype ref = xp.asarray(ref, dtype=dtype) res = _tanhsinh(norm_pdf, *limits) xp_assert_close(res.integral, ref) logres = _tanhsinh(norm_logpdf, *limits, log=True) xp_assert_close(xp.exp(logres.integral), ref, check_dtype=False) # Transformation should not make the result complex unnecessarily assert (xp.isdtype(logres.integral.dtype, "real floating") if ref > 0 else xp.isdtype(logres.integral.dtype, "complex floating")) atol = 2 * xp.finfo(res.error.dtype).eps xp_assert_close(xp.exp(logres.error), res.error, atol=atol, check_dtype=False) # 15 skipped intentionally; it's very difficult numerically @pytest.mark.skip_xp_backends(np_only=True, reason='Cumbersome to convert everything.') @pytest.mark.parametrize('f_number', range(1, 15)) def test_basic(self, f_number, xp): f = getattr(self, f"f{f_number}") rtol = 2e-8 res = _tanhsinh(f, 0, f.b, rtol=rtol) assert_allclose(res.integral, f.ref, rtol=rtol) if f_number not in {7, 12, 14}: # mildly underestimates error here true_error = abs(self.error(res.integral, f.ref)/res.integral) assert true_error < res.error if f_number in {7, 10, 12}: # succeeds, but doesn't know it return assert res.success assert res.status == 0 @pytest.mark.skip_xp_backends(np_only=True, reason="Distributions aren't xp-compatible.") @pytest.mark.parametrize('ref', (0.5, [0.4, 0.6])) @pytest.mark.parametrize('case', stats._distr_params.distcont) def test_accuracy(self, ref, case, xp): distname, params = case if distname in {'dgamma', 'dweibull', 'laplace', 'kstwo'}: # should split up interval at first-derivative discontinuity pytest.skip('tanh-sinh is not great for non-smooth integrands') if (distname in {'studentized_range', 'levy_stable'} and not int(os.getenv('SCIPY_XSLOW', 0))): pytest.skip('This case passes, but it is too slow.') dist = getattr(stats, distname)(*params) x = dist.interval(ref) res = _tanhsinh(dist.pdf, *x) assert_allclose(res.integral, ref) @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)]) def test_vectorization(self, shape, xp): # Test for correct functionality, output shapes, and dtypes for various # input shapes. rng = np.random.default_rng(82456839535679456794) a = xp.asarray(rng.random(shape)) b = xp.asarray(rng.random(shape)) p = xp.asarray(rng.random(shape)) n = math.prod(shape) def f(x, p): f.ncall += 1 f.feval += 1 if (xp_size(x) == n or x.ndim <= 1) else x.shape[-1] return x**p f.ncall = 0 f.feval = 0 @_vectorize(xp) def _tanhsinh_single(a, b, p): return _tanhsinh(lambda x: x**p, a, b) res = _tanhsinh(f, a, b, args=(p,)) refs = _tanhsinh_single(a, b, p) attrs = ['integral', 'error', 'success', 'status', 'nfev', 'maxlevel'] for attr in attrs: ref_attr = xp.stack([getattr(ref, attr) for ref in refs]) res_attr = xp_ravel(getattr(res, attr)) xp_assert_close(res_attr, ref_attr, rtol=1e-15) assert getattr(res, attr).shape == shape assert xp.isdtype(res.success.dtype, 'bool') assert xp.isdtype(res.status.dtype, 'integral') assert xp.isdtype(res.nfev.dtype, 'integral') assert xp.isdtype(res.maxlevel.dtype, 'integral') assert xp.max(res.nfev) == f.feval # maxlevel = 2 -> 3 function calls (2 initialization, 1 work) assert xp.max(res.maxlevel) >= 2 assert xp.max(res.maxlevel) == f.ncall def test_flags(self, xp): # Test cases that should produce different status flags; show that all # can be produced simultaneously. def f(xs, js): f.nit += 1 funcs = [lambda x: xp.exp(-x**2), # converges lambda x: xp.exp(x), # reaches maxiter due to order=2 lambda x: xp.full_like(x, xp.nan)] # stops due to NaN res = [] for i in range(xp_size(js)): x = xs[i, ...] j = int(xp_ravel(js)[i]) res.append(funcs[j](x)) return xp.stack(res) f.nit = 0 args = (xp.arange(3, dtype=xp.int64),) a = xp.asarray([xp.inf]*3) b = xp.asarray([-xp.inf] * 3) res = _tanhsinh(f, a, b, maxlevel=5, args=args) ref_flags = xp.asarray([0, -2, -3], dtype=xp.int32) xp_assert_equal(res.status, ref_flags) def test_flags_preserve_shape(self, xp): # Same test as above but using `preserve_shape` option to simplify. def f(x): res = [xp.exp(-x[0]**2), # converges xp.exp(x[1]), # reaches maxiter due to order=2 xp.full_like(x[2], xp.nan)] # stops due to NaN return xp.stack(res) a = xp.asarray([xp.inf] * 3) b = xp.asarray([-xp.inf] * 3) res = _tanhsinh(f, a, b, maxlevel=5, preserve_shape=True) ref_flags = xp.asarray([0, -2, -3], dtype=xp.int32) xp_assert_equal(res.status, ref_flags) def test_preserve_shape(self, xp): # Test `preserve_shape` option def f(x, xp): return xp.stack([xp.stack([x, xp.sin(10 * x)]), xp.stack([xp.cos(30 * x), x * xp.sin(100 * x)])]) ref = quad_vec(lambda x: f(x, np), 0, 1) res = _tanhsinh(lambda x: f(x, xp), xp.asarray(0), xp.asarray(1), preserve_shape=True) dtype = xp.asarray(0.).dtype xp_assert_close(res.integral, xp.asarray(ref[0], dtype=dtype)) def test_convergence(self, xp): # demonstrate that number of accurate digits doubles each iteration dtype = xp.float64 # this only works with good precision def f(t): return t * xp.log(1 + t) ref = xp.asarray(0.25, dtype=dtype) a, b = xp.asarray(0., dtype=dtype), xp.asarray(1., dtype=dtype) last_logerr = 0 for i in range(4): res = _tanhsinh(f, a, b, minlevel=0, maxlevel=i) logerr = self.error(res.integral, ref, log=True, xp=xp) assert (logerr < last_logerr * 2 or logerr < -15.5) last_logerr = logerr def test_options_and_result_attributes(self, xp): # demonstrate that options are behaving as advertised and status # messages are as intended def f(x): f.calls += 1 f.feval += xp_size(xp.asarray(x)) return x**2 * xp.atan(x) f.ref = xp.asarray((math.pi - 2 + 2 * math.log(2)) / 12, dtype=xp.float64) default_rtol = 1e-12 default_atol = f.ref * default_rtol # effective default absolute tol # Keep things simpler by leaving tolerances fixed rather than # having to make them dtype-dependent a = xp.asarray(0., dtype=xp.float64) b = xp.asarray(1., dtype=xp.float64) # Test default options f.feval, f.calls = 0, 0 ref = _tanhsinh(f, a, b) assert self.error(ref.integral, f.ref) < ref.error < default_atol assert ref.nfev == f.feval ref.calls = f.calls # reference number of function calls assert ref.success assert ref.status == 0 # Test `maxlevel` equal to required max level # We should get all the same results f.feval, f.calls = 0, 0 maxlevel = int(ref.maxlevel) res = _tanhsinh(f, a, b, maxlevel=maxlevel) res.calls = f.calls assert res == ref # Now reduce the maximum level. We won't meet tolerances. f.feval, f.calls = 0, 0 maxlevel -= 1 assert maxlevel >= 2 # can't compare errors otherwise res = _tanhsinh(f, a, b, maxlevel=maxlevel) assert self.error(res.integral, f.ref) < res.error > default_atol assert res.nfev == f.feval < ref.nfev assert f.calls == ref.calls - 1 assert not res.success assert res.status == eim._ECONVERR # `maxfun` is currently not enforced # # Test `maxfun` equal to required number of function evaluations # # We should get all the same results # f.feval, f.calls = 0, 0 # maxfun = ref.nfev # res = _tanhsinh(f, 0, f.b, maxfun = maxfun) # assert res == ref # # # Now reduce `maxfun`. We won't meet tolerances. # f.feval, f.calls = 0, 0 # maxfun -= 1 # res = _tanhsinh(f, 0, f.b, maxfun=maxfun) # assert self.error(res.integral, f.ref) < res.error > default_atol # assert res.nfev == f.feval < ref.nfev # assert f.calls == ref.calls - 1 # assert not res.success # assert res.status == 2 # Take this result to be the new reference ref = res ref.calls = f.calls # Test `atol` f.feval, f.calls = 0, 0 # With this tolerance, we should get the exact same result as ref atol = np.nextafter(float(ref.error), np.inf) res = _tanhsinh(f, a, b, rtol=0, atol=atol) assert res.integral == ref.integral assert res.error == ref.error assert res.nfev == f.feval == ref.nfev assert f.calls == ref.calls # Except the result is considered to be successful assert res.success assert res.status == 0 f.feval, f.calls = 0, 0 # With a tighter tolerance, we should get a more accurate result atol = np.nextafter(float(ref.error), -np.inf) res = _tanhsinh(f, a, b, rtol=0, atol=atol) assert self.error(res.integral, f.ref) < res.error < atol assert res.nfev == f.feval > ref.nfev assert f.calls > ref.calls assert res.success assert res.status == 0 # Test `rtol` f.feval, f.calls = 0, 0 # With this tolerance, we should get the exact same result as ref rtol = np.nextafter(float(ref.error/ref.integral), np.inf) res = _tanhsinh(f, a, b, rtol=rtol) assert res.integral == ref.integral assert res.error == ref.error assert res.nfev == f.feval == ref.nfev assert f.calls == ref.calls # Except the result is considered to be successful assert res.success assert res.status == 0 f.feval, f.calls = 0, 0 # With a tighter tolerance, we should get a more accurate result rtol = np.nextafter(float(ref.error/ref.integral), -np.inf) res = _tanhsinh(f, a, b, rtol=rtol) assert self.error(res.integral, f.ref)/f.ref < res.error/res.integral < rtol assert res.nfev == f.feval > ref.nfev assert f.calls > ref.calls assert res.success assert res.status == 0 @pytest.mark.skip_xp_backends('torch', reason= 'https://github.com/scipy/scipy/pull/21149#issuecomment-2330477359', ) @pytest.mark.parametrize('rtol', [1e-4, 1e-14]) def test_log(self, rtol, xp): # Test equivalence of log-integration and regular integration test_tols = dict(atol=1e-18, rtol=1e-15) # Positive integrand (real log-integrand) a = xp.asarray(-1., dtype=xp.float64) b = xp.asarray(2., dtype=xp.float64) res = _tanhsinh(norm_logpdf, a, b, log=True, rtol=math.log(rtol)) ref = _tanhsinh(norm_pdf, a, b, rtol=rtol) xp_assert_close(xp.exp(res.integral), ref.integral, **test_tols) xp_assert_close(xp.exp(res.error), ref.error, **test_tols) assert res.nfev == ref.nfev # Real integrand (complex log-integrand) def f(x): return -norm_logpdf(x)*norm_pdf(x) def logf(x): return xp.log(norm_logpdf(x) + 0j) + norm_logpdf(x) + xp.pi * 1j a = xp.asarray(-xp.inf, dtype=xp.float64) b = xp.asarray(xp.inf, dtype=xp.float64) res = _tanhsinh(logf, a, b, log=True) ref = _tanhsinh(f, a, b) # In gh-19173, we saw `invalid` warnings on one CI platform. # Silencing `all` because I can't reproduce locally and don't want # to risk the need to run CI again. with np.errstate(all='ignore'): xp_assert_close(xp.exp(res.integral), ref.integral, **test_tols, check_dtype=False) xp_assert_close(xp.exp(res.error), ref.error, **test_tols, check_dtype=False) assert res.nfev == ref.nfev def test_complex(self, xp): # Test integration of complex integrand # Finite limits def f(x): return xp.exp(1j * x) a, b = xp.asarray(0.), xp.asarray(xp.pi/4) res = _tanhsinh(f, a, b) ref = math.sqrt(2)/2 + (1-math.sqrt(2)/2)*1j xp_assert_close(res.integral, xp.asarray(ref)) # Infinite limits def f(x): return norm_pdf(x) + 1j/2*norm_pdf(x/2) a, b = xp.asarray(xp.inf), xp.asarray(-xp.inf) res = _tanhsinh(f, a, b) xp_assert_close(res.integral, xp.asarray(-(1+1j))) @pytest.mark.parametrize("maxlevel", range(4)) def test_minlevel(self, maxlevel, xp): # Verify that minlevel does not change the values at which the # integrand is evaluated or the integral/error estimates, only the # number of function calls def f(x): f.calls += 1 f.feval += xp_size(xp.asarray(x)) f.x = xp.concat((f.x, xp_ravel(x))) return x**2 * xp.atan(x) f.feval, f.calls, f.x = 0, 0, xp.asarray([]) a = xp.asarray(0, dtype=xp.float64) b = xp.asarray(1, dtype=xp.float64) ref = _tanhsinh(f, a, b, minlevel=0, maxlevel=maxlevel) ref_x = xp.sort(f.x) for minlevel in range(0, maxlevel + 1): f.feval, f.calls, f.x = 0, 0, xp.asarray([]) options = dict(minlevel=minlevel, maxlevel=maxlevel) res = _tanhsinh(f, a, b, **options) # Should be very close; all that has changed is the order of values xp_assert_close(res.integral, ref.integral, rtol=4e-16) # Difference in absolute errors << magnitude of integral xp_assert_close(res.error, ref.error, atol=4e-16 * ref.integral) assert res.nfev == f.feval == f.x.shape[0] assert f.calls == maxlevel - minlevel + 1 + 1 # 1 validation call assert res.status == ref.status xp_assert_equal(ref_x, xp.sort(f.x)) def test_improper_integrals(self, xp): # Test handling of infinite limits of integration (mixed with finite limits) def f(x): x[xp.isinf(x)] = xp.nan return xp.exp(-x**2) a = xp.asarray([-xp.inf, 0, -xp.inf, xp.inf, -20, -xp.inf, -20]) b = xp.asarray([xp.inf, xp.inf, 0, -xp.inf, 20, 20, xp.inf]) ref = math.sqrt(math.pi) ref = xp.asarray([ref, ref/2, ref/2, -ref, ref, ref, ref]) res = _tanhsinh(f, a, b) xp_assert_close(res.integral, ref) @pytest.mark.parametrize("limits", ((0, 3), ([-math.inf, 0], [3, 3]))) @pytest.mark.parametrize("dtype", ('float32', 'float64')) def test_dtype(self, limits, dtype, xp): # Test that dtypes are preserved dtype = getattr(xp, dtype) a, b = xp.asarray(limits, dtype=dtype) def f(x): assert x.dtype == dtype return xp.exp(x) rtol = 1e-12 if dtype == xp.float64 else 1e-5 res = _tanhsinh(f, a, b, rtol=rtol) assert res.integral.dtype == dtype assert res.error.dtype == dtype assert xp.all(res.success) xp_assert_close(res.integral, xp.exp(b)-xp.exp(a)) def test_maxiter_callback(self, xp): # Test behavior of `maxiter` parameter and `callback` interface a, b = xp.asarray(-xp.inf), xp.asarray(xp.inf) def f(x): return xp.exp(-x*x) minlevel, maxlevel = 0, 2 maxiter = maxlevel - minlevel + 1 kwargs = dict(minlevel=minlevel, maxlevel=maxlevel, rtol=1e-15) res = _tanhsinh(f, a, b, **kwargs) assert not res.success assert res.maxlevel == maxlevel def callback(res): callback.iter += 1 callback.res = res assert hasattr(res, 'integral') assert res.status == 1 if callback.iter == maxiter: raise StopIteration callback.iter = -1 # callback called once before first iteration callback.res = None del kwargs['maxlevel'] res2 = _tanhsinh(f, a, b, **kwargs, callback=callback) # terminating with callback is identical to terminating due to maxiter # (except for `status`) for key in res.keys(): if key == 'status': assert res[key] == -2 assert res2[key] == -4 else: assert res2[key] == callback.res[key] == res[key] def test_jumpstart(self, xp): # The intermediate results at each level i should be the same as the # final results when jumpstarting at level i; i.e. minlevel=maxlevel=i a = xp.asarray(-xp.inf, dtype=xp.float64) b = xp.asarray(xp.inf, dtype=xp.float64) def f(x): return xp.exp(-x*x) def callback(res): callback.integrals.append(xp_copy(res.integral)[()]) callback.errors.append(xp_copy(res.error)[()]) callback.integrals = [] callback.errors = [] maxlevel = 4 _tanhsinh(f, a, b, minlevel=0, maxlevel=maxlevel, callback=callback) for i in range(maxlevel + 1): res = _tanhsinh(f, a, b, minlevel=i, maxlevel=i) xp_assert_close(callback.integrals[1+i], res.integral, rtol=1e-15) xp_assert_close(callback.errors[1+i], res.error, rtol=1e-15, atol=1e-16) def test_special_cases(self, xp): # Test edge cases and other special cases a, b = xp.asarray(0), xp.asarray(1) def f(x): assert xp.isdtype(x.dtype, "real floating") return x res = _tanhsinh(f, a, b) assert res.success xp_assert_close(res.integral, xp.asarray(0.5)) # Test levels 0 and 1; error is NaN res = _tanhsinh(f, a, b, maxlevel=0) assert res.integral > 0 xp_assert_equal(res.error, xp.asarray(xp.nan)) res = _tanhsinh(f, a, b, maxlevel=1) assert res.integral > 0 xp_assert_equal(res.error, xp.asarray(xp.nan)) # Test equal left and right integration limits res = _tanhsinh(f, b, b) assert res.success assert res.maxlevel == -1 xp_assert_close(res.integral, xp.asarray(0.)) # Test scalar `args` (not in tuple) def f(x, c): return x**c res = _tanhsinh(f, a, b, args=29) xp_assert_close(res.integral, xp.asarray(1/30)) # Test NaNs a = xp.asarray([xp.nan, 0, 0, 0]) b = xp.asarray([1, xp.nan, 1, 1]) c = xp.asarray([1, 1, xp.nan, 1]) res = _tanhsinh(f, a, b, args=(c,)) xp_assert_close(res.integral, xp.asarray([xp.nan, xp.nan, xp.nan, 0.5])) xp_assert_equal(res.error[:3], xp.full((3,), xp.nan)) xp_assert_equal(res.status, xp.asarray([-3, -3, -3, 0], dtype=xp.int32)) xp_assert_equal(res.success, xp.asarray([False, False, False, True])) xp_assert_equal(res.nfev[:3], xp.full((3,), 1, dtype=xp.int32)) # Test complex integral followed by real integral # Previously, h0 was of the result dtype. If the `dtype` were complex, # this could lead to complex cached abscissae/weights. If these get # cast to real dtype for a subsequent real integral, we would get a # ComplexWarning. Check that this is avoided. _pair_cache.xjc = xp.empty(0) _pair_cache.wj = xp.empty(0) _pair_cache.indices = [0] _pair_cache.h0 = None a, b = xp.asarray(0), xp.asarray(1) res = _tanhsinh(lambda x: xp.asarray(x*1j), a, b) xp_assert_close(res.integral, xp.asarray(0.5*1j)) res = _tanhsinh(lambda x: x, a, b) xp_assert_close(res.integral, xp.asarray(0.5)) # Test zero-size shape = (0, 3) res = _tanhsinh(lambda x: x, xp.asarray(0), xp.zeros(shape)) attrs = ['integral', 'error', 'success', 'status', 'nfev', 'maxlevel'] for attr in attrs: assert res[attr].shape == shape @pytest.mark.skip_xp_backends(np_only=True) def test_compress_nodes_weights_gh21496(self, xp): # See discussion in: # https://github.com/scipy/scipy/pull/21496#discussion_r1878681049 # This would cause "ValueError: attempt to get argmax of an empty sequence" # Check that this has been resolved. x = np.full(65, 3) x[-1] = 1000 _tanhsinh(np.sin, 1, x) def test_gh_22681_finite_error(self, xp): # gh-22681 noted a case in which the error was NaN on some platforms; # check that this does in fact fail in CI. c1 = complex(12, -10) c2 = complex(12, 39) def f(t): return xp.sin(c1 * (1 - t) + c2 * t) a, b = xp.asarray(0., dtype=xp.float64), xp.asarray(1., dtype=xp.float64) ref = _tanhsinh(f, a, b, atol=0, rtol=0, maxlevel=10) assert xp.isfinite(ref.error) # Previously, tanhsinh would not detect convergence res = _tanhsinh(f, a, b, rtol=1e-14) assert res.success assert res.maxlevel < 5 xp_assert_close(res.integral, ref.integral, rtol=1e-15) @make_xp_test_case(nsum)
TestTanhSinh
python
etianen__django-reversion
tests/test_app/tests/test_commands.py
{ "start": 7162, "end": 8068 }
class ____(TestModelMixin, TestBase): def testDeleteRevisionsKeep(self): with reversion.create_revision(): obj_1 = TestModel.objects.create() reversion.set_comment("obj_1 v1") with reversion.create_revision(): obj_1.save() reversion.set_comment("obj_1 v2") with reversion.create_revision(): obj_2 = TestModel.objects.create() reversion.set_comment("obj_2 v1") with reversion.create_revision(): obj_2.save() reversion.set_comment("obj_2 v2") with reversion.create_revision(): obj_3 = TestModel.objects.create() self.callCommand("deleterevisions", keep=1) self.assertSingleRevision((obj_1,), comment="obj_1 v2") self.assertSingleRevision((obj_2,), comment="obj_2 v2") self.assertSingleRevision((obj_3,))
DeleteRevisionsKeepTest
python
kamyu104__LeetCode-Solutions
Python/maximum-total-damage-with-spell-casting.py
{ "start": 102, "end": 606 }
class ____(object): def maximumTotalDamage(self, power): """ :type power: List[int] :rtype: int """ DIST = 2 power.sort() dp = collections.deque() mx = 0 for x in power: if dp and dp[-1][0] == x: dp[-1][1] += x continue while dp and dp[0][0]+DIST < x: mx = max(mx, dp.popleft()[1]) dp.append([x, mx+x]) return max(x for _, x in dp)
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 508731, "end": 509461 }
class ____(sgqlc.types.Type): """A month of contributions in a user's contribution graph.""" __schema__ = github_schema __field_names__ = ("first_day", "name", "total_weeks", "year") first_day = sgqlc.types.Field(sgqlc.types.non_null(Date), graphql_name="firstDay") """The date of the first day of this month.""" name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") """The name of the month.""" total_weeks = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalWeeks") """How many weeks started in this month.""" year = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="year") """The year the month occurred in."""
ContributionCalendarMonth
python
pytorch__pytorch
test/profiler/test_execution_trace.py
{ "start": 1385, "end": 30422 }
class ____(TestCase): def payload(self, device, use_device=False): u = torch.randn(3, 4, 5, requires_grad=True) with record_function("## TEST 1 ##", "1, 2, 3"): inf_val = float("inf") neg_inf_val = float("-inf") nan_val = float("nan") rf_handle = _record_function_with_args_enter( "## TEST 2 ##", 1, False, 2.5, [u, u], (u, u), "hello", u, inf_val, neg_inf_val, nan_val, ) x = torch.randn(10, 10, requires_grad=True) if use_device: x = x.to(device) y = torch.randn(10, 10, requires_grad=True) if use_device: y = y.to(device) z = x + y + x * y + x * y z.backward(z) gelu = nn.GELU() m = torch.randn(2) _ = gelu(m) if use_device: z = z.cpu() _record_function_with_args_exit(rf_handle) def get_execution_trace_root(self, output_file_name) -> Json: import gzip nodes = [] with ( gzip.open(output_file_name) if output_file_name.endswith(".gz") else open(output_file_name) ) as f: et_graph = json.load(f) assert "nodes" in et_graph nodes = et_graph["nodes"] return nodes def get_execution_trace_rf_ids(self, nodes: list[Json]) -> list[int]: """Returns a sorted list of rf_id (record function ids) in execution trace""" def get_rf_id(node): attrs = node["attrs"] for a in attrs: if a["name"] == "rf_id": return a["value"] return None rf_ids_ = ( get_rf_id(n) for n in nodes if n["name"] != "[pytorch|profiler|execution_trace|process]" and n["name"] != "[pytorch|profiler|execution_trace|thread]" ) return sorted(rf_id for rf_id in rf_ids_ if rf_id is not None) def get_kineto_rf_ids(self, events: list[Json]) -> list[int]: """Returns a sorted list of Record function IDs for CPU operators and user annotations""" ops_and_annotations = ( e for e in events if e.get("cat", "") in ["cpu_op", "user_annotation"] ) return sorted( e.get("args", {}).get("Record function id", -1) for e in ops_and_annotations ) @unittest.skipIf(not kineto_available(), "Kineto is required") @skipIfHpu @skipIfTorchDynamo("profiler gets ignored if dynamo activated") def test_execution_trace_with_kineto(self, device): trace_called_num = 0 def trace_handler(p): nonlocal trace_called_num trace_called_num += 1 use_device = ( torch.profiler.ProfilerActivity.CUDA or torch.profiler.ProfilerActivity.XPU in supported_activities() or torch.profiler.ProfilerActivity.HPU in supported_activities() ) # Create a temp file to save execution trace and kineto data. fp = tempfile.NamedTemporaryFile("w+t", suffix=".et.json", delete=False) fp.close() kt = tempfile.NamedTemporaryFile( mode="w+t", suffix=".kineto.json", delete=False ) kt.close() with profile( activities=supported_activities(), schedule=torch.profiler.schedule( skip_first=3, wait=1, warmup=1, active=2, repeat=1 ), on_trace_ready=trace_handler, execution_trace_observer=( ExecutionTraceObserver().register_callback(fp.name) ), ) as p: for idx in range(10): with record_function(f"## LOOP {idx} ##"): self.payload(device, use_device=use_device) p.step() self.assertEqual(fp.name, p.execution_trace_observer.get_output_file_path()) # Uncomment for debugging # print("Output kineto = ", kt.name) # print("Output ET = ", fp.name) p.export_chrome_trace(kt.name) self.assertEqual(trace_called_num, 1) nodes = self.get_execution_trace_root(fp.name) loop_count = 0 found_root_node = False for n in nodes: assert "name" in n if "[pytorch|profiler|execution_trace|process]" in n["name"]: found_root_node = True if n["name"].startswith("## LOOP "): loop_count += 1 self.assertTrue(found_root_node) # Since profiler trace is active for 2 iterations self.assertEqual(loop_count, 2) # Compare the collected Execution Trace and Kineto Trace # in terms of record func ID (rf_id) and External IDs # both of these should match for the same trace window. with open(kt.name) as f: kineto = json.load(f) events = kineto["traceEvents"] # Look up rf_ids in both Execution and Kineto trace as two lists. rf_ids_et = self.get_execution_trace_rf_ids(nodes) rf_ids_kineto = self.get_kineto_rf_ids(events) self.assertCountEqual(rf_ids_et, rf_ids_kineto) self.assertListEqual( rf_ids_et, rf_ids_kineto, msg=f"ET and kineto rf_id should exactly match\n" f" rf_ids_et = {rf_ids_et}\n" f" rf_ids_kineto = {rf_ids_kineto}\n", ) @unittest.skipIf(not kineto_available(), "Kineto is required") @skipIfHpu @skipIfTorchDynamo("profiler gets ignored if dynamo activated") def test_execution_trace_env_enabled_with_kineto(self, device): import os os.environ["ENABLE_PYTORCH_EXECUTION_TRACE"] = "1" os.environ["ENABLE_PYTORCH_EXECUTION_TRACE_EXTRAS"] = "1" trace_called_num = 0 def trace_handler(p): nonlocal trace_called_num trace_called_num += 1 use_device = ( torch.profiler.ProfilerActivity.CUDA or torch.profiler.ProfilerActivity.XPU in supported_activities() or torch.profiler.ProfilerActivity.HPU in supported_activities() ) # Create a temp file to save kineto data. kt = tempfile.NamedTemporaryFile( mode="w+t", suffix=".kineto.json", delete=False ) kt.close() with profile( activities=supported_activities(), schedule=torch.profiler.schedule( skip_first=3, wait=1, warmup=1, active=2, repeat=1 ), on_trace_ready=trace_handler, ) as p: for idx in range(10): with record_function(f"## LOOP {idx} ##"): self.payload(device, use_device=use_device) p.step() # Uncomment for debugging # print("Output kineto = ", kt.name) # print("Output ET = ", fp.name) p.export_chrome_trace(kt.name) self.assertEqual(trace_called_num, 1) et_path = p.execution_trace_observer.get_output_file_path() et_res_path = p.execution_trace_observer.get_resources_dir(et_path) # the path should be set up due to our env variables self.assertTrue(et_path is not None) # et_res_path should be an empty directory self.assertTrue(os.path.isdir(et_res_path)) self.assertEqual(len(os.listdir(et_res_path)), 0) # Compare the collected Execution Trace and Kineto Trace # in terms of record func nodes = self.get_execution_trace_root(et_path) loop_count = 0 found_root_node = False for n in nodes: assert "name" in n if "[pytorch|profiler|execution_trace|process]" in n["name"]: found_root_node = True if n["name"].startswith("## LOOP "): loop_count += 1 self.assertTrue(found_root_node) # Since profiler trace is active for 2 iterations self.assertEqual(loop_count, 2) # Compare the collected Execution Trace and Kineto Trace # in terms of record func ID (rf_id) and External IDs # both of these should match for the same trace window. with open(kt.name) as f: kineto = json.load(f) events = kineto["traceEvents"] # Look up rf_ids in both Execution and Kineto trace as two lists. rf_ids_et = self.get_execution_trace_rf_ids(nodes) rf_ids_kineto = self.get_kineto_rf_ids(events) self.assertCountEqual(rf_ids_et, rf_ids_kineto) self.assertListEqual( rf_ids_et, rf_ids_kineto, msg=f"ET and kineto rf_id should exactly match\n" f" rf_ids_et = {rf_ids_et}\n" f" rf_ids_kineto = {rf_ids_kineto}\n", ) def test_execution_trace_alone(self, device): use_device = ( torch.profiler.ProfilerActivity.CUDA or torch.profiler.ProfilerActivity.HPU in supported_activities() or torch.profiler.ProfilerActivity.XPU in supported_activities() ) # Create a temp file to save execution trace data. # Use a gzip file to test compression codepath fp = tempfile.NamedTemporaryFile("w", suffix=".et.json.gz", delete=False) fp.close() expected_loop_events = 0 et = ExecutionTraceObserver().register_callback(fp.name) et.start() for idx in range(5): expected_loop_events += 1 with record_function(f"## LOOP {idx} ##"): self.payload(device, use_device=use_device) et.stop() assert fp.name == et.get_output_file_path() et.unregister_callback() nodes = self.get_execution_trace_root(fp.name) loop_count = 0 # Expected tensor object tuple size, in th form of: # [tensor_id, storage_id, offset, numel, itemsize, device_str] tensor_tuple_size = 6 found_root_node = False for n in nodes: assert "name" in n if "[pytorch|profiler|execution_trace|process]" in n["name"]: found_root_node = True if n["name"].startswith("## LOOP "): loop_count += 1 # Check if tensor tuple representation size is correct. if n["name"] == "## TEST 2 ##": assert len(n["inputs"]["values"][3][0]) == tensor_tuple_size assert found_root_node assert loop_count == expected_loop_events def test_execution_trace_env_disabled(self, device): import os os.environ["ENABLE_PYTORCH_EXECUTION_TRACE"] = "0" os.environ["ENABLE_PYTORCH_EXECUTION_TRACE_EXTRAS"] = "0" use_device = ( torch.profiler.ProfilerActivity.CUDA or torch.profiler.ProfilerActivity.HPU in supported_activities() or torch.profiler.ProfilerActivity.XPU in supported_activities() ) with profile( activities=torch.profiler.supported_activities(), record_shapes=True, schedule=torch.profiler.schedule( skip_first=3, wait=1, warmup=1, active=2, repeat=1 ), ) as p: for idx in range(10): with record_function(f"## LOOP {idx} ##"): self.payload(device, use_device=use_device) p.step() self.assertTrue(p.execution_trace_observer is None) @unittest.skipIf(IS_WINDOWS, "torch.compile does not support WINDOWS") @unittest.skipIf( sys.version_info >= (3, 12), "torch.compile is not supported on python 3.12+" ) @unittest.skipIf( (not has_triton()) or (not TEST_CUDA and not TEST_XPU), "need triton and device(CUDA or XPU) availability to run", ) @skipCPUIf(True, "skip CPU device for testing profiling triton") def test_execution_trace_with_pt2(self, device): @torchdynamo.optimize("inductor") def fn(a, b, c): x = torch.nn.functional.linear(a, b) x = x + c return x.cos() a, b, c = (torch.randn(4, 4, requires_grad=True).to(device) for _ in range(3)) inputs = [a, b, c] with torch._inductor.config.patch(compile_threads=1): fn(*inputs) # Create a temp file to save execution trace data. fp = tempfile.NamedTemporaryFile("w+t", suffix="_et.json", delete=False) fp.close() et = ExecutionTraceObserver() et.register_callback(fp.name) et.set_extra_resource_collection(True) with profile( activities=torch.profiler.supported_activities(), record_shapes=True, schedule=torch.profiler.schedule( skip_first=3, wait=1, warmup=1, active=2, repeat=1 ), execution_trace_observer=et, ) as p: for idx in range(10): with record_function(f"## LOOP {idx} ##"): fn(*inputs) p.step() nodes = self.get_execution_trace_root(fp.name) found_captured_triton_kernel_node = False found_call_compiled_fx_graph = False for n in nodes: assert "name" in n if "triton_" in n["name"]: for attr in n["attrs"]: if attr["name"] == "kernel_file" and attr["value"] != "": found_captured_triton_kernel_node = True assert len(n["inputs"]["values"]) > 0 assert len(n["outputs"]["values"]) == 0 elif "Call CompiledFxGraph" in n["name"]: found_call_compiled_fx_graph = True assert found_captured_triton_kernel_node assert found_call_compiled_fx_graph @unittest.skipIf(IS_WINDOWS, "torch.compile does not support WINDOWS") @unittest.skipIf( sys.version_info >= (3, 12), "torch.compile is not supported on python 3.12+" ) @unittest.skipIf( (not has_triton()) or (not TEST_CUDA and not TEST_XPU), "need triton and device(CUDA or XPU) availability to run", ) @skipCPUIf(True, "skip CPU device for testing profiling triton") def test_execution_trace_env_enabled_with_pt2(self, device): # clean up the local cache for triton kernel from torch._inductor.codecache import PyCodeCache PyCodeCache.cache_clear(purge=True) import os os.environ["ENABLE_PYTORCH_EXECUTION_TRACE"] = "1" os.environ["ENABLE_PYTORCH_EXECUTION_TRACE_EXTRAS"] = "1" @torchdynamo.optimize("inductor") def fn(a, b, c): x = torch.nn.functional.linear(a, b) x = x + c return x.cos() a, b, c = (torch.randn(4, 4, requires_grad=True).to(device) for _ in range(3)) inputs = [a, b, c] with torch._inductor.config.patch( compile_threads=1, fx_graph_cache=False, fx_graph_remote_cache=False ): fn(*inputs) with profile( activities=torch.profiler.supported_activities(), record_shapes=True, schedule=torch.profiler.schedule( skip_first=3, wait=1, warmup=1, active=2, repeat=1 ), ) as p: for idx in range(10): with record_function(f"## LOOP {idx} ##"): fn(*inputs) p.step() et_path = p.execution_trace_observer.get_output_file_path() et_res_path = p.execution_trace_observer.get_resources_dir(et_path) # the path should be set up due to our env variables self.assertTrue(et_path is not None) # et_res_path should be an empty directory self.assertTrue(os.path.isdir(et_res_path)) self.assertEqual(len(os.listdir(et_res_path)), 2) nodes = self.get_execution_trace_root(et_path) found_captured_triton_kernel_node = False for n in nodes: assert "name" in n if "triton_" in n["name"]: for attr in n["attrs"]: if attr["name"] == "kernel_file" and attr["value"] != "": found_captured_triton_kernel_node = True assert len(n["inputs"]["values"]) > 0 assert len(n["outputs"]["values"]) == 0 assert found_captured_triton_kernel_node @unittest.skipIf(IS_WINDOWS, "torch.compile does not support WINDOWS") @unittest.skipIf( (not has_triton()) or (not TEST_CUDA), "need triton and device CUDA availability to run", ) @skipCPUIf(True, "skip CPU device for testing profiling triton") def test_triton_fx_graph_with_et(self, device): # clean up the local cache for triton kernel from torch._inductor.codecache import PyCodeCache PyCodeCache.cache_clear(purge=True) import os @torchdynamo.optimize("inductor") def fn(a, b, c): x = torch.nn.functional.linear(a, b) x = x.sin() x = x.t() + c * 1111 return x.cos() a, b, c = ( torch.randn(4, 4, requires_grad=False).to(torch.device("cuda:0")) for _ in range(3) ) inputs = [a, b, c] with torch._inductor.config.patch( compile_threads=1, fx_graph_cache=False, fx_graph_remote_cache=False ): fn(*inputs) fp = tempfile.NamedTemporaryFile("w+t", suffix="fx_graph_et.json", delete=False) fp.close() et = ExecutionTraceObserver() et.register_callback(fp.name) et.set_extra_resource_collection(True) with profile( activities=torch.profiler.supported_activities(), record_shapes=True, schedule=torch.profiler.schedule( skip_first=0, wait=1, warmup=1, active=1, repeat=1 ), execution_trace_observer=et, ) as p: for idx in range(10): with record_function(f"## LOOP {idx} ##"): fn(*inputs) p.step() et_path = p.execution_trace_observer.get_output_file_path() et_res_path = p.execution_trace_observer.get_resources_dir(et_path) # the path should be set up due to our env variables self.assertTrue(et_path is not None) # et_res_path should be an empty directory self.assertTrue(os.path.isdir(et_res_path)) for filename in os.listdir(et_res_path): file_path = os.path.join(et_res_path, filename) if os.path.isfile(file_path): with open(file_path) as file: fx_graph_found = False fx_graph = [] for line in file: line = line.strip() # There are two files in the directory, one is the source # code of the triton kernel, and the other is the source code for FX graph. # Only the FX graph file contains the string "# Graph fragment:". if line.startswith("# Graph fragment:"): fx_graph_found = True elif fx_graph_found and line.startswith("#"): fx_graph.append(line) else: fx_graph_found = False if len(fx_graph) > 0: assert ( fx_graph[0] == '# %mm : Tensor "f32[4, 4][4, 1]cuda:0" = PlaceHolder[target=mm]' ) assert ( fx_graph[1] == '# %arg2_1 : Tensor "f32[4, 4][4, 1]cuda:0" = PlaceHolder[target=arg2_1]' ) assert ( fx_graph[2] == '# %sin : Tensor "f32[4, 4][4, 1]cuda:0"[num_users=1] = call_function[target=torch.ops.aten.sin.default](args = (%mm,), kwargs = {})' # noqa: B950 ) assert ( fx_graph[3] == '# %permute_1 : Tensor "f32[4, 4][1, 4]cuda:0"[num_users=1] = call_function[target=torch.ops.aten.permute.default](args = (%sin, [1, 0]), kwargs = {})' # noqa: B950 ) assert ( fx_graph[4] == '# %mul : Tensor "f32[4, 4][4, 1]cuda:0"[num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%arg2_1, 1111), kwargs = {})' # noqa: B950 ) assert ( fx_graph[5] == '# %add : Tensor "f32[4, 4][1, 4]cuda:0"[num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%permute_1, %mul), kwargs = {})' # noqa: B950 ) assert ( fx_graph[6] == '# %cos : Tensor "f32[4, 4][1, 4]cuda:0"[num_users=1] = call_function[target=torch.ops.aten.cos.default](args = (%add,), kwargs = {})' # noqa: B950 ) assert fx_graph[7] == "# return %cos" def test_execution_trace_start_stop(self, device): use_device = ( torch.profiler.ProfilerActivity.CUDA or torch.profiler.ProfilerActivity.XPU in supported_activities() or torch.profiler.ProfilerActivity.HPU in supported_activities() ) # Create a temp file to save execution trace data. fp = tempfile.NamedTemporaryFile("w+t", suffix=".et.json", delete=False) fp.close() expected_loop_events = 0 et = ExecutionTraceObserver().register_callback(fp.name) for idx in range(10): if idx == 3: et.start() elif idx == 5: et.stop() elif idx == 8: et.start() elif idx == 9: et.stop() if et._execution_trace_running: expected_loop_events += 1 with record_function(f"## LOOP {idx} ##"): self.payload(device, use_device=use_device) assert fp.name == et.get_output_file_path() et.unregister_callback() nodes = self.get_execution_trace_root(fp.name) loop_count = 0 found_root_node = False for n in nodes: assert "name" in n if "[pytorch|profiler|execution_trace|process]" in n["name"]: found_root_node = True if n["name"].startswith("## LOOP "): loop_count += 1 assert found_root_node assert loop_count == expected_loop_events def test_execution_trace_repeat_in_loop(self, device): use_device = ( torch.profiler.ProfilerActivity.CUDA or torch.profiler.ProfilerActivity.XPU in supported_activities() or torch.profiler.ProfilerActivity.HPU in supported_activities() ) iter_list = {3, 4, 6, 8} expected_loop_events = len(iter_list) output_files = [] for idx in range(10): if idx in iter_list: # Create a temp file to save execution trace data. fp = tempfile.NamedTemporaryFile("w+t", suffix=".et.json", delete=False) fp.close() output_files.append(fp.name) et = ExecutionTraceObserver().register_callback(fp.name) et.start() with record_function(f"## LOOP {idx} ##"): self.payload(device, use_device=use_device) if idx in iter_list: et.stop() et.unregister_callback() event_count = 0 for et_file in output_files: nodes = self.get_execution_trace_root(et_file) found_root_node = False for n in nodes: assert "name" in n if "[pytorch|profiler|execution_trace|process]" in n["name"]: assert n["id"] == 1 found_root_node = True if n["name"].startswith("## LOOP "): event_count += 1 assert found_root_node assert event_count == expected_loop_events def test_execution_trace_no_capture(self): fp = tempfile.NamedTemporaryFile("w+t", suffix=".et.json", delete=False) fp.close() et = ExecutionTraceObserver().register_callback(fp.name) assert fp.name == et.get_output_file_path() et.unregister_callback() nodes = self.get_execution_trace_root(fp.name) for n in nodes: assert "name" in n if "[pytorch|profiler|execution_trace|process]" in n["name"]: found_root_node = True assert found_root_node @skipIfTorchDynamo("https://github.com/pytorch/pytorch/issues/124500") def test_execution_trace_nested_tensor(self): fp = tempfile.NamedTemporaryFile("w+t", suffix=".et.json", delete=False) fp.close() observer = ExecutionTraceObserver().register_callback(fp.name) def fn(nt): return nt.sin().cos() with torch.profiler.profile(execution_trace_observer=observer): for i in range(3): values = torch.rand((8 + i, 4 + i)) offsets = torch.tensor([0, 2, 4, 6, 8 + i]) nt = torch.nested.nested_tensor_from_jagged(values, offsets) fn(nt) nodes = self.get_execution_trace_root(fp.name) found_cos = False for n in nodes: assert "name" in n if "cos" in n["name"]: found_cos = True assert found_cos @unittest.skipIf( not TEST_CUDA, "need CUDA device availability to run", ) def test_execution_trace_record_integral_tensor_range(self): fp = tempfile.NamedTemporaryFile("w+t", suffix=".et.json", delete=False) fp.close() os.environ["ENABLE_PYTORCH_EXECUTION_TRACE_SAVE_INTEGRAL_TENSOR_RANGE"] = "1" t1 = torch.tensor([[1, 2], [3, 4]]).cuda() t2 = torch.tensor([[0, 0], [1, 0]]).cuda() with profile( activities=supported_activities(), schedule=torch.profiler.schedule( skip_first=0, wait=0, warmup=0, active=1, repeat=1 ), record_shapes=True, execution_trace_observer=( ExecutionTraceObserver().register_callback(fp.name) ), ) as p: torch.gather(t1, 1, t2) p.step() nodes = self.get_execution_trace_root(fp.name) for n in nodes: assert "name" in n if "aten::gather" in n["name"]: for attr in n["attrs"]: if attr["name"] == "tensor_range": assert attr["value"] == '{"0":[1,4],"1":[0,1]}' @unittest.skipIf( not TEST_CUDA, "need CUDA device availability to run", ) def test_execution_trace_record_integral_tensor_data(self): with tempfile.TemporaryDirectory() as temp_dir: fp_name = os.path.join(temp_dir, "test.et.json") os.environ["ENABLE_PYTORCH_EXECUTION_TRACE_SAVE_INTEGRAL_TENSOR_DATA"] = ( "aten::gather" ) et = ExecutionTraceObserver() et.register_callback(fp_name) et.set_extra_resource_collection(True) t1 = torch.tensor([[1, 2], [3, 4]]).cuda() t2 = torch.tensor([[0, 0], [1, 0]]).cuda() with profile( activities=supported_activities(), schedule=torch.profiler.schedule( skip_first=0, wait=0, warmup=0, active=1, repeat=1 ), record_shapes=True, execution_trace_observer=et, ) as p: torch.gather(t1, 1, t2) p.step() resourceDir = fp_name.replace(".json", "_resources") assert os.path.exists(resourceDir + "/nid_4_tid_0.dat") assert os.path.exists(resourceDir + "/nid_4_tid_1.dat") t1 = np.fromfile(resourceDir + "/nid_4_tid_0.dat", dtype=np.int64) t2 = np.fromfile(resourceDir + "/nid_4_tid_1.dat", dtype=np.int64) assert (t1 == np.array([1, 2, 3, 4])).all() assert (t2 == np.array([0, 0, 1, 0])).all() devices = ["cpu", "cuda"] if TEST_XPU: devices.append("xpu") if TEST_HPU: devices.append("hpu") instantiate_device_type_tests( TestExecutionTrace, globals(), allow_xpu="xpu" in devices, only_for=devices ) if __name__ == "__main__": run_tests()
TestExecutionTrace
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 173454, "end": 174020 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("owner_id", "setting_value", "client_mutation_id") owner_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="ownerId") setting_value = sgqlc.types.Field( sgqlc.types.non_null(IpAllowListForInstalledAppsEnabledSettingValue), graphql_name="settingValue", ) client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
UpdateIpAllowListForInstalledAppsEnabledSettingInput
python
Pylons__pyramid
tests/test_config/test_settings.py
{ "start": 18, "end": 2918 }
class ____(unittest.TestCase): def _makeOne(self, *arg, **kw): from pyramid.config import Configurator config = Configurator(*arg, **kw) return config def test__set_settings_as_None(self): config = self._makeOne() settings = config._set_settings(None) self.assertTrue(settings) def test__set_settings_does_not_uses_original_dict(self): config = self._makeOne() dummy = {} result = config._set_settings(dummy) self.assertTrue(dummy is not result) self.assertNotIn('pyramid.debug_all', dummy) def test__set_settings_as_dictwithvalues(self): config = self._makeOne() settings = config._set_settings({'a': '1'}) self.assertEqual(settings['a'], '1') def test_get_settings_nosettings(self): from pyramid.registry import Registry reg = Registry() config = self._makeOne(reg) self.assertEqual(config.get_settings(), None) def test_get_settings_withsettings(self): settings = {'a': 1} config = self._makeOne() config.registry.settings = settings self.assertEqual(config.get_settings(), settings) def test_add_settings_settings_already_registered(self): from pyramid.registry import Registry reg = Registry() config = self._makeOne(reg) config._set_settings({'a': 1}) config.add_settings({'b': 2}) settings = reg.settings self.assertEqual(settings['a'], 1) self.assertEqual(settings['b'], 2) def test_add_settings_settings_not_yet_registered(self): from pyramid.interfaces import ISettings from pyramid.registry import Registry reg = Registry() config = self._makeOne(reg) config.add_settings({'a': 1}) settings = reg.getUtility(ISettings) self.assertEqual(settings['a'], 1) def test_add_settings_settings_None(self): from pyramid.interfaces import ISettings from pyramid.registry import Registry reg = Registry() config = self._makeOne(reg) config.add_settings(None, a=1) settings = reg.getUtility(ISettings) self.assertEqual(settings['a'], 1) def test_settings_parameter_dict_is_never_updated(self): class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): # pragma: no cover raise RuntimeError("Cannot modify ReadOnlyDict") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ clear = __readonly__ update = __readonly__ setdefault = __readonly__ del __readonly__ initial = ReadOnlyDict() config = self._makeOne(settings=initial) config._set_settings({'a': '1'})
TestSettingsConfiguratorMixin
python
Netflix__metaflow
metaflow/_vendor/v3_7/typing_extensions.py
{ "start": 2464, "end": 6132 }
class ____: def __repr__(self): return "<sentinel>" _marker = _Sentinel() def _check_generic(cls, parameters, elen=_marker): """Check correct count for parameters of a generic cls (internal helper). This gives a nice error message in case of count mismatch. """ if not elen: raise TypeError(f"{cls} is not a generic class") if elen is _marker: if not hasattr(cls, "__parameters__") or not cls.__parameters__: raise TypeError(f"{cls} is not a generic class") elen = len(cls.__parameters__) alen = len(parameters) if alen != elen: if hasattr(cls, "__parameters__"): parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters) if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples): return raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};" f" actual {alen}, expected {elen}") if sys.version_info >= (3, 10): def _should_collect_from_parameters(t): return isinstance( t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) ) elif sys.version_info >= (3, 9): def _should_collect_from_parameters(t): return isinstance(t, (typing._GenericAlias, _types.GenericAlias)) else: def _should_collect_from_parameters(t): return isinstance(t, typing._GenericAlias) and not t._special def _collect_type_vars(types, typevar_types=None): """Collect all type variable contained in types in order of first appearance (lexicographic order). For example:: _collect_type_vars((T, List[S, T])) == (T, S) """ if typevar_types is None: typevar_types = typing.TypeVar tvars = [] for t in types: if ( isinstance(t, typevar_types) and t not in tvars and not _is_unpack(t) ): tvars.append(t) if _should_collect_from_parameters(t): tvars.extend([t for t in t.__parameters__ if t not in tvars]) return tuple(tvars) NoReturn = typing.NoReturn # Some unconstrained type variables. These are used by the container types. # (These are not for export.) T = typing.TypeVar('T') # Any type. KT = typing.TypeVar('KT') # Key type. VT = typing.TypeVar('VT') # Value type. T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. if sys.version_info >= (3, 11): from typing import Any else: class _AnyMeta(type): def __instancecheck__(self, obj): if self is Any: raise TypeError("typing_extensions.Any cannot be used with isinstance()") return super().__instancecheck__(obj) def __repr__(self): if self is Any: return "typing_extensions.Any" return super().__repr__() class Any(metaclass=_AnyMeta): """Special type indicating an unconstrained type. - Any is compatible with every type. - Any assumed to have all methods. - All values assumed to be instances of Any. Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks. """ def __new__(cls, *args, **kwargs): if cls is Any: raise TypeError("Any cannot be instantiated") return super().__new__(cls, *args, **kwargs) ClassVar = typing.ClassVar
_Sentinel
python
numpy__numpy
benchmarks/benchmarks/bench_function_base.py
{ "start": 2606, "end": 2991 }
class ____(Benchmark): def setup(self): self.e = np.arange(10000, dtype=np.float32) self.o = np.arange(21, dtype=np.float32) def time_quartile(self): np.percentile(self.e, [25, 75]) def time_percentile(self): np.percentile(self.e, [25, 35, 55, 65, 75]) def time_percentile_small(self): np.percentile(self.o, [25, 75])
Percentile
python
ansible__ansible
test/lib/ansible_test/_internal/commands/integration/cloud/scaleway.py
{ "start": 731, "end": 1538 }
class ____(CloudEnvironment): """Updates integration test environment after delegation. Will setup the config file as parameter.""" def get_environment_config(self) -> CloudEnvironmentConfig: """Return environment configuration for use in the test environment after delegation.""" parser = configparser.ConfigParser() parser.read(self.config_path) env_vars = dict( SCW_API_KEY=parser.get('default', 'key'), SCW_ORG=parser.get('default', 'org'), ) display.sensitive.add(env_vars['SCW_API_KEY']) ansible_vars = dict( scw_org=parser.get('default', 'org'), ) return CloudEnvironmentConfig( env_vars=env_vars, ansible_vars=ansible_vars, )
ScalewayCloudEnvironment
python
tensorflow__tensorflow
tensorflow/compiler/tests/jit_test.py
{ "start": 18567, "end": 23533 }
class ____(test.TestCase): def testLazyCompilation(self): @function.Defun(compiled=True) def CompiledFunction(x): return math_ops.log(x) with session_lib.Session(config=NoRewriteSessionConfig()) as sess: x = array_ops.placeholder(dtypes.float32) y = CompiledFunction(x) # The very first run of the cluster is always compiled (non-lazily). run_metadata_for_first_run = config_pb2.RunMetadata() sess.run( y, feed_dict={x: [2., 10., 19., 77., 100.]}, run_metadata=run_metadata_for_first_run, options=config_pb2.RunOptions( trace_level=config_pb2.RunOptions.FULL_TRACE)) self.assertTrue( InLabels( RunMetadataLabels(run_metadata_for_first_run), "_XlaCompile")) self.assertTrue( InLabels(RunMetadataLabels(run_metadata_for_first_run), "_XlaRun")) run_metadata_before_warmup = config_pb2.RunMetadata() sess.run( y, feed_dict={x: [2., 10.]}, run_metadata=run_metadata_before_warmup, options=config_pb2.RunOptions( trace_level=config_pb2.RunOptions.FULL_TRACE)) self.assertTrue( InLabels( RunMetadataLabels(run_metadata_before_warmup), "_XlaCompile")) self.assertFalse( InLabels(RunMetadataLabels(run_metadata_before_warmup), "_XlaRun")) # We compile when we see the same shape a second time. run_metadata_after_warmup = config_pb2.RunMetadata() sess.run( y, feed_dict={x: [2., 10.]}, run_metadata=run_metadata_after_warmup, options=config_pb2.RunOptions( trace_level=config_pb2.RunOptions.FULL_TRACE)) self.assertTrue( InLabels(RunMetadataLabels(run_metadata_after_warmup), "_XlaCompile")) self.assertTrue( InLabels(RunMetadataLabels(run_metadata_after_warmup), "_XlaRun")) run_metadata_for_new_shape = config_pb2.RunMetadata() sess.run( y, feed_dict={x: [2., 10., 12.]}, run_metadata=run_metadata_for_new_shape, options=config_pb2.RunOptions( trace_level=config_pb2.RunOptions.FULL_TRACE)) self.assertTrue( InLabels( RunMetadataLabels(run_metadata_for_new_shape), "_XlaCompile")) self.assertFalse( InLabels(RunMetadataLabels(run_metadata_for_new_shape), "_XlaRun")) def testIsMegamorphic(self): @function.Defun(compiled=True) def CompiledFunction(x): return math_ops.log(x) with session_lib.Session(config=NoRewriteSessionConfig()) as sess: x = array_ops.placeholder(dtypes.float32) y = CompiledFunction(x) # Make the cluster go megamorphic by running it with lots of shape # signatures where the cluster is executed with each signature only a few # times. Then check that we don't compile the cluster ever again. for shape in range(10, 50): for _ in range(0, 49): sess.run(y, feed_dict={x: [0.] * shape}) for _ in range(0, 50): run_metadata = config_pb2.RunMetadata() sess.run( y, feed_dict={x: [0.] * 60}, run_metadata=run_metadata, options=config_pb2.RunOptions( trace_level=config_pb2.RunOptions.FULL_TRACE)) self.assertTrue( InLabels(RunMetadataLabels(run_metadata), "_XlaCompile")) self.assertFalse(InLabels(RunMetadataLabels(run_metadata), "_XlaRun")) def testIsNotMegamorphic(self): @function.Defun(compiled=True) def CompiledFunction(x): return math_ops.log(x) with session_lib.Session(config=NoRewriteSessionConfig()) as sess: x = array_ops.placeholder(dtypes.float32) y = CompiledFunction(x) # Run the cluster with lots of shape signatures, but in a way that it # isn't megamorphic (i.e. each shape signature sees a lot of executions). # Then check that the cluster has not been marked as megamorphic. for shape in range(10, 50): for _ in range(0, 1000): sess.run(y, feed_dict={x: [0.] * shape}) for _ in range(0, 10): sess.run(y, feed_dict={x: [0.] * 60}) run_metadata = config_pb2.RunMetadata() sess.run( y, feed_dict={x: [0.] * 60}, run_metadata=run_metadata, options=config_pb2.RunOptions( trace_level=config_pb2.RunOptions.FULL_TRACE)) self.assertTrue(InLabels(RunMetadataLabels(run_metadata), "_XlaCompile")) self.assertTrue(InLabels(RunMetadataLabels(run_metadata), "_XlaRun")) if __name__ == "__main__": os.environ["TF_XLA_FLAGS"] = ("--tf_xla_enable_lazy_compilation=true " + os.environ.get("TF_XLA_FLAGS", "")) # This test is using Tensorflow sessions which are not compatible with eager # mode. ops.disable_eager_execution() test.main()
LazyCompilationTest
python
getsentry__sentry
src/sentry/metrics/sentry_sdk.py
{ "start": 162, "end": 4536 }
class ____(MetricsBackend): def __init__(self, **kwargs: Any) -> None: self._experimental_sample_rate = kwargs.pop("experimental_sample_rate", 0.0) self._deny_list = tuple(kwargs.pop("deny_list", [])) super().__init__(**kwargs) def _is_denied(self, key: str) -> bool: return key.startswith(self._deny_list) def _should_send(self, key: str) -> bool: if self._is_denied(key): return False return self._should_sample_experimental() def _should_sample_experimental(self) -> bool: """Sample based on passed in sample rate, can't use options as they hit the db too much.""" return self._experimental_sample_rate >= 1.0 or random() < self._experimental_sample_rate def incr( self, key: str, instance: str | None = None, tags: Tags | None = None, amount: float | int = 1, sample_rate: float = 1, unit: str | None = None, stacklevel: int = 0, ) -> None: full_key = self._get_key(key) if not self._should_send(full_key): return if not self._should_sample(sample_rate): return metric_attributes = dict(tags) if tags else {} if instance: metric_attributes["instance"] = instance if sample_rate != 1.0: metric_attributes["sentry.client_sample_rate"] = sample_rate metrics.count( full_key, amount, unit=unit, attributes=metric_attributes, ) def timing( self, key: str, value: float, instance: str | None = None, tags: Tags | None = None, sample_rate: float = 1, stacklevel: int = 0, ) -> None: full_key = self._get_key(key) if not self._should_send(full_key): return if not self._should_sample(sample_rate): return metric_attributes = dict(tags) if tags else {} if instance: metric_attributes["instance"] = instance if sample_rate != 1.0: metric_attributes["sentry.client_sample_rate"] = sample_rate metric_attributes["is_timing"] = True metrics.distribution( full_key, value, unit="millisecond", attributes=metric_attributes, ) def gauge( self, key: str, value: float, instance: str | None = None, tags: Tags | None = None, sample_rate: float = 1, unit: str | None = None, stacklevel: int = 0, ) -> None: full_key = self._get_key(key) if not self._should_send(full_key): return if not self._should_sample(sample_rate): return metric_attributes = dict(tags) if tags else {} if instance: metric_attributes["instance"] = instance if sample_rate != 1.0: metric_attributes["sentry.client_sample_rate"] = sample_rate metrics.gauge( full_key, value, unit=unit, attributes=metric_attributes, ) def distribution( self, key: str, value: float, instance: str | None = None, tags: Tags | None = None, sample_rate: float = 1, unit: str | None = None, stacklevel: int = 0, ) -> None: full_key = self._get_key(key) if not self._should_send(full_key): return if not self._should_sample(sample_rate): return metric_attributes = dict(tags) if tags else {} if instance: metric_attributes["instance"] = instance if sample_rate != 1.0: metric_attributes["sentry.client_sample_rate"] = sample_rate metrics.distribution( full_key, value, unit=unit, attributes=metric_attributes, ) def event( self, title: str, message: str, alert_type: str | None = None, aggregation_key: str | None = None, source_type_name: str | None = None, priority: str | None = None, instance: str | None = None, tags: Tags | None = None, stacklevel: int = 0, ) -> None: pass
SentrySDKMetricsBackend
python
fluentpython__example-code
14-it-generator/fibo_by_hand.py
{ "start": 237, "end": 317 }
class ____: def __iter__(self): return FibonacciGenerator()
Fibonacci
python
huggingface__transformers
src/transformers/models/wav2vec2/modeling_wav2vec2.py
{ "start": 69433, "end": 75980 }
class ____(Wav2Vec2PreTrainedModel): def __init__(self, config, target_lang: Optional[str] = None): r""" target_lang (`str`, *optional*): Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or adapter.<lang>.bin. Only relevant when using an instance of [`Wav2Vec2ForCTC`] with adapters. Uses 'eng' by default. """ super().__init__(config) self.wav2vec2 = Wav2Vec2Model(config) self.dropout = nn.Dropout(config.final_dropout) self.target_lang = target_lang if config.vocab_size is None: raise ValueError( f"You are trying to instantiate {self.__class__} with a configuration that " "does not define the vocabulary size of the language model head. Please " "instantiate the model as follows: `Wav2Vec2ForCTC.from_pretrained(..., vocab_size=vocab_size)`. " "or define `vocab_size` of your model's configuration." ) output_hidden_size = ( config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size ) self.lm_head = nn.Linear(output_hidden_size, config.vocab_size) # Initialize weights and apply final processing self.post_init() def tie_weights(self, **kwargs): """ This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when passing `target_lang=...` to `from_pretrained(...)`. This method is **not** supposed to be called by the user and is prone to be changed in the future. """ # Note that `tie_weights` is usually used to tie input and output embedding weights. The method is re-purposed to # correctly load adapter layers for Wav2Vec2 so that we do not have to introduce a new API to # [`PreTrainedModel`]. While slightly hacky, Wav2Vec2 never has to tie input and output embeddings, so that it is # ok to repurpose this function here. target_lang = self.target_lang if target_lang is not None and getattr(self.config, "adapter_attn_dim", None) is None: raise ValueError(f"Cannot pass `target_lang`: {target_lang} if `config.adapter_attn_dim` is not defined.") elif target_lang is None and getattr(self.config, "adapter_attn_dim", None) is not None: logger.info("By default `target_lang` is set to 'eng'.") elif target_lang is not None: self.load_adapter(target_lang, force_load=True) def freeze_feature_encoder(self): """ Calling this function will disable the gradient computation for the feature encoder so that its parameter will not be updated during training. """ self.wav2vec2.feature_extractor._freeze_parameters() def freeze_base_model(self): """ Calling this function will disable the gradient computation for the base model so that its parameters will not be updated during training. Only the classification head will be updated. """ for param in self.wav2vec2.parameters(): param.requires_grad = False @auto_docstring def forward( self, input_values: Optional[torch.Tensor], attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, labels: Optional[torch.Tensor] = None, ) -> Union[tuple, CausalLMOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*): Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size - 1]`. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict if labels is not None and labels.max() >= self.config.vocab_size: raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}") outputs = self.wav2vec2( input_values, attention_mask=attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = outputs[0] hidden_states = self.dropout(hidden_states) logits = self.lm_head(hidden_states) loss = None if labels is not None: # retrieve loss input_lengths from attention_mask attention_mask = ( attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long) ) input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long) # assuming that padded tokens are filled with -100 # when not being attended to labels_mask = labels >= 0 target_lengths = labels_mask.sum(-1) flattened_targets = labels.masked_select(labels_mask) # ctc_loss doesn't support fp16 log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1) with torch.backends.cudnn.flags(enabled=False): loss = nn.functional.ctc_loss( log_probs, flattened_targets, input_lengths, target_lengths, blank=self.config.pad_token_id, reduction=self.config.ctc_loss_reduction, zero_infinity=self.config.ctc_zero_infinity, ) if not return_dict: output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:] return ((loss,) + output) if loss is not None else output return CausalLMOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions ) @auto_docstring( custom_intro=""" Wav2Vec2 Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting. """ )
Wav2Vec2ForCTC
python
sanic-org__sanic
tests/test_config.py
{ "start": 892, "end": 12028 }
class ____: def __init__(self, answer): self.answer = int(answer) def test_load_from_object(app: Sanic): app.config.load(ConfigTest) assert "CONFIG_VALUE" in app.config assert app.config.CONFIG_VALUE == "should be used" assert "not_for_config" not in app.config def test_load_from_object_string(app: Sanic): app.config.load("tests.test_config.ConfigTest") assert "CONFIG_VALUE" in app.config assert app.config.CONFIG_VALUE == "should be used" assert "not_for_config" not in app.config def test_load_from_instance(app: Sanic): app.config.load(ConfigTest()) assert "CONFIG_VALUE" in app.config assert app.config.CONFIG_VALUE == "should be used" assert app.config.ANOTHER_VALUE == "should be used" assert "not_for_config" not in app.config assert "another_not_for_config" not in app.config def test_load_from_object_string_exception(app: Sanic): with pytest.raises(ImportError): app.config.load("test_config.Config.test") def test_auto_env_prefix(): environ["SANIC_TEST_ANSWER"] = "42" app = Sanic(name="Test") assert app.config.TEST_ANSWER == 42 del environ["SANIC_TEST_ANSWER"] def test_auto_bool_env_prefix(): environ["SANIC_TEST_ANSWER"] = "True" app = Sanic(name="Test") assert app.config.TEST_ANSWER is True del environ["SANIC_TEST_ANSWER"] @pytest.mark.parametrize("env_prefix", [None, ""]) def test_empty_load_env_prefix(env_prefix): environ["SANIC_TEST_ANSWER"] = "42" app = Sanic(name="Test", env_prefix=env_prefix) assert getattr(app.config, "TEST_ANSWER", None) is None del environ["SANIC_TEST_ANSWER"] def test_env_prefix(): environ["MYAPP_TEST_ANSWER"] = "42" app = Sanic(name="Test", env_prefix="MYAPP_") assert app.config.TEST_ANSWER == 42 del environ["MYAPP_TEST_ANSWER"] def test_env_prefix_float_values(): environ["MYAPP_TEST_ROI"] = "2.3" app = Sanic(name="Test", env_prefix="MYAPP_") assert app.config.TEST_ROI == 2.3 del environ["MYAPP_TEST_ROI"] def test_env_prefix_string_value(): environ["MYAPP_TEST_TOKEN"] = "somerandomtesttoken" app = Sanic(name="Test", env_prefix="MYAPP_") assert app.config.TEST_TOKEN == "somerandomtesttoken" del environ["MYAPP_TEST_TOKEN"] def test_env_w_custom_converter(): environ["SANIC_TEST_ANSWER"] = "42" config = Config(converters=[UltimateAnswer]) app = Sanic(name="Test", config=config) assert isinstance(app.config.TEST_ANSWER, UltimateAnswer) assert app.config.TEST_ANSWER.answer == 42 del environ["SANIC_TEST_ANSWER"] def test_env_lowercase(): environ["SANIC_test_answer"] = "42" app = Sanic(name="Test") assert "test_answer" not in app.config del environ["SANIC_test_answer"] def test_add_converter_multiple_times(caplog): def converter(): ... message = ( "Configuration value converter 'converter' has already been registered" ) config = Config() config.register_type(converter) with caplog.at_level(logging.WARNING): config.register_type(converter) assert ("sanic.error", logging.WARNING, message) in caplog.record_tuples assert len(config._converters) == 5 def test_load_from_file(app: Sanic): config = dedent( """ VALUE = 'some value' condition = 1 == 1 if condition: CONDITIONAL = 'should be set' """ ) with temp_path() as config_path: config_path.write_text(config) app.config.load(str(config_path)) assert "VALUE" in app.config assert app.config.VALUE == "some value" assert "CONDITIONAL" in app.config assert app.config.CONDITIONAL == "should be set" assert "condition" not in app.config def test_load_from_missing_file(app: Sanic): with pytest.raises(IOError): app.config.load("non-existent file") def test_load_from_envvar(app: Sanic): config = "VALUE = 'some value'" with temp_path() as config_path: config_path.write_text(config) environ["APP_CONFIG"] = str(config_path) app.config.load("${APP_CONFIG}") assert "VALUE" in app.config assert app.config.VALUE == "some value" def test_load_from_missing_envvar(app: Sanic): with pytest.raises(IOError) as e: app.config.load("non-existent variable") assert str(e.value) == ( "The environment variable 'non-existent " "variable' is not set and thus configuration " "could not be loaded." ) def test_load_config_from_file_invalid_syntax(app: Sanic): config = "VALUE = some value" with temp_path() as config_path: config_path.write_text(config) with pytest.raises(PyFileError): app.config.load(config_path) def test_overwrite_exisiting_config(app: Sanic): app.config.DEFAULT = 1 class Config: DEFAULT = 2 app.config.load(Config) assert app.config.DEFAULT == 2 def test_overwrite_exisiting_config_ignore_lowercase(app: Sanic): app.config.default = 1 class Config: default = 2 app.config.load(Config) assert app.config.default == 1 def test_missing_config(app: Sanic): with pytest.raises(AttributeError, match="Config has no 'NON_EXISTENT'"): _ = app.config.NON_EXISTENT def test_config_defaults(): """ load DEFAULT_CONFIG """ conf = Config() for key, value in DEFAULT_CONFIG.items(): assert getattr(conf, key) == value def test_config_custom_defaults(): """ we should have all the variables from defaults rewriting them with custom defaults passed in Config """ custom_defaults = { "REQUEST_MAX_SIZE": 1, "KEEP_ALIVE": False, "ACCESS_LOG": False, } conf = Config(defaults=custom_defaults) for key, value in DEFAULT_CONFIG.items(): if key in custom_defaults.keys(): value = custom_defaults[key] assert getattr(conf, key) == value def test_config_custom_defaults_with_env(): """ test that environment variables has higher priority than DEFAULT_CONFIG and passed defaults dict """ custom_defaults = { "REQUEST_MAX_SIZE123": 1, "KEEP_ALIVE123": False, "ACCESS_LOG123": False, } environ_defaults = { "SANIC_REQUEST_MAX_SIZE123": "2", "SANIC_KEEP_ALIVE123": "True", "SANIC_ACCESS_LOG123": "False", } for key, value in environ_defaults.items(): environ[key] = value conf = Config(defaults=custom_defaults) for key, value in DEFAULT_CONFIG.items(): if "SANIC_" + key in environ_defaults.keys(): value = environ_defaults["SANIC_" + key] try: value = int(value) except ValueError: if value in ["True", "False"]: value = value == "True" assert getattr(conf, key) == value for key, value in environ_defaults.items(): del environ[key] @pytest.mark.parametrize("access_log", (True, False)) def test_config_access_log_passing_in_run(app: Sanic, access_log): assert app.config.ACCESS_LOG is False @app.listener("after_server_start") async def _request(sanic, loop): app.stop() app.run(port=1340, access_log=access_log, single_process=True) assert app.config.ACCESS_LOG is access_log @pytest.mark.asyncio async def test_config_access_log_passing_in_create_server(app: Sanic): assert app.config.ACCESS_LOG is False @app.listener("after_server_start") async def _request(sanic, loop): app.stop() await app.create_server( port=get_port(), access_log=False, return_asyncio_server=True ) assert app.config.ACCESS_LOG is False await app.create_server( port=get_port(), access_log=True, return_asyncio_server=True ) assert app.config.ACCESS_LOG is True def test_config_rewrite_keep_alive(): config = Config() assert config.KEEP_ALIVE == DEFAULT_CONFIG["KEEP_ALIVE"] config = Config(keep_alive=True) assert config.KEEP_ALIVE is True config = Config(keep_alive=False) assert config.KEEP_ALIVE is False # use defaults config = Config(defaults={"KEEP_ALIVE": False}) assert config.KEEP_ALIVE is False config = Config(defaults={"KEEP_ALIVE": True}) assert config.KEEP_ALIVE is True _test_setting_as_dict = {"TEST_SETTING_VALUE": 1} _test_setting_as_class = type("C", (), {"TEST_SETTING_VALUE": 1}) _test_setting_as_module = str( Path(__file__).parent / "static/app_test_config.py" ) @pytest.mark.parametrize( "conf_object", [ _test_setting_as_dict, _test_setting_as_class, _test_setting_as_module, ], ids=["from_dict", "from_class", "from_file"], ) def test_update(app: Sanic, conf_object): app.update_config(conf_object) assert app.config["TEST_SETTING_VALUE"] == 1 def test_update_from_lowercase_key(app: Sanic): d = {"test_setting_value": 1} app.update_config(d) assert "test_setting_value" not in app.config def test_config_set_methods(app: Sanic, monkeypatch: MonkeyPatch): post_set = Mock() monkeypatch.setattr(Config, "_post_set", post_set) app.config.FOO = 1 post_set.assert_called_once_with("FOO", 1) post_set.reset_mock() app.config["FOO"] = 2 post_set.assert_called_once_with("FOO", 2) post_set.reset_mock() app.config.update({"FOO": 3}) post_set.assert_called_once_with("FOO", 3) post_set.reset_mock() app.config.update([("FOO", 4)]) post_set.assert_called_once_with("FOO", 4) post_set.reset_mock() app.config.update(FOO=5) post_set.assert_called_once_with("FOO", 5) post_set.reset_mock() app.config.update({"FOO": 6}, {"BAR": 7}) post_set.assert_has_calls( calls=[ call("FOO", 6), call("BAR", 7), ] ) post_set.reset_mock() app.config.update({"FOO": 8}, BAR=9) post_set.assert_has_calls( calls=[ call("FOO", 8), call("BAR", 9), ], any_order=True, ) post_set.reset_mock() app.config.update_config({"FOO": 10}) post_set.assert_called_once_with("FOO", 10) def test_negative_proxy_count(app: Sanic): app.config.PROXIES_COUNT = -1 message = ( "PROXIES_COUNT cannot be negative. " "https://sanic.readthedocs.io/en/latest/sanic/config.html" "#proxy-configuration" ) with pytest.raises(ValueError, match=message): app.prepare() @pytest.mark.parametrize( "passed,expected", ( ("auto", LocalCertCreator.AUTO), ("mkcert", LocalCertCreator.MKCERT), ("trustme", LocalCertCreator.TRUSTME), ("AUTO", LocalCertCreator.AUTO), ("MKCERT", LocalCertCreator.MKCERT), ("TRUSTME", LocalCertCreator.TRUSTME), ), ) def test_convert_local_cert_creator(passed, expected): os.environ["SANIC_LOCAL_CERT_CREATOR"] = passed app = Sanic("Test") assert app.config.LOCAL_CERT_CREATOR is expected del os.environ["SANIC_LOCAL_CERT_CREATOR"]
UltimateAnswer