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
wandb__wandb
wandb/sync/sync.py
{ "start": 657, "end": 1036 }
class ____: def __init__(self, path, synced=None): self.path = path self.synced = synced self.offline = os.path.basename(path).startswith("offline-") self.datetime = datetime.datetime.strptime( os.path.basename(path).split("run-")[1].split("-")[0], "%Y%m%d_%H%M%S" ) def __str__(self): return self.path
_LocalRun
python
getsentry__sentry
tests/sentry/features/test_flagpole_context.py
{ "start": 758, "end": 1517 }
class ____(TestCase): def test_sentry_flagpole_context_builder(self) -> None: org = self.create_organization() project = self.create_project(organization=org, platform="php") sentry_flagpole_builder = get_sentry_flagpole_context_builder() sentry_context = sentry_flagpole_builder.build( SentryContextData(organization=org, project=project) ) assert sentry_context.get("organization_slug") == org.slug assert sentry_context.get("organization_slug") == org.slug assert sentry_context.get("project_slug") == project.slug assert sentry_context.get("project_id") == project.id assert sentry_context.get("project_platform") == project.platform
TestSentryFlagpoleContext
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_bitstring.py
{ "start": 424, "end": 5891 }
class ____(fixtures.TestBase): @testing.combinations( lambda: BitString("111") == BitString("111"), lambda: BitString("111") == "111", lambda: BitString("111") != BitString("110"), lambda: BitString("111") != "110", lambda: hash(BitString("011")) == hash(BitString("011")), lambda: hash(BitString("011")) == hash("011"), lambda: BitString("011")[1] == BitString("1"), lambda: BitString("010") > BitString("001"), lambda: "010" > BitString("001"), lambda: "011" <= BitString("011"), lambda: "011" <= BitString("101"), ) def test_comparisons(self, case): is_true(case()) def test_sorting(self): eq_( sorted([BitString("110"), BitString("010"), "111", "101"]), [BitString("010"), "101", BitString("110"), "111"], ) def test_str_conversion(self): x = BitString("1110111") eq_(str(x), "1110111") assert_raises(ValueError, lambda: BitString("1246")) def test_same_instance_returned(self): x = BitString("1110111") y = BitString("1110111") z = BitString(x) eq_(x, y) eq_(x, z) is_not(x, y) is_(x, z) @testing.combinations( (0, 0, BitString("")), (0, 1, BitString("0")), (1, 1, BitString("1")), (1, 0, ValueError), (1, -1, ValueError), (2, 1, ValueError), (-1, 4, ValueError), (1, 4, BitString("0001")), (1, 10, BitString("0000000001")), (127, 8, BitString("01111111")), (127, 10, BitString("0001111111")), (1404, 8, ValueError), (1404, 12, BitString("010101111100")), argnames="source, bitlen, result_or_error", ) def test_int_conversion(self, source, bitlen, result_or_error): if isinstance(result_or_error, type): assert_raises( result_or_error, lambda: BitString.from_int(source, bitlen) ) return result = result_or_error bits = BitString.from_int(source, bitlen) eq_(bits, result) eq_(int(bits), source) @testing.combinations( (b"", -1, BitString("")), (b"", 4, BitString("0000")), (b"\x00", 1, BitString("0")), (b"\x01", 1, BitString("1")), (b"\x01", 4, BitString("0001")), (b"\x01", 10, BitString("0000000001")), (b"\x01", -1, BitString("00000001")), (b"\xff", 10, BitString("0011111111")), (b"\xaf\x04", 8, ValueError), (b"\xaf\x04", 16, BitString("1010111100000100")), (b"\xaf\x04", 20, BitString("00001010111100000100")), argnames="source, bitlen, result_or_error", ) def test_bytes_conversion(self, source, bitlen, result_or_error): if isinstance(result_or_error, type): assert_raises( result_or_error, lambda: BitString.from_bytes(source, length=bitlen), ) return result = result_or_error bits = BitString.from_bytes(source, bitlen) eq_(bits, result) # Expecting a roundtrip conversion in this case is nonsensical if source == b"" and bitlen > 0: return eq_(bits.to_bytes(len(source)), source) def test_get_set_bit(self): eq_(BitString("1010").get_bit(2), "1") eq_(BitString("0101").get_bit(2), "0") assert_raises(IndexError, lambda: BitString("0").get_bit(1)) eq_(BitString("0101").set_bit(3, "0"), BitString("0100")) eq_(BitString("0101").set_bit(3, "1"), BitString("0101")) assert_raises(IndexError, lambda: BitString("1111").set_bit(5, "1")) def test_string_methods(self): eq_(BitString("01100").lstrip(), BitString("1100")) eq_(BitString("01100").rstrip(), BitString("011")) eq_(BitString("01100").strip(), BitString("11")) eq_(BitString("11100").removeprefix("111"), BitString("00")) eq_(BitString("11100").removeprefix("0"), BitString("11100")) eq_(BitString("11100").removesuffix("10"), BitString("11100")) eq_(BitString("11100").removesuffix("00"), BitString("111")) eq_( BitString("010101011").replace("0101", "11", 1), BitString("1101011"), ) eq_( BitString("01101101").split("1", 2), [BitString("0"), BitString(""), BitString("01101")], ) eq_(BitString("0110").split("11"), [BitString("0"), BitString("0")]) eq_(BitString("111").zfill(8), BitString("00000111")) def test_string_operators(self): is_true("1" in BitString("001")) is_true("0" in BitString("110")) is_false("1" in BitString("000")) is_true("001" in BitString("01001")) is_true(BitString("001") in BitString("01001")) is_false(BitString("000") in BitString("01001")) eq_(BitString("010") + "001", BitString("010001")) eq_("001" + BitString("010"), BitString("001010")) def test_bitwise_operators(self): eq_(~BitString("0101"), BitString("1010")) eq_(BitString("010") & BitString("011"), BitString("010")) eq_(BitString("010") | BitString("011"), BitString("011")) eq_(BitString("010") ^ BitString("011"), BitString("001")) eq_(BitString("001100") << 2, BitString("110000")) eq_(BitString("001100") >> 2, BitString("000011"))
BitStringTests
python
huggingface__transformers
examples/pytorch/speech-recognition/run_speech_recognition_seq2seq.py
{ "start": 9022, "end": 25574 }
class ____: """ Data collator that will dynamically pad the inputs received. Args: processor ([`WhisperProcessor`]) The processor used for processing the data. decoder_start_token_id (`int`) The begin-of-sentence of the decoder. forward_attention_mask (`bool`) Whether to return attention_mask. """ processor: Any decoder_start_token_id: int forward_attention_mask: bool def __call__(self, features: list[dict[str, Union[list[int], torch.Tensor]]]) -> dict[str, torch.Tensor]: # split inputs and labels since they have to be of different lengths and need # different padding methods model_input_name = self.processor.model_input_names[0] input_features = [{model_input_name: feature[model_input_name]} for feature in features] label_features = [{"input_ids": feature["labels"]} for feature in features] batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt") if self.forward_attention_mask: batch["attention_mask"] = torch.LongTensor([feature["attention_mask"] for feature in features]) labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt") # replace padding with -100 to ignore loss correctly labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100) # if bos token is appended in previous tokenization step, # cut bos token here as it's append later anyways if (labels[:, 0] == self.decoder_start_token_id).all().cpu().item(): labels = labels[:, 1:] batch["labels"] = labels return batch def main(): # 1. Parse input arguments # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # 2. Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) log_level = training_args.get_process_log_level() logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.setLevel(logging.INFO if is_main_process(training_args.local_process_index) else logging.WARN) # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_process_index}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, " f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}" ) logger.info(f"Training/evaluation parameters {training_args}") # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_process_index): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s", training_args) # Set seed before initializing model. set_seed(training_args.seed) # 4. Load dataset raw_datasets = DatasetDict() if training_args.do_train: raw_datasets["train"] = load_dataset( data_args.dataset_name, data_args.dataset_config_name, split=data_args.train_split_name, cache_dir=model_args.cache_dir, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) if training_args.do_eval: raw_datasets["eval"] = load_dataset( data_args.dataset_name, data_args.dataset_config_name, split=data_args.eval_split_name, cache_dir=model_args.cache_dir, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) if data_args.audio_column_name not in next(iter(raw_datasets.values())).column_names: raise ValueError( f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. " "Make sure to set `--audio_column_name` to the correct audio column - one of " f"{', '.join(next(iter(raw_datasets.values())).column_names)}." ) if data_args.text_column_name not in next(iter(raw_datasets.values())).column_names: raise ValueError( f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. " "Make sure to set `--text_column_name` to the correct text column - one of " f"{', '.join(next(iter(raw_datasets.values())).column_names)}." ) # 5. Load pretrained model, tokenizer, and feature extractor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently config = AutoConfig.from_pretrained( (model_args.config_name if model_args.config_name else model_args.model_name_or_path), cache_dir=model_args.cache_dir, revision=model_args.model_revision, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) # SpecAugment for whisper models if getattr(config, "model_type", None) == "whisper": config.update({"apply_spec_augment": model_args.apply_spec_augment}) feature_extractor = AutoFeatureExtractor.from_pretrained( (model_args.feature_extractor_name if model_args.feature_extractor_name else model_args.model_name_or_path), cache_dir=model_args.cache_dir, revision=model_args.model_revision, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) tokenizer = AutoTokenizer.from_pretrained( (model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path), cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer, revision=model_args.model_revision, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) model = AutoModelForSpeechSeq2Seq.from_pretrained( model_args.model_name_or_path, config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined") if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if model_args.freeze_encoder: model.freeze_encoder() model.model.encoder.gradient_checkpointing = False if hasattr(model.generation_config, "is_multilingual") and model.generation_config.is_multilingual: # We only need to set the language and task ids in a multilingual setting tokenizer.set_prefix_tokens(language=data_args.language, task=data_args.task) model.generation_config.language = data_args.language model.generation_config.task = data_args.task elif data_args.language is not None: raise ValueError( "Setting language token for an English-only checkpoint is not permitted. The language argument should " "only be set for multilingual checkpoints." ) # TODO (Sanchit): deprecate these arguments in v4.41 if model_args.forced_decoder_ids is not None: logger.warning( "The use of `forced_decoder_ids` is deprecated and will be removed in v4.41." "Please use the `language` and `task` arguments instead" ) model.generation_config.forced_decoder_ids = model_args.forced_decoder_ids else: model.generation_config.forced_decoder_ids = None model.config.forced_decoder_ids = None if model_args.suppress_tokens is not None: logger.warning( "The use of `suppress_tokens` is deprecated and will be removed in v4.41." "Should you need `suppress_tokens`, please manually set them in the fine-tuning script." ) model.generation_config.suppress_tokens = model_args.suppress_tokens # 6. Resample speech dataset if necessary dataset_sampling_rate = next(iter(raw_datasets.values())).features[data_args.audio_column_name].sampling_rate if dataset_sampling_rate != feature_extractor.sampling_rate: raw_datasets = raw_datasets.cast_column( data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate), ) # 7. Preprocessing the datasets. # We need to read the audio files as arrays and tokenize the targets. max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate min_input_length = data_args.min_duration_in_seconds * feature_extractor.sampling_rate audio_column_name = data_args.audio_column_name num_workers = data_args.preprocessing_num_workers text_column_name = data_args.text_column_name model_input_name = feature_extractor.model_input_names[0] do_lower_case = data_args.do_lower_case # if SpecAugment is used for whisper models, return attention_mask to guide the mask along time axis forward_attention_mask = ( getattr(config, "model_type", None) == "whisper" and getattr(config, "apply_spec_augment", False) and getattr(config, "mask_time_prob", 0) > 0 ) if data_args.max_train_samples is not None: raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples)) if data_args.max_eval_samples is not None: raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples)) def prepare_dataset(batch): # process audio sample = batch[audio_column_name] inputs = feature_extractor( sample["array"], sampling_rate=sample["sampling_rate"], return_attention_mask=forward_attention_mask, ) # process audio length batch[model_input_name] = inputs.get(model_input_name)[0] batch["input_length"] = len(sample["array"]) if forward_attention_mask: batch["attention_mask"] = inputs.get("attention_mask")[0] # process targets input_str = batch[text_column_name].lower() if do_lower_case else batch[text_column_name] batch["labels"] = tokenizer(input_str).input_ids return batch with training_args.main_process_first(desc="dataset map pre-processing"): vectorized_datasets = raw_datasets.map( prepare_dataset, remove_columns=next(iter(raw_datasets.values())).column_names, num_proc=data_args.preprocessing_num_workers, desc="preprocess train dataset", ) # filter data that is shorter than min_input_length or longer than # max_input_length def is_audio_in_length_range(length): return length > min_input_length and length < max_input_length vectorized_datasets = vectorized_datasets.filter( is_audio_in_length_range, num_proc=num_workers, input_columns=["input_length"], ) # for large datasets it is advised to run the preprocessing on a # single machine first with `args.preprocessing_only` since there will mostly likely # be a timeout when running the script in distributed mode. # In a second step `args.preprocessing_only` can then be set to `False` to load the # cached dataset if data_args.preprocessing_only: cache = {k: v.cache_files for k, v in vectorized_datasets.items()} logger.info(f"Data preprocessing finished. Files cached at {cache}.") return # 8. Load Metric metric = evaluate.load("wer", cache_dir=model_args.cache_dir) def compute_metrics(pred): pred_ids = pred.predictions pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True) # we do not want to group tokens when computing the metrics label_str = tokenizer.batch_decode(pred.label_ids, skip_special_tokens=True) wer = metric.compute(predictions=pred_str, references=label_str) return {"wer": wer} # 9. Create a single speech processor # make sure all processes wait until data is saved with training_args.main_process_first(): # only the main process saves them if is_main_process(training_args.local_process_index): # save feature extractor, tokenizer and config feature_extractor.save_pretrained(training_args.output_dir) tokenizer.save_pretrained(training_args.output_dir) config.save_pretrained(training_args.output_dir) processor = AutoProcessor.from_pretrained(training_args.output_dir) # 10. Define data collator data_collator = DataCollatorSpeechSeq2SeqWithPadding( processor=processor, decoder_start_token_id=model.config.decoder_start_token_id, forward_attention_mask=forward_attention_mask, ) # 11. Initialize Trainer trainer = Seq2SeqTrainer( model=model, args=training_args, train_dataset=vectorized_datasets["train"] if training_args.do_train else None, eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None, processing_class=feature_extractor, data_collator=data_collator, compute_metrics=(compute_metrics if training_args.predict_with_generate else None), ) # 12. Training if training_args.do_train: checkpoint = None if training_args.resume_from_checkpoint is not None: checkpoint = training_args.resume_from_checkpoint train_result = trainer.train(resume_from_checkpoint=checkpoint) trainer.save_model() # Saves the feature extractor too for easy upload metrics = train_result.metrics max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(vectorized_datasets["train"]) ) metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"])) trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # 13. Evaluation results = {} if training_args.do_eval: logger.info("*** Evaluate ***") metrics = trainer.evaluate( metric_key_prefix="eval", max_length=training_args.generation_max_length, num_beams=training_args.generation_num_beams, ) max_eval_samples = ( data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"]) ) metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"])) trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) # 14. Write Training Stats kwargs = { "finetuned_from": model_args.model_name_or_path, "tasks": "automatic-speech-recognition", } if data_args.dataset_name is not None: kwargs["dataset_tags"] = data_args.dataset_name if data_args.dataset_config_name is not None: kwargs["dataset_args"] = data_args.dataset_config_name kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" else: kwargs["dataset"] = data_args.dataset_name if training_args.push_to_hub: trainer.push_to_hub(**kwargs) else: trainer.create_model_card(**kwargs) return results if __name__ == "__main__": main()
DataCollatorSpeechSeq2SeqWithPadding
python
spack__spack
lib/spack/spack/version/version_types.py
{ "start": 7750, "end": 17477 }
class ____(ConcreteVersion): """Class to represent versions""" __slots__ = ["version", "_string", "separators"] _string: str version: VersionTuple separators: Tuple[str, ...] def __init__(self, string: str, version: VersionTuple, separators: Tuple[str, ...]): """Create a StandardVersion from a string and parsed version components. Arguments: string: The original version string, or ``""`` if the it is not available. version: A tuple as returned by ``parse_string_components()``. Contains two tuples: one with alpha or numeric components and another with prerelease components. separators: separators parsed from the original version string. If constructed with ``string=""``, the string will be lazily constructed from components when ``str()`` is called. """ self._string = string self.version = version self.separators = separators @staticmethod def from_string(string: str) -> "StandardVersion": return StandardVersion(string, *parse_string_components(string)) @staticmethod def typemin() -> "StandardVersion": return _STANDARD_VERSION_TYPEMIN @staticmethod def typemax() -> "StandardVersion": return _STANDARD_VERSION_TYPEMAX @property def string(self) -> str: if not self._string: self._string = _stringify_version(self.version, self.separators) return self._string @string.setter def string(self, string) -> None: self._string = string def __bool__(self) -> bool: return True def __eq__(self, other: object) -> bool: if isinstance(other, StandardVersion): return self.version == other.version return False def __ne__(self, other: object) -> bool: if isinstance(other, StandardVersion): return self.version != other.version return True def __lt__(self, other: object) -> bool: if isinstance(other, StandardVersion): return self.version < other.version if isinstance(other, ClosedOpenRange): # Use <= here so that Version(x) < ClosedOpenRange(Version(x), ...). return self <= other.lo return NotImplemented def __le__(self, other: object) -> bool: if isinstance(other, StandardVersion): return self.version <= other.version if isinstance(other, ClosedOpenRange): # Versions are never equal to ranges, so follow < logic. return self <= other.lo return NotImplemented def __ge__(self, other: object) -> bool: if isinstance(other, StandardVersion): return self.version >= other.version if isinstance(other, ClosedOpenRange): # Versions are never equal to ranges, so follow > logic. return self > other.lo return NotImplemented def __gt__(self, other: object) -> bool: if isinstance(other, StandardVersion): return self.version > other.version if isinstance(other, ClosedOpenRange): return self > other.lo return NotImplemented def __iter__(self) -> Iterator: return iter(self.version[0]) def __len__(self) -> int: return len(self.version[0]) def __getitem__(self, idx: Union[int, slice]): cls = type(self) release = self.version[0] if isinstance(idx, int): return release[idx] elif isinstance(idx, slice): string_arg = [] pairs = zip(release[idx], self.separators[idx]) for token, sep in pairs: string_arg.append(str(token)) string_arg.append(str(sep)) if string_arg: string_arg.pop() # We don't need the last separator return cls.from_string("".join(string_arg)) else: return StandardVersion.from_string("") raise TypeError(f"{cls.__name__} indices must be integers or slices") def __str__(self) -> str: return self.string def __repr__(self) -> str: # Print indirect repr through Version(...) return f'Version("{str(self)}")' def __hash__(self) -> int: # If this is a final release, do not hash the prerelease part for backward compat. return hash(self.version if self.is_prerelease() else self.version[0]) def __contains__(rhs, lhs) -> bool: # We should probably get rid of `x in y` for versions, since # versions still have a dual interpretation as singleton sets # or elements. x in y should be: is the lhs-element in the # rhs-set. Instead this function also does subset checks. if isinstance(lhs, VersionType): return lhs.satisfies(rhs) raise TypeError(f"'in' not supported for instances of {type(lhs)}") def intersects(self, other: VersionType) -> bool: if isinstance(other, StandardVersion): return self == other return other.intersects(self) def satisfies(self, other: VersionType) -> bool: if isinstance(other, GitVersion): return False if isinstance(other, StandardVersion): return self == other if isinstance(other, ClosedOpenRange): return other.intersects(self) if isinstance(other, VersionList): return other.intersects(self) raise NotImplementedError def union(self, other: VersionType) -> VersionType: if isinstance(other, StandardVersion): return self if self == other else VersionList([self, other]) return other.union(self) def intersection(self, other: VersionType) -> VersionType: if isinstance(other, StandardVersion): return self if self == other else VersionList() return other.intersection(self) def isdevelop(self) -> bool: """Triggers on the special case of the ``@develop-like`` version.""" return any( isinstance(p, VersionStrComponent) and isinstance(p.data, int) for p in self.version[0] ) def is_prerelease(self) -> bool: return self.version[1][0] != FINAL @property def dotted_numeric_string(self) -> str: """Replaces all non-numeric components of the version with 0. This can be used to pass Spack versions to libraries that have stricter version schema. """ numeric = tuple(0 if isinstance(v, VersionStrComponent) else v for v in self.version[0]) if self.is_prerelease(): numeric += (0, *self.version[1][1:]) return ".".join(str(v) for v in numeric) @property def dotted(self) -> "StandardVersion": """The dotted representation of the version. Example: >>> version = Version('1-2-3b') >>> version.dotted Version('1.2.3b') Returns: Version: The version with separator characters replaced by dots """ return type(self).from_string(self.string.replace("-", ".").replace("_", ".")) @property def underscored(self) -> "StandardVersion": """The underscored representation of the version. Example: >>> version = Version("1.2.3b") >>> version.underscored Version("1_2_3b") Returns: Version: The version with separator characters replaced by underscores """ return type(self).from_string(self.string.replace(".", "_").replace("-", "_")) @property def dashed(self) -> "StandardVersion": """The dashed representation of the version. Example: >>> version = Version("1.2.3b") >>> version.dashed Version("1-2-3b") Returns: Version: The version with separator characters replaced by dashes """ return type(self).from_string(self.string.replace(".", "-").replace("_", "-")) @property def joined(self) -> "StandardVersion": """The joined representation of the version. Example: >>> version = Version("1.2.3b") >>> version.joined Version("123b") Returns: Version: The version with separator characters removed """ return type(self).from_string( self.string.replace(".", "").replace("-", "").replace("_", "") ) def up_to(self, index: int) -> "StandardVersion": """The version up to the specified component. Examples: >>> version = Version("1.23-4b") >>> version.up_to(1) Version("1") >>> version.up_to(2) Version("1.23") >>> version.up_to(3) Version("1.23-4") >>> version.up_to(4) Version("1.23-4b") >>> version.up_to(-1) Version("1.23-4") >>> version.up_to(-2) Version("1.23") >>> version.up_to(-3) Version("1") Returns: Version: The first index components of the version """ return self[:index] @property def up_to_1(self): """The version truncated to the first component.""" return self.up_to(1) @property def up_to_2(self): """The version truncated to the first two components.""" return self.up_to(2) @property def up_to_3(self): """The version truncated to the first three components.""" return self.up_to(3) _STANDARD_VERSION_TYPEMIN = StandardVersion("", ((), (ALPHA,)), ("",)) _STANDARD_VERSION_TYPEMAX = StandardVersion( "infinity", ((VersionStrComponent(len(infinity_versions)),), (FINAL,)), ("",) )
StandardVersion
python
pytorch__pytorch
test/dynamo/test_skip_guard_eval_unsafe.py
{ "start": 153, "end": 3884 }
class ____(torch._dynamo.test_case.TestCase): def test_bool_recompile(self): def fn(x, y, c): if c: return x * y else: return x + y opt_fn = torch.compile(fn, backend="inductor") x = 2 * torch.ones(4) y = 3 * torch.ones(4) ref1 = opt_fn(x, y, True) ref2 = opt_fn(x, y, False) with torch.compiler.set_stance(skip_guard_eval_unsafe=True): res2 = opt_fn(x, y, False) res1 = opt_fn(x, y, True) self.assertEqual(ref1, res1) self.assertEqual(ref2, res2) def test_tensor_recompile(self): def fn(x, y): return x * y opt_fn = torch.compile(fn, backend="eager") x = torch.randn(4, dtype=torch.float32) y = torch.randn(4, dtype=torch.float32) ref1 = opt_fn(x, y) x64 = torch.randn(4, dtype=torch.float64) y64 = torch.randn(4, dtype=torch.float64) ref2 = opt_fn(x64, y64) with torch.compiler.set_stance(skip_guard_eval_unsafe=True): res1 = opt_fn(x, y) res2 = opt_fn(x64, y64) self.assertEqual(ref1, res1) self.assertEqual(ref2, res2) def test_post_recompile(self): class Foo: def __init__(self): self.a = 4 self.b = 5 foo = Foo() def fn(x): return x + foo.a + foo.b cnts = torch._dynamo.testing.CompileCounter() opt_fn = torch.compile(fn, backend=cnts) x = torch.randn(4) ref = fn(x) res = opt_fn(x) self.assertEqual(ref, res) self.assertEqual(cnts.frame_count, 1) foo.a = 11 ref = fn(x) res = opt_fn(x) self.assertEqual(ref, res) self.assertEqual(cnts.frame_count, 2) with torch.compiler.set_stance(skip_guard_eval_unsafe=True): # Set it back to original value foo.a = 4 ref = fn(x) res = opt_fn(x) self.assertEqual(ref, res) foo.a = 11 ref = fn(x) res = opt_fn(x) self.assertEqual(ref, res) # Check that we are back to original behavior foo.b = 8 ref = fn(x) res = opt_fn(x) self.assertEqual(ref, res) self.assertEqual(cnts.frame_count, 3) def test_fail_on_tensor_shape_change(self): def fn(dt): return dt["x"] + 1 x = torch.randn(4) dt = {} dt["x"] = x opt_fn = torch.compile(fn, backend="eager") opt_fn(dt) with self.assertRaisesRegex( RuntimeError, "Recompilation triggered with skip_guard_eval_unsafe stance" ): with torch.compiler.set_stance(skip_guard_eval_unsafe=True): x = torch.randn(4, 4) dt["x"] = x opt_fn(dt) def test_cache_line_pickup(self): def fn(x, a=None, b=None): x = x * 3 if a: x = x * 5 if b: x = x * 7 return x opt_fn = torch.compile(fn, backend="eager") x = torch.ones(4) ref1 = opt_fn(x, a=None, b=None) ref2 = opt_fn(x, a=1, b=None) ref3 = opt_fn(x, a=1, b=1) with torch.compiler.set_stance(skip_guard_eval_unsafe=True): res1 = opt_fn(x, a=None, b=None) res2 = opt_fn(x, a=1, b=None) res3 = opt_fn(x, a=1, b=1) self.assertEqual(ref1, res1) self.assertEqual(ref2, res2) self.assertEqual(ref3, res3) if __name__ == "__main__": from torch._dynamo.test_case import run_tests run_tests()
RunDiffGuardTests
python
ray-project__ray
python/ray/data/_internal/logical/interfaces/logical_plan.py
{ "start": 175, "end": 936 }
class ____(Plan): """The plan with a DAG of logical operators.""" def __init__(self, dag: LogicalOperator, context: "DataContext"): super().__init__(context) self._dag = dag @property def dag(self) -> LogicalOperator: """Get the DAG of logical operators.""" return self._dag def sources(self) -> List[LogicalOperator]: """List of operators that are sources for this plan's DAG.""" # If an operator has no input dependencies, it's a source. if not any(self._dag.input_dependencies): return [self._dag] sources = [] for op in self._dag.input_dependencies: sources.extend(LogicalPlan(op, self._context).sources()) return sources
LogicalPlan
python
PyCQA__bandit
tests/unit/formatters/test_xml.py
{ "start": 320, "end": 2785 }
class ____(testtools.TestCase): def setUp(self): super().setUp() conf = config.BanditConfig() self.manager = manager.BanditManager(conf, "file") (tmp_fd, self.tmp_fname) = tempfile.mkstemp() self.context = { "filename": self.tmp_fname, "lineno": 4, "linerange": [4], } self.check_name = "hardcoded_bind_all_interfaces" self.issue = issue.Issue( bandit.MEDIUM, issue.Cwe.MULTIPLE_BINDS, bandit.MEDIUM, "Possible binding to all interfaces.", ) self.manager.out_file = self.tmp_fname self.issue.fname = self.context["filename"] self.issue.lineno = self.context["lineno"] self.issue.linerange = self.context["linerange"] self.issue.test = self.check_name self.manager.results.append(self.issue) def _xml_to_dict(self, t): d = {t.tag: {} if t.attrib else None} children = list(t) if children: dd = collections.defaultdict(list) for dc in map(self._xml_to_dict, children): for k, v in dc.items(): dd[k].append(v) d = {t.tag: {k: v[0] if len(v) == 1 else v for k, v in dd.items()}} if t.attrib: d[t.tag].update(("@" + k, v) for k, v in t.attrib.items()) if t.text: text = t.text.strip() if children or t.attrib: if text: d[t.tag]["#text"] = text else: d[t.tag] = text return d def test_report(self): with open(self.tmp_fname, "wb") as tmp_file: b_xml.report( self.manager, tmp_file, self.issue.severity, self.issue.confidence, ) with open(self.tmp_fname) as f: data = self._xml_to_dict(ET.XML(f.read())) self.assertEqual( self.tmp_fname, data["testsuite"]["testcase"]["@classname"] ) self.assertEqual( self.issue.text, data["testsuite"]["testcase"]["error"]["@message"], ) self.assertEqual( self.check_name, data["testsuite"]["testcase"]["@name"] ) self.assertIsNotNone( data["testsuite"]["testcase"]["error"]["@more_info"] )
XmlFormatterTests
python
apache__airflow
providers/microsoft/azure/tests/unit/microsoft/azure/secrets/test_key_vault.py
{ "start": 1068, "end": 6662 }
class ____: @mock.patch(f"{KEY_VAULT_MODULE}.AzureKeyVaultBackend.get_conn_value") def test_get_connection(self, mock_get_value): mock_get_value.return_value = "scheme://user:pass@host:100" conn = AzureKeyVaultBackend().get_connection("fake_conn") assert conn.host == "host" @mock.patch(f"{KEY_VAULT_MODULE}.AzureKeyVaultBackend.client") def test_get_variable(self, mock_client): mock_client.get_secret.return_value = mock.Mock(value="world") backend = AzureKeyVaultBackend() returned_uri = backend.get_variable("hello") mock_client.get_secret.assert_called_with(name="airflow-variables-hello") assert returned_uri == "world" @mock.patch(f"{KEY_VAULT_MODULE}.AzureKeyVaultBackend.client") def test_get_variable_non_existent_key(self, mock_client): """ Test that if Variable key is not present, AzureKeyVaultBackend.get_variables should return None """ mock_client.get_secret.side_effect = ResourceNotFoundError backend = AzureKeyVaultBackend() assert backend.get_variable("test_mysql") is None @mock.patch(f"{KEY_VAULT_MODULE}.AzureKeyVaultBackend.client") def test_get_secret_value_not_found(self, mock_client): """ Test that if a non-existent secret returns None """ mock_client.get_secret.side_effect = ResourceNotFoundError backend = AzureKeyVaultBackend() assert ( backend._get_secret(path_prefix=backend.connections_prefix, secret_id="test_non_existent") is None ) @mock.patch(f"{KEY_VAULT_MODULE}.AzureKeyVaultBackend.client") def test_get_secret_value(self, mock_client): """ Test that get_secret returns the secret value """ mock_client.get_secret.return_value = mock.Mock(value="super-secret") backend = AzureKeyVaultBackend() secret_val = backend._get_secret("af-secrets", "test_mysql_password") mock_client.get_secret.assert_called_with(name="af-secrets-test-mysql-password") assert secret_val == "super-secret" @mock.patch(f"{KEY_VAULT_MODULE}.AzureKeyVaultBackend._get_secret") def test_variable_prefix_none_value(self, mock_get_secret): """ Test that if Variables prefix is None, AzureKeyVaultBackend.get_variables should return None AzureKeyVaultBackend._get_secret should not be called """ kwargs = {"variables_prefix": None} backend = AzureKeyVaultBackend(**kwargs) assert backend.get_variable("hello") is None mock_get_secret.assert_not_called() @mock.patch(f"{KEY_VAULT_MODULE}.AzureKeyVaultBackend._get_secret") def test_config_prefix_none_value(self, mock_get_secret): """ Test that if Config prefix is None, AzureKeyVaultBackend.get_config should return None AzureKeyVaultBackend._get_secret should not be called """ kwargs = {"config_prefix": None} backend = AzureKeyVaultBackend(**kwargs) assert backend.get_config("test_mysql") is None mock_get_secret.assert_not_called() @mock.patch(f"{KEY_VAULT_MODULE}.get_sync_default_azure_credential") @mock.patch(f"{KEY_VAULT_MODULE}.ClientSecretCredential") @mock.patch(f"{KEY_VAULT_MODULE}.SecretClient") def test_client_authenticate_with_default_azure_credential( self, mock_client, mock_client_secret_credential, mock_defaul_azure_credential ): """ Test that if AzureKeyValueBackend is authenticated with DefaultAzureCredential tenant_id, client_id and client_secret are not provided """ backend = AzureKeyVaultBackend(vault_url="https://example-akv-resource-name.vault.azure.net/") backend.client assert not mock_client_secret_credential.called mock_defaul_azure_credential.assert_called_once() @mock.patch(f"{KEY_VAULT_MODULE}.get_sync_default_azure_credential") @mock.patch(f"{KEY_VAULT_MODULE}.ClientSecretCredential") @mock.patch(f"{KEY_VAULT_MODULE}.SecretClient") def test_client_authenticate_with_default_azure_credential_and_customized_configuration( self, mock_client, mock_client_secret_credential, mock_defaul_azure_credential ): backend = AzureKeyVaultBackend( vault_url="https://example-akv-resource-name.vault.azure.net/", managed_identity_client_id="managed_identity_client_id", workload_identity_tenant_id="workload_identity_tenant_id", ) backend.client assert not mock_client_secret_credential.called mock_defaul_azure_credential.assert_called_once_with( managed_identity_client_id="managed_identity_client_id", workload_identity_tenant_id="workload_identity_tenant_id", ) @mock.patch(f"{KEY_VAULT_MODULE}.get_sync_default_azure_credential") @mock.patch(f"{KEY_VAULT_MODULE}.ClientSecretCredential") @mock.patch(f"{KEY_VAULT_MODULE}.SecretClient") def test_client_authenticate_with_client_secret_credential( self, mock_client, mock_client_secret_credential, mock_defaul_azure_credential ): backend = AzureKeyVaultBackend( vault_url="https://example-akv-resource-name.vault.azure.net/", tenant_id="tenant_id", client_id="client_id", client_secret="client_secret", ) backend.client assert not mock_defaul_azure_credential.called mock_client_secret_credential.assert_called_once()
TestAzureKeyVaultBackend
python
run-llama__llama_index
llama-index-packs/llama-index-packs-node-parser-semantic-chunking/llama_index/packs/node_parser_semantic_chunking/base.py
{ "start": 4506, "end": 7145 }
class ____(MetadataAwareTextSplitter): """ Semantic splitter. Inspired by Greg's semantic chunking. """ buffer_size: int = Field( default=1, description="Number of sentences to include in each chunk." ) embed_model: Optional[BaseEmbedding] = Field( default=None, description="Embedding model." ) breakpoint_percentile_threshold: float = Field( default=95.0, description="Percentile threshold for breakpoint distance.", ) def __init__( self, buffer_size: int = 1, embed_model: Optional[BaseEmbedding] = None, breakpoint_percentile_threshold: float = 95.0, **kwargs: Any, ): from llama_index.embeddings.openai import OpenAIEmbedding super().__init__( buffer_size=buffer_size, embed_model=embed_model or OpenAIEmbedding(), breakpoint_percentile_threshold=breakpoint_percentile_threshold, ) @classmethod def class_name(cls) -> str: return "SentenceSplitter" def split_text_metadata_aware(self, text: str, metadata_str: str) -> List[str]: return self._split_text(text) def split_text(self, text: str) -> List[str]: return self._split_text(text) def _split_text(self, text: str) -> List[str]: """ _Split incoming text and return chunks with overlap size. Has a preference for complete sentences, phrases, and minimal overlap. """ # Splitting the essay on '.', '?', and '!' single_sentences_list = re.split(r"(?<=[.?!])\s+", text) sentences = [ {"sentence": x, "index": i} for i, x in enumerate(single_sentences_list) ] combined_sentences = combine_sentences(sentences, self.buffer_size) # compute embeddings embeddings = self.embed_model.get_text_embedding_batch( [x["combined_sentence"] for x in combined_sentences] ) # assign embeddings to the sentences for i, embedding in enumerate(embeddings): combined_sentences[i]["embedding"] = embedding # calculate cosine distance between adjacent sentences distances = calculate_cosine_distances(combined_sentences) for i, distance in enumerate(distances): combined_sentences[i]["dist_to_next"] = distance # get indices above threshold indices_above_thresh = get_indices_above_threshold( distances, self.breakpoint_percentile_threshold ) # make chunks return make_chunks(combined_sentences, indices_above_thresh)
SemanticChunker
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 36069, "end": 36579 }
class ____(PrefectBaseModel, OperatorMixin): """Filter variables. Only variables matching all criteria will be returned""" id: Optional[VariableFilterId] = Field( default=None, description="Filter criteria for `Variable.id`" ) name: Optional[VariableFilterName] = Field( default=None, description="Filter criteria for `Variable.name`" ) tags: Optional[VariableFilterTags] = Field( default=None, description="Filter criteria for `Variable.tags`" )
VariableFilter
python
great-expectations__great_expectations
great_expectations/expectations/expectation_configuration.py
{ "start": 2936, "end": 3157 }
class ____(Schema): description = fields.String(required=False, allow_none=True) @post_load def make_expectation_context(self, data, **kwargs): return ExpectationContext(**data)
ExpectationContextSchema
python
numba__numba
numba/cuda/tests/cudapy/test_lang.py
{ "start": 146, "end": 1691 }
class ____(CUDATestCase): def test_enumerate(self): tup = (1., 2.5, 3.) @cuda.jit("void(float64[:])") def foo(a): for i, v in enumerate(tup): a[i] = v a = np.zeros(len(tup)) foo[1, 1](a) self.assertTrue(np.all(a == tup)) def test_zip(self): t1 = (1, 2, 3) t2 = (4.5, 5.6, 6.7) @cuda.jit("void(float64[:])") def foo(a): c = 0 for i, j in zip(t1, t2): c += i + j a[0] = c a = np.zeros(1) foo[1, 1](a) b = np.array(t1) c = np.array(t2) self.assertTrue(np.all(a == (b + c).sum())) def test_issue_872(self): ''' Ensure that typing and lowering of CUDA kernel API primitives works in more than one block. Was originally to ensure that macro expansion works for more than one block (issue #872), but macro expansion has been replaced by a "proper" implementation of all kernel API functions. ''' @cuda.jit("void(float64[:,:])") def cuda_kernel_api_in_multiple_blocks(ary): for i in range(2): tx = cuda.threadIdx.x for j in range(3): ty = cuda.threadIdx.y sm = cuda.shared.array((2, 3), float64) sm[tx, ty] = 1.0 ary[tx, ty] = sm[tx, ty] a = np.zeros((2, 3)) cuda_kernel_api_in_multiple_blocks[1, (2, 3)](a) if __name__ == '__main__': unittest.main()
TestLang
python
getsentry__sentry
src/sentry/discover/translation/mep_to_eap.py
{ "start": 498, "end": 638 }
class ____(TypedDict): selected_columns: list[str] query: str equations: list[str] | None orderby: list[str] | None
QueryParts
python
django-extensions__django-extensions
django_extensions/management/base.py
{ "start": 135, "end": 1407 }
class ____(BaseCommand): """ A subclass of BaseCommand that logs run time errors to `django.commands`. To use this, create a management command subclassing LoggingBaseCommand: from django_extensions.management.base import LoggingBaseCommand class Command(LoggingBaseCommand): help = 'Test error' def handle(self, *args, **options): raise Exception And then define a logging handler in settings.py: LOGGING = { ... # Other stuff here 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, }, 'loggers': { 'django.commands': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, } } """ def execute(self, *args, **options): try: super().execute(*args, **options) except Exception as e: logger.error(e, exc_info=sys.exc_info(), extra={"status_code": 500}) raise
LoggingBaseCommand
python
falconry__falcon
falcon/errors.py
{ "start": 77406, "end": 79748 }
class ____(HTTPError): """504 Gateway Timeout. The 504 (Gateway Timeout) status code indicates that the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request. (See also: RFC 7231, Section 6.6.5) All the arguments are defined as keyword-only. Keyword Args: title (str): Error title (default '503 Service Unavailable'). description (str): Human-friendly description of the error, along with a helpful suggestion or two. headers (dict or list): A ``dict`` of header names and values to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and *value* must be of type ``str`` or ``StringType``, and only character values 0x00 through 0xFF may be used on platforms that use wide characters. Note: The Content-Type header, if present, will be overridden. If you wish to return custom error messages, you can create your own HTTP error class, and install an error handler to convert it into an appropriate HTTP response for the client Note: Falcon can process a list of ``tuple`` slightly faster than a ``dict``. href (str): A URL someone can visit to find out more information (default ``None``). Unicode characters are percent-encoded. href_text (str): If href is given, use this as the friendly title/description for the link (default 'API documentation for this error'). code (int): An internal code that customers can reference in their support request or to help them when searching for knowledge base articles related to this error (default ``None``). """ def __init__( self, *, title: str | None = None, description: str | None = None, headers: HeaderArg | None = None, **kwargs: HTTPErrorKeywordArguments, ): super().__init__( status.HTTP_504, title=title, description=description, headers=headers, **kwargs, # type: ignore[arg-type] )
HTTPGatewayTimeout
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 8547, "end": 8686 }
class ____(_TestDCTIBase): def setup_method(self): self.rdt = np.float32 self.dec = 4 self.type = 1
TestDCTIFloat
python
google__pytype
pytype/imports/module_loader.py
{ "start": 3087, "end": 5064 }
class ____(base.ModuleLoader): """Find and read module type information.""" def __init__(self, options: config.Options): self.options = options self._path_finder = _PathFinder(options) def find_import(self, module_name: str) -> base.ModuleInfo | None: """See if the loader can find a file to import for the module.""" found_import = self._path_finder.find_import(module_name) if found_import is None: return None full_path, file_exists = found_import return base.ModuleInfo(module_name, full_path, file_exists) def _load_pyi(self, mod_info: base.ModuleInfo): """Load a file and parse it into a pytd AST.""" with self.options.open_function(mod_info.filename, "r") as f: mod_ast = parser.parse_string( f.read(), filename=mod_info.filename, name=mod_info.module_name, options=parser.PyiOptions.from_toplevel_options(self.options), ) return mod_ast def _load_pickle(self, mod_info: base.ModuleInfo): """Load and unpickle a serialized pytd AST.""" return pickle_utils.LoadAst( mod_info.filename, open_function=self.options.open_function ) def load_ast(self, mod_info: base.ModuleInfo): if file_utils.is_pickle(mod_info.filename): return self._load_pickle(mod_info) else: return self._load_pyi(mod_info) def log_module_not_found(self, module_name: str): log.warning( "Couldn't import module %s %r in (path=%r) imports_map: %s", module_name, module_name, self.options.pythonpath, f"{len(self.options.imports_map)} items" if self.options.imports_map is not None else "none", ) def get_unused_imports_map_paths(self) -> set[str]: if not self.options.imports_map: return set() return ( set(self.options.imports_map.items.values()) - set(self._path_finder.accessed_imports_paths) ) | set(self.options.imports_map.unused)
ModuleLoader
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/maximum_tito_depth.py
{ "start": 880, "end": 1272 }
class ____: def tito(self, parameter): ... def tito_obscure(x): # Obscure calls are treated as tito depth 0. c = C() return c.tito(x) def tito_four(x): # Ignored because too far. return tito_three(x) def issue(): x = _test_source() y = tito_three(x) _test_sink(y) def non_issue(): x = _test_source() y = tito_four(x) _test_sink(y)
C
python
wandb__wandb
landfill/functional_tests/torch/t3_ddp_basic.py
{ "start": 587, "end": 1959 }
class ____(nn.Module): def __init__(self): super().__init__() self.net1 = nn.Linear(10, 10) self.relu = nn.ReLU() self.net2 = nn.Linear(10, 5) def forward(self, x): return self.net2(self.relu(self.net1(x))) def demo_basic(rank, world_size): print(f"Running basic DDP example on rank {rank}.") setup(rank, world_size) if torch.cuda.is_available(): device = rank device_ids = [rank] else: device = torch.device("cpu") device_ids = [] # create model and move it to GPU with id rank model = ToyModel().to(device) ddp_model = DistributedDataParallel(model, device_ids=device_ids) with wandb.init(group="ddp-basic") as run: run.watch(models=ddp_model, log_freq=1, log_graph=True) loss_fn = nn.MSELoss() optimizer = optim.SGD(ddp_model.parameters(), lr=0.001) for _ in range(3): optimizer.zero_grad() outputs = ddp_model(torch.randn(20, 10)) labels = torch.randn(20, 5).to(device) loss = loss_fn(outputs, labels) run.log({"loss": loss}) loss.backward() optimizer.step() cleanup() if __name__ == "__main__": world_size = 2 mp.spawn( demo_basic, args=(world_size,), nprocs=world_size, join=True, )
ToyModel
python
astropy__astropy
astropy/cosmology/_src/tests/io/test_html.py
{ "start": 476, "end": 8675 }
class ____(ReadWriteTestMixinBase): """ Tests for a Cosmology[Read/Write] with ``format="ascii.html"``. This class will not be directly called by :mod:`pytest` since its name does not begin with ``Test``. To activate the contained tests this class must be inherited in a subclass. Subclasses must define a :func:`pytest.fixture` ``cosmo`` that returns/yields an instance of a |Cosmology|. See ``TestCosmology`` for an example. """ @pytest.mark.skipif(not HAS_BS4, reason="requires beautifulsoup4") def test_to_html_table_bad_index(self, read, write, tmp_path): """Test if argument ``index`` is incorrect""" fp = tmp_path / "test_to_html_table_bad_index.html" write(fp, format="ascii.html") # single-row table and has a non-0/None index with pytest.raises(IndexError, match="index 2 out of range"): read(fp, index=2, format="ascii.html") # string index where doesn't match with pytest.raises(KeyError, match="No matches found for key"): read(fp, index="row 0", format="ascii.html") # ----------------------- @pytest.mark.skipif(not HAS_BS4, reason="requires beautifulsoup4") def test_to_html_table_failed_cls(self, write, tmp_path): """Test failed table type.""" fp = tmp_path / "test_to_html_table_failed_cls.html" with pytest.raises(TypeError, match="'cls' must be"): write(fp, format="ascii.html", cls=list) @pytest.mark.parametrize("tbl_cls", [QTable, Table]) @pytest.mark.skipif(not HAS_BS4, reason="requires beautifulsoup4") def test_to_html_table_cls(self, write, tbl_cls, tmp_path): fp = tmp_path / "test_to_html_table_cls.html" write(fp, format="ascii.html", cls=tbl_cls) # ----------------------- @pytest.mark.skipif(not HAS_BS4, reason="requires beautifulsoup4") def test_readwrite_html_table_instance( self, cosmo_cls, cosmo, read, write, tmp_path, add_cu ): """Test cosmology -> ascii.html -> cosmology.""" fp = tmp_path / "test_readwrite_html_table_instance.html" # ------------ # To Table write(fp, format="ascii.html") # some checks on the saved file tbl = QTable.read(fp) # assert tbl.meta["cosmology"] == cosmo_cls.__qualname__ # metadata read not implemented assert tbl["name"] == cosmo.name # ------------ # From Table tbl["mismatching"] = "will error" tbl.write(fp, format="ascii.html", overwrite=True) # tests are different if the last argument is a **kwarg if cosmo._init_has_kwargs: got = read(fp, format="ascii.html") assert got.__class__ is cosmo_cls assert got.name == cosmo.name # assert "mismatching" not in got.meta # metadata read not implemented return # don't continue testing # read with mismatching parameters errors with pytest.raises(TypeError, match="there are unused parameters"): read(fp, format="ascii.html") # unless mismatched are moved to meta got = read(fp, format="ascii.html", move_to_meta=True) assert got == cosmo # assert got.meta["mismatching"] == "will error" # metadata read not implemented # it won't error if everything matches up tbl.remove_column("mismatching") tbl.write(fp, format="ascii.html", overwrite=True) got = read(fp, format="ascii.html") assert got == cosmo # and it will also work if the cosmology is a class # Note this is not the default output of ``write``. # tbl.meta["cosmology"] = _COSMOLOGY_CLASSES[tbl.meta["cosmology"]] # # metadata read not implemented got = read(fp, format="ascii.html") assert got == cosmo got = read(fp) assert got == cosmo @pytest.mark.skipif(not HAS_BS4, reason="requires beautifulsoup4") def test_rename_html_table_columns(self, read, write, tmp_path): """Tests renaming columns""" fp = tmp_path / "test_rename_html_table_columns.html" write(fp, format="ascii.html", latex_names=True) tbl = QTable.read(fp) # asserts each column name has not been reverted yet # For now, Cosmology class and name are stored in first 2 slots for column_name in tbl.colnames[2:]: assert column_name in _FORMAT_TABLE.values() cosmo = read(fp, format="ascii.html") converted_tbl = cosmo.to_format("astropy.table") # asserts each column name has been reverted # cosmology name is still stored in first slot for column_name in converted_tbl.colnames[1:]: assert column_name in _FORMAT_TABLE.keys() @pytest.mark.skipif(not HAS_BS4, reason="requires beautifulsoup4") @pytest.mark.parametrize("latex_names", [True, False]) def test_readwrite_html_subclass_partial_info( self, cosmo_cls, cosmo, read, write, latex_names, tmp_path, add_cu ): """ Test writing from an instance and reading from that class. This works with missing information. """ fp = tmp_path / "test_read_html_subclass_partial_info.html" # test write write(fp, format="ascii.html", latex_names=latex_names) # partial information tbl = QTable.read(fp) # tbl.meta.pop("cosmology", None) # metadata not implemented cname = "$$T_{0}$$" if latex_names else "Tcmb0" del tbl[cname] # format is not converted to original units tbl.write(fp, overwrite=True) # read with the same class that wrote fills in the missing info with # the default value got = cosmo_cls.read(fp, format="ascii.html") got2 = read(fp, format="ascii.html", cosmology=cosmo_cls) got3 = read(fp, format="ascii.html", cosmology=cosmo_cls.__qualname__) assert (got == got2) and (got2 == got3) # internal consistency # not equal, because Tcmb0 is changed, which also changes m_nu assert got != cosmo assert got.Tcmb0 == cosmo_cls.parameters["Tcmb0"].default assert got.clone(name=cosmo.name, Tcmb0=cosmo.Tcmb0, m_nu=cosmo.m_nu) == cosmo # but the metadata is the same # assert got.meta == cosmo.meta # metadata read not implemented @pytest.mark.skipif(not HAS_BS4, reason="requires beautifulsoup4") def test_readwrite_html_mutlirow(self, cosmo, read, write, tmp_path, add_cu): """Test if table has multiple rows.""" fp = tmp_path / "test_readwrite_html_mutlirow.html" # Make cosmo1 = cosmo.clone(name="row 0") cosmo2 = cosmo.clone(name="row 2") table = vstack( [c.to_format("astropy.table") for c in (cosmo1, cosmo, cosmo2)], metadata_conflicts="silent", ) cosmo_cls = type(cosmo) assert cosmo is not None for n, col in zip(table.colnames, table.itercols()): if n not in cosmo_cls.parameters: continue param = cosmo_cls.parameters[n] if param.unit in (None, u.one): continue # Replace column with unitless version table.replace_column(n, (col << param.unit).value, copy=False) table.write(fp, format="ascii.html") # ------------ # From Table # it will error on a multi-row table with pytest.raises(ValueError, match="need to select a specific row"): read(fp, format="ascii.html") # unless the index argument is provided got = cosmo_cls.read(fp, index=1, format="ascii.html") # got = read(fp, index=1, format="ascii.html") assert got == cosmo # the index can be a string got = cosmo_cls.read(fp, index=cosmo.name, format="ascii.html") assert got == cosmo # it's better if the table already has an index # this will be identical to the previous ``got`` table.add_index("name") got2 = cosmo_cls.read(fp, index=cosmo.name, format="ascii.html") assert got2 == cosmo
ReadWriteHTMLTestMixin
python
django__django
tests/forms_tests/widget_tests/test_input.py
{ "start": 71, "end": 722 }
class ____(WidgetTest): def test_attrs_with_type(self): attrs = {"type": "date"} widget = Input(attrs) self.check_html( widget, "name", "value", '<input type="date" name="name" value="value">' ) # reuse the same attrs for another widget self.check_html( Input(attrs), "name", "value", '<input type="date" name="name" value="value">', ) attrs["type"] = "number" # shouldn't change the widget type self.check_html( widget, "name", "value", '<input type="date" name="name" value="value">' )
InputTests
python
getsentry__sentry
tests/sentry/integrations/github_enterprise/test_webhooks.py
{ "start": 11263, "end": 21503 }
class ____(APITestCase): def setUp(self) -> None: self.url = "/extensions/github-enterprise/webhook/" self.metadata = { "url": "35.232.149.196", "id": "2", "name": "test-app", "webhook_secret": "b3002c3e321d4b7880360d397db2ccfd", "private_key": "private_key", "verify_ssl": True, } Repository.objects.create( organization_id=self.project.organization.id, external_id="35129377", provider="integrations:github_enterprise", name="baxterthehacker/public-repo", ) @responses.activate @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_simple( self, mock_record: MagicMock, mock_get_installation_metadata: MagicMock, mock_get_jwt: MagicMock, ) -> None: responses.add( responses.POST, "https://35.232.149.196/extensions/github-enterprise/webhook/", status=204, ) mock_get_jwt.return_value = "" mock_get_installation_metadata.return_value = self.metadata self.create_integration( external_id="35.232.149.196:12345", organization=self.project.organization, provider="github_enterprise", metadata={ "domain_name": "35.232.149.196/baxterthehacker", "installation_id": "12345", "installation": { "id": "2", "private_key": "private_key", "verify_ssl": True, }, }, ) response = self.client.post( path=self.url, data=PUSH_EVENT_EXAMPLE_INSTALLATION, content_type="application/json", HTTP_X_GITHUB_EVENT="push", HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196", HTTP_X_HUB_SIGNATURE="sha1=2a0586cc46490b17441834e1e143ec3d8c1fe032", HTTP_X_GITHUB_DELIVERY=str(uuid4()), ) assert response.status_code == 204 commit_list = list( Commit.objects.filter( # organization_id=project.organization_id, ) .select_related("author") .order_by("-date_added") ) assert len(commit_list) == 2 commit = commit_list[0] assert commit.key == "133d60480286590a610a0eb7352ff6e02b9674c4" assert commit.message == "Update README.md (àgain)" assert commit.author is not None assert commit.author.name == "bàxterthehacker" assert commit.author.email == "baxterthehacker@users.noreply.github.com" assert commit.author.external_id is None assert commit.date_added == datetime(2015, 5, 5, 23, 45, 15, tzinfo=timezone.utc) commit = commit_list[1] assert commit.key == "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c" assert commit.message == "Update README.md" assert commit.author is not None assert commit.author.name == "bàxterthehacker" assert commit.author.email == "baxterthehacker@users.noreply.github.com" assert commit.author.external_id is None assert commit.date_added == datetime(2015, 5, 5, 23, 40, 15, tzinfo=timezone.utc) assert_success_metric(mock_record) @responses.activate @patch("sentry.integrations.github.webhook.PushEventWebhook.__call__") @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_webhook_error_metric( self, mock_record, mock_event, mock_get_installation_metadata, mock_get_jwt ): responses.add( responses.POST, "https://35.232.149.196/extensions/github-enterprise/webhook/", status=204, ) mock_get_jwt.return_value = "" mock_get_installation_metadata.return_value = self.metadata self.create_integration( external_id="35.232.149.196:12345", organization=self.project.organization, provider="github_enterprise", metadata={ "domain_name": "35.232.149.196/baxterthehacker", "installation_id": "12345", "installation": { "id": "2", "private_key": "private_key", "verify_ssl": True, }, }, ) error = Exception("error") mock_event.side_effect = error response = self.client.post( path=self.url, data=PUSH_EVENT_EXAMPLE_INSTALLATION, content_type="application/json", HTTP_X_GITHUB_EVENT="push", HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196", HTTP_X_HUB_SIGNATURE="sha1=2a0586cc46490b17441834e1e143ec3d8c1fe032", HTTP_X_GITHUB_DELIVERY=str(uuid4()), ) assert response.status_code == 500 assert_failure_metric(mock_record, error) def test_anonymous_lookup( self, mock_get_installation_metadata: MagicMock, mock_get_jwt: MagicMock ) -> None: mock_get_installation_metadata.return_value = self.metadata self.create_integration( external_id="35.232.149.196:12345", organization=self.project.organization, provider="github_enterprise", name="octocat", metadata={ "domain_name": "35.232.149.196/baxterthehacker", "installation": { "id": "2", "private_key": "private_key", "verify_ssl": True, }, }, ) CommitAuthor.objects.create( external_id="github_enterprise:baxterthehacker", organization_id=self.project.organization_id, email="baxterthehacker@example.com", name="bàxterthehacker", ) response = self.client.post( path=self.url, data=PUSH_EVENT_EXAMPLE_INSTALLATION, content_type="application/json", HTTP_X_GITHUB_EVENT="push", HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196", HTTP_X_HUB_SIGNATURE="sha1=2a0586cc46490b17441834e1e143ec3d8c1fe032", HTTP_X_GITHUB_DELIVERY=str(uuid4()), ) assert response.status_code == 204 commit_list = list( Commit.objects.filter(organization_id=self.project.organization_id) .select_related("author") .order_by("-date_added") ) # should be skipping the #skipsentry commit assert len(commit_list) == 2 commit = commit_list[0] assert commit.key == "133d60480286590a610a0eb7352ff6e02b9674c4" assert commit.message == "Update README.md (àgain)" assert commit.author is not None assert commit.author.name == "bàxterthehacker" assert commit.author.email == "baxterthehacker@example.com" assert commit.date_added == datetime(2015, 5, 5, 23, 45, 15, tzinfo=timezone.utc) commit = commit_list[1] assert commit.key == "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c" assert commit.message == "Update README.md" assert commit.author is not None assert commit.author.name == "bàxterthehacker" assert commit.author.email == "baxterthehacker@example.com" assert commit.date_added == datetime(2015, 5, 5, 23, 40, 15, tzinfo=timezone.utc) @responses.activate def test_multiple_orgs( self, mock_get_installation_metadata: MagicMock, mock_get_jwt: MagicMock ) -> None: responses.add( responses.POST, "https://35.232.149.196/extensions/github-enterprise/webhook/", status=204, ) mock_get_jwt.return_value = "" mock_get_installation_metadata.return_value = self.metadata self.create_integration( external_id="35.232.149.196:12345", organization=self.project.organization, provider="github_enterprise", metadata={ "domain_name": "35.232.149.196/baxterthehacker", "installation_id": "12345", "installation": { "id": "2", "private_key": "private_key", "verify_ssl": True, }, }, ) org2 = self.create_organization() project2 = self.create_project(organization=org2, name="bar") Repository.objects.create( organization_id=project2.organization.id, external_id="77", provider="integrations:github_enterprise", name="another/repo", ) self.create_integration( external_id="35.232.149.196:99", organization=org2, provider="github_enterprise", metadata={ "domain_name": "35.232.149.196/another", "installation": { "installation_id": "99", "id": "2", "private_key": "private_key", "verify_ssl": True, }, }, ) response = self.client.post( path=self.url, data=PUSH_EVENT_EXAMPLE_INSTALLATION, content_type="application/json", HTTP_X_GITHUB_EVENT="push", HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196", HTTP_X_HUB_SIGNATURE="sha1=2a0586cc46490b17441834e1e143ec3d8c1fe032", HTTP_X_GITHUB_DELIVERY=str(uuid4()), ) assert response.status_code == 204 commit_list = list( Commit.objects.filter(organization_id=self.project.organization_id) .select_related("author") .order_by("-date_added") ) assert len(commit_list) == 2 commit_list = list( Commit.objects.filter(organization_id=org2.id) .select_related("author") .order_by("-date_added") ) assert len(commit_list) == 0 @patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
PushEventWebhookTest
python
getsentry__sentry
src/sentry/db/models/fields/bounded.py
{ "start": 2019, "end": 2396 }
class ____(models.BigIntegerField): description = _("Big Integer") MAX_VALUE = I64_MAX def get_internal_type(self) -> str: return "BigIntegerField" def get_prep_value(self, value: int) -> int: if value: value = int(value) assert value <= self.MAX_VALUE return super().get_prep_value(value)
BoundedBigIntegerField
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/class_methods.py
{ "start": 316, "end": 476 }
class ____: @classmethod def foo(cls, x) -> None: return _test_sink(x) def bar(): Test.foo(_test_source()) TInput = TypeVar("TInput")
Test
python
automl__auto-sklearn
autosklearn/evaluation/abstract_evaluator.py
{ "start": 3451, "end": 5962 }
class ____(DummyRegressor): def __init__( self, config: Configuration, random_state: Optional[Union[int, np.random.RandomState]], feat_type: Optional[FEAT_TYPE_TYPE] = None, init_params: Optional[Dict[str, Any]] = None, dataset_properties: Dict[str, Any] = {}, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, ): self.config = config if config == 1: super().__init__(strategy="mean") else: super().__init__(strategy="median") self.random_state = random_state self.init_params = init_params self.dataset_properties = dataset_properties self.include = include self.exclude = exclude self.feat_type = feat_type def pre_transform( self, X: np.ndarray, y: np.ndarray, fit_params: Optional[Dict[str, Any]] = None, ) -> Tuple[np.ndarray, Dict[str, Any]]: if fit_params is None: fit_params = {} return X, fit_params def fit( self, X: np.ndarray, y: np.ndarray, sample_weight: Optional[Union[np.ndarray, List]] = None, ) -> DummyRegressor: return super().fit(np.ones((X.shape[0], 1)), y, sample_weight=sample_weight) def fit_estimator( self, X: np.ndarray, y: np.ndarray, fit_params: Optional[Dict[str, Any]] = None, ) -> DummyRegressor: return self.fit(X, y) def predict(self, X: np.ndarray, batch_size: int = 1000) -> np.ndarray: new_X = np.ones((X.shape[0], 1)) return super().predict(new_X).astype(np.float32) def estimator_supports_iterative_fit(self) -> bool: return False def get_additional_run_info(self) -> Optional[TYPE_ADDITIONAL_INFO]: return None def _fit_and_suppress_warnings( logger: Union[logging.Logger, PicklableClientLogger], model: BaseEstimator, X: np.ndarray, y: np.ndarray, ) -> BaseEstimator: def send_warnings_to_log( message: Union[Warning, str], category: Type[Warning], filename: str, lineno: int, file: Optional[TextIO] = None, line: Optional[str] = None, ) -> None: logger.debug("%s:%s: %s:%s" % (filename, lineno, str(category), message)) return with warnings.catch_warnings(): warnings.showwarning = send_warnings_to_log model.fit(X, y) return model
MyDummyRegressor
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/in_airflow/partition_utils.py
{ "start": 216, "end": 375 }
class ____(Enum): TIME_WINDOW = "TIME_WINDOW" STATIC = "STATIC" MULTIPARTITIONED = "MULTIPARTITIONED" DYNAMIC = "DYNAMIC"
PartitionDefinitionType
python
spyder-ide__spyder
external-deps/spyder-remote-services/spyder_remote_services/services/files/compression.py
{ "start": 31636, "end": 31687 }
class ____(ZipValueError): pass
ZipIntegrityError
python
django__django
tests/utils_tests/test_decorators.py
{ "start": 246, "end": 585 }
class ____: def __init__(self, get_response): self.get_response = get_response def process_view(self, request, view_func, view_args, view_kwargs): pass process_view_dec = decorator_from_middleware(ProcessViewMiddleware) @process_view_dec def process_view(request): return HttpResponse()
ProcessViewMiddleware
python
coleifer__peewee
tests/kv.py
{ "start": 125, "end": 3820 }
class ____(DatabaseTestCase): def setUp(self): super(TestKeyValue, self).setUp() self._kvs = [] def tearDown(self): if self._kvs: self.database.drop_tables([kv.model for kv in self._kvs]) super(TestKeyValue, self).tearDown() def create_kv(self, **kwargs): kv = KeyValue(database=self.database, **kwargs) self._kvs.append(kv) return kv def test_basic_apis(self): KV = self.create_kv() KV['k1'] = 'v1' KV['k2'] = [0, 1, 2] self.assertEqual(KV['k1'], 'v1') self.assertEqual(KV['k2'], [0, 1, 2]) self.assertRaises(KeyError, lambda: KV['k3']) self.assertTrue((KV.key < 'k2') in KV) self.assertFalse((KV.key > 'k2') in KV) del KV['k1'] KV['k3'] = 'v3' self.assertFalse('k1' in KV) self.assertTrue('k3' in KV) self.assertEqual(sorted(KV.keys()), ['k2', 'k3']) self.assertEqual(len(KV), 2) data = dict(KV) self.assertEqual(data, { 'k2': [0, 1, 2], 'k3': 'v3'}) self.assertEqual(dict(KV), dict(KV.items())) self.assertEqual(KV.pop('k2'), [0, 1, 2]) self.assertRaises(KeyError, lambda: KV['k2']) self.assertRaises(KeyError, KV.pop, 'k2') self.assertEqual(KV.get('k3'), 'v3') self.assertTrue(KV.get('kx') is None) self.assertEqual(KV.get('kx', 'vx'), 'vx') self.assertTrue(KV.get('k4') is None) self.assertEqual(KV.setdefault('k4', 'v4'), 'v4') self.assertEqual(KV.get('k4'), 'v4') self.assertEqual(KV.get('k4', 'v5'), 'v4') KV.clear() self.assertEqual(len(KV), 0) def test_update(self): KV = self.create_kv() with self.assertQueryCount(1): KV.update(k1='v1', k2='v2', k3='v3') self.assertEqual(len(KV), 3) with self.assertQueryCount(1): KV.update(k1='v1-x', k3='v3-x', k4='v4') self.assertEqual(len(KV), 4) self.assertEqual(dict(KV), { 'k1': 'v1-x', 'k2': 'v2', 'k3': 'v3-x', 'k4': 'v4'}) KV['k1'] = 'v1-y' self.assertEqual(len(KV), 4) self.assertEqual(dict(KV), { 'k1': 'v1-y', 'k2': 'v2', 'k3': 'v3-x', 'k4': 'v4'}) def test_expressions(self): KV = self.create_kv(value_field=IntegerField(), ordered=True) with self.database.atomic(): for i in range(1, 11): KV['k%d' % i] = i self.assertEqual(KV[KV.key < 'k2'], [1, 10]) self.assertEqual(KV[KV.value > 7], [10, 8, 9]) self.assertEqual(KV[(KV.key > 'k2') & (KV.key < 'k6')], [3, 4, 5]) self.assertEqual(KV[KV.key == 'kx'], []) del KV[KV.key > 'k3'] self.assertEqual(dict(KV), { 'k1': 1, 'k2': 2, 'k3': 3, 'k10': 10}) KV[KV.value > 2] = 99 self.assertEqual(dict(KV), { 'k1': 1, 'k2': 2, 'k3': 99, 'k10': 99}) def test_integer_keys(self): KV = self.create_kv(key_field=IntegerField(primary_key=True), ordered=True) KV[1] = 'v1' KV[2] = 'v2' KV[10] = 'v10' self.assertEqual(list(KV), [(1, 'v1'), (2, 'v2'), (10, 'v10')]) self.assertEqual(list(KV.keys()), [1, 2, 10]) self.assertEqual(list(KV.values()), ['v1', 'v2', 'v10']) del KV[2] KV[1] = 'v1-x' KV[3] = 'v3' self.assertEqual(dict(KV), { 1: 'v1-x', 3: 'v3', 10: 'v10'})
TestKeyValue
python
getsentry__sentry
src/sentry/core/endpoints/organization_details.py
{ "start": 28115, "end": 37405 }
class ____(serializers.Serializer): # general slug = serializers.CharField( max_length=50, help_text="The new slug for the organization, which needs to be unique.", required=False, ) name = serializers.CharField( max_length=64, help_text="The new name for the organization.", required=False ) isEarlyAdopter = serializers.BooleanField( help_text="Specify `true` to opt-in to new features before they're released to the public.", required=False, ) hideAiFeatures = serializers.BooleanField( help_text="Specify `true` to hide AI features from the organization.", required=False, ) codecovAccess = serializers.BooleanField( help_text="Specify `true` to enable Code Coverage Insights. This feature is only available for organizations on the Team plan and above. Learn more about Codecov [here](/product/codecov/).", required=False, ) # membership defaultRole = serializers.ChoiceField( choices=roles.get_choices(), help_text="The default role new members will receive.", required=False, ) openMembership = serializers.BooleanField( help_text="Specify `true` to allow organization members to freely join any team.", required=False, ) eventsMemberAdmin = serializers.BooleanField( help_text="Specify `true` to allow members to delete events (including the delete & discard action) by granting them the `event:admin` scope.", required=False, ) alertsMemberWrite = serializers.BooleanField( help_text="Specify `true` to allow members to create, edit, and delete alert rules by granting them the `alerts:write` scope.", required=False, ) attachmentsRole = serializers.ChoiceField( choices=roles.get_choices(), help_text="The role required to download event attachments, such as native crash reports or log files.", required=False, ) debugFilesRole = serializers.ChoiceField( choices=roles.get_choices(), help_text="The role required to download debug information files, ProGuard mappings and source maps.", required=False, ) # avatar avatarType = serializers.ChoiceField( choices=(("letter_avatar", "Use initials"), ("upload", "Upload an image")), help_text="The type of display picture for the organization.", required=False, ) avatar = serializers.CharField( help_text="The image to upload as the organization avatar, in base64. Required if `avatarType` is `upload`.", required=False, ) # security & privacy require2FA = serializers.BooleanField( help_text="Specify `true` to require and enforce two-factor authentication for all members.", required=False, ) allowSharedIssues = serializers.BooleanField( help_text="Specify `true` to allow sharing of limited details on issues to anonymous users.", required=False, ) enhancedPrivacy = serializers.BooleanField( help_text="Specify `true` to enable enhanced privacy controls to limit personally identifiable information (PII) as well as source code in things like notifications.", required=False, ) scrapeJavaScript = serializers.BooleanField( help_text="Specify `true` to allow Sentry to scrape missing JavaScript source context when possible.", required=False, ) storeCrashReports = serializers.ChoiceField( choices=( (0, "Disabled"), (1, "1 per issue"), (5, "5 per issue"), (10, "10 per issue"), (20, "20 per issue"), (50, "50 per issue"), (100, "100 per issue"), (-1, "Unlimited"), ), help_text="How many native crash reports (such as Minidumps for improved processing and download in issue details) to store per issue.", required=False, ) allowJoinRequests = serializers.BooleanField( help_text="Specify `true` to allow users to request to join your organization.", required=False, ) # data scrubbing dataScrubber = serializers.BooleanField( help_text="Specify `true` to require server-side data scrubbing for all projects.", required=False, ) dataScrubberDefaults = serializers.BooleanField( help_text="Specify `true` to apply the default scrubbers to prevent things like passwords and credit cards from being stored for all projects.", required=False, ) sensitiveFields = serializers.ListField( child=serializers.CharField(), help_text="A list of additional global field names to match against when scrubbing data for all projects.", required=False, ) safeFields = serializers.ListField( child=serializers.CharField(), help_text="A list of global field names which data scrubbers should ignore.", required=False, ) scrubIPAddresses = serializers.BooleanField( help_text="Specify `true` to prevent IP addresses from being stored for new events on all projects.", required=False, ) relayPiiConfig = serializers.CharField( help_text="""Advanced data scrubbing rules that can be configured for each project as a JSON string. The new rules will only apply to new incoming events. For more details on advanced data scrubbing, see our [full documentation](/security-legal-pii/scrubbing/advanced-datascrubbing/). > Warning: Calling this endpoint with this field fully overwrites the advanced data scrubbing rules. Below is an example of a payload for a set of advanced data scrubbing rules for masking credit card numbers from the log message (equivalent to `[Mask] [Credit card numbers] from [$message]` in the Sentry app) and removing a specific key called `foo` (equivalent to `[Remove] [Anything] from [extra.foo]` in the Sentry app): ```json { relayPiiConfig: "{\\"rules\":{\\"0\\":{\\"type\\":\\"creditcard\\",\\"redaction\\":{\\"method\\":\\"mask\\"}},\\"1\\":{\\"type\\":\\"anything\\",\\"redaction\\":{\\"method\\":\\"remove\\"}}},\\"applications\\":{\\"$message\\":[\\"0\\"],\\"extra.foo\\":[\\"1\\"]}}" } ``` """, required=False, ) # relay trustedRelays = serializers.ListField( child=serializers.JSONField(), help_text="""A list of local Relays (the name, public key, and description as a JSON) registered for the organization. This feature is only available for organizations on the Business and Enterprise plans. Read more about Relay [here](/product/relay/). Below is an example of a list containing a single local Relay registered for the organization: ```json { trustedRelays: [ { name: "my-relay", publicKey: "eiwr9fdruw4erfh892qy4493reyf89ur34wefd90h", description: "Configuration for my-relay." } ] } ``` """, required=False, ) # github features githubPRBot = serializers.BooleanField( help_text="Specify `true` to allow Sentry to comment on recent pull requests suspected of causing issues. Requires a GitHub integration.", required=False, ) githubNudgeInvite = serializers.BooleanField( help_text="Specify `true` to allow Sentry to detect users committing to your GitHub repositories that are not part of your Sentry organization. Requires a GitHub integration.", required=False, ) # gitlab features gitlabPRBot = serializers.BooleanField( help_text="Specify `true` to allow Sentry to comment on recent pull requests suspected of causing issues. Requires a GitLab integration.", required=False, ) # slack features issueAlertsThreadFlag = serializers.BooleanField( help_text="Specify `true` to allow the Sentry Slack integration to post replies in threads for an Issue Alert notification. Requires a Slack integration.", required=False, ) metricAlertsThreadFlag = serializers.BooleanField( help_text="Specify `true` to allow the Sentry Slack integration to post replies in threads for a Metric Alert notification. Requires a Slack integration.", required=False, ) # restore org cancelDeletion = serializers.BooleanField( help_text="Specify `true` to restore an organization that is pending deletion.", required=False, ) # private attributes # legacy features apdexThreshold = serializers.IntegerField(required=False) # NOTE: We override the permission class of this endpoint in getsentry with the OrganizationDetailsPermission class @extend_schema(tags=["Organizations"]) @region_silo_endpoint
OrganizationDetailsPutSerializer
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/patch_stdout.py
{ "start": 2109, "end": 2176 }
class ____: "Sentinel value for stopping the stdout proxy."
_Done
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solverHigherOrder6.py
{ "start": 925, "end": 1161 }
class ____(Protocol): def __call__(self, func: _T) -> _T: ... def func5(cb: Proto, names: Any): val1 = cb(cb(names)) reveal_type(val1, expected_text="Any") val2 = cb(cb(1)) reveal_type(val2, expected_text="int")
Proto
python
run-llama__llama_index
llama-index-core/llama_index/core/readers/file/base.py
{ "start": 5595, "end": 31637 }
class ____(BaseReader, ResourcesReaderMixin, FileSystemReaderMixin): """ Simple directory reader. Load files from file directory. Automatically select the best file reader given file extensions. Args: input_dir (Union[Path, str]): Path to the directory. input_files (List): List of file paths to read (Optional; overrides input_dir, exclude) exclude (List): glob of python file paths to exclude (Optional) exclude_hidden (bool): Whether to exclude hidden files (dotfiles). exclude_empty (bool): Whether to exclude empty files (Optional). encoding (str): Encoding of the files. Default is utf-8. errors (str): how encoding and decoding errors are to be handled, see https://docs.python.org/3/library/functions.html#open recursive (bool): Whether to recursively search in subdirectories. False by default. filename_as_id (bool): Whether to use the filename as the document id. False by default. required_exts (Optional[List[str]]): List of required extensions. Default is None. file_extractor (Optional[Dict[str, BaseReader]]): A mapping of file extension to a BaseReader class that specifies how to convert that file to text. If not specified, use default from DEFAULT_FILE_READER_CLS. num_files_limit (Optional[int]): Maximum number of files to read. Default is None. file_metadata (Optional[Callable[[str], Dict]]): A function that takes in a filename and returns a Dict of metadata for the Document. Default is None. raise_on_error (bool): Whether to raise an error if a file cannot be read. fs (Optional[fsspec.AbstractFileSystem]): File system to use. Defaults to using the local file system. Can be changed to use any remote file system exposed via the fsspec interface. """ supported_suffix_fn: Callable = _try_loading_included_file_formats def __init__( self, input_dir: Optional[Union[Path, str]] = None, input_files: Optional[list] = None, exclude: Optional[list] = None, exclude_hidden: bool = True, exclude_empty: bool = False, errors: str = "ignore", recursive: bool = False, encoding: str = "utf-8", filename_as_id: bool = False, required_exts: Optional[list[str]] = None, file_extractor: Optional[dict[str, BaseReader]] = None, num_files_limit: Optional[int] = None, file_metadata: Optional[Callable[[str], dict]] = None, raise_on_error: bool = False, fs: fsspec.AbstractFileSystem | None = None, ) -> None: """Initialize with parameters.""" super().__init__() if not input_dir and not input_files: raise ValueError("Must provide either `input_dir` or `input_files`.") self.fs = fs or get_default_fs() self.errors = errors self.encoding = encoding self.exclude = exclude self.recursive = recursive self.exclude_hidden = exclude_hidden self.exclude_empty = exclude_empty self.required_exts = required_exts self.num_files_limit = num_files_limit self.raise_on_error = raise_on_error _Path = Path if is_default_fs(self.fs) else PurePosixPath if input_files: self.input_files = [] for path in input_files: if not self.fs.isfile(path): raise ValueError(f"File {path} does not exist.") input_file = _Path(path) self.input_files.append(input_file) elif input_dir: if not self.fs.isdir(input_dir): raise ValueError(f"Directory {input_dir} does not exist.") self.input_dir = _Path(input_dir) self.exclude = exclude self.input_files = self._add_files(self.input_dir) self.file_extractor = file_extractor or {} self.file_metadata = file_metadata or _DefaultFileMetadataFunc(self.fs) self.filename_as_id = filename_as_id def is_hidden(self, path: Path | PurePosixPath) -> bool: return any( part.startswith(".") and part not in [".", ".."] for part in path.parts ) def is_empty_file(self, path: Path | PurePosixPath) -> bool: return self.fs.isfile(str(path)) and self.fs.info(str(path)).get("size", 0) == 0 def _is_directory(self, path: Path | PurePosixPath) -> bool: """ Check if a path is a directory, with special handling for S3 filesystems. For S3 filesystems, directories are often represented as 0-byte objects ending with '/'. This method provides more reliable directory detection than fs.isdir() alone. """ try: # First try the standard isdir check if self.fs.isdir(path): return True # For non-default filesystems (like S3), also check for directory placeholders if not is_default_fs(self.fs): try: info = self.fs.info(str(path)) # Check if it's a 0-byte object ending with '/' # This is how S3 typically represents directory placeholders if ( info.get("size", 0) == 0 and str(path).endswith("/") and info.get("type") != "file" ): return True except Exception: # If we can't get info, fall back to the original isdir check pass return False except Exception: # If anything fails, assume it's not a directory to be safe return False def _add_files(self, input_dir: Path | PurePosixPath) -> list[Path | PurePosixPath]: """Add files.""" all_files: set[Path | PurePosixPath] = set() rejected_files: set[Path | PurePosixPath] = set() rejected_dirs: set[Path | PurePosixPath] = set() # Default to POSIX paths for non-default file systems (e.g. S3) _Path = Path if is_default_fs(self.fs) else PurePosixPath if self.exclude is not None: for excluded_pattern in self.exclude: if self.recursive: # Recursive glob excluded_glob = _Path(input_dir) / _Path("**") / excluded_pattern else: # Non-recursive glob excluded_glob = _Path(input_dir) / excluded_pattern for file in self.fs.glob(str(excluded_glob)): if self.fs.isdir(file): rejected_dirs.add(_Path(str(file))) else: rejected_files.add(_Path(str(file))) file_refs: list[Union[Path, PurePosixPath]] = [] limit = ( self.num_files_limit if self.num_files_limit is not None and self.num_files_limit > 0 else None ) c = 0 depth = 1000 if self.recursive else 1 for root, _, files in self.fs.walk( str(input_dir), topdown=True, maxdepth=depth ): for file in files: c += 1 if limit and c > limit: break file_refs.append(_Path(root, file)) for ref in file_refs: # Manually check if file is hidden or directory instead of # in glob for backwards compatibility. is_dir = self._is_directory(ref) skip_because_hidden = self.exclude_hidden and self.is_hidden(ref) skip_because_empty = self.exclude_empty and self.is_empty_file(ref) skip_because_bad_ext = ( self.required_exts is not None and ref.suffix not in self.required_exts ) skip_because_excluded = ref in rejected_files if not skip_because_excluded: if is_dir: ref_parent_dir = ref else: ref_parent_dir = self.fs._parent(ref) for rejected_dir in rejected_dirs: if str(ref_parent_dir).startswith(str(rejected_dir)): skip_because_excluded = True logger.debug( "Skipping %s because it in parent dir %s which is in %s", ref, ref_parent_dir, rejected_dir, ) break if ( is_dir or skip_because_hidden or skip_because_bad_ext or skip_because_excluded or skip_because_empty ): continue else: all_files.add(ref) new_input_files = sorted(all_files) if len(new_input_files) == 0: raise ValueError(f"No files found in {input_dir}.") # print total number of files added logger.debug( f"> [SimpleDirectoryReader] Total files added: {len(new_input_files)}" ) return new_input_files def _exclude_metadata(self, documents: list[Document]) -> list[Document]: """ Exclude metadata from documents. Args: documents (List[Document]): List of documents. """ for doc in documents: # Keep only metadata['file_path'] in both embedding and llm content # str, which contain extreme important context that about the chunks. # Dates is provided for convenience of postprocessor such as # TimeWeightedPostprocessor, but excluded for embedding and LLMprompts doc.excluded_embed_metadata_keys.extend( [ "file_name", "file_type", "file_size", "creation_date", "last_modified_date", "last_accessed_date", ] ) doc.excluded_llm_metadata_keys.extend( [ "file_name", "file_type", "file_size", "creation_date", "last_modified_date", "last_accessed_date", ] ) return documents def list_resources(self, *args: Any, **kwargs: Any) -> list[str]: """List files in the given filesystem.""" return [str(x) for x in self.input_files] def get_resource_info(self, resource_id: str, *args: Any, **kwargs: Any) -> dict: info_result = self.fs.info(resource_id) creation_date = _format_file_timestamp( info_result.get("created"), include_time=True ) last_modified_date = _format_file_timestamp( info_result.get("mtime"), include_time=True ) info_dict = { "file_path": resource_id, "file_size": info_result.get("size"), "creation_date": creation_date, "last_modified_date": last_modified_date, } # Ignore None values return { meta_key: meta_value for meta_key, meta_value in info_dict.items() if meta_value is not None } def load_resource( self, resource_id: str, *args: Any, **kwargs: Any ) -> list[Document]: file_metadata = kwargs.get("file_metadata", self.file_metadata) file_extractor = kwargs.get("file_extractor", self.file_extractor) filename_as_id = kwargs.get("filename_as_id", self.filename_as_id) encoding = kwargs.get("encoding", self.encoding) errors = kwargs.get("errors", self.errors) raise_on_error = kwargs.get("raise_on_error", self.raise_on_error) fs = kwargs.get("fs", self.fs) _Path = Path if is_default_fs(fs) else PurePosixPath return SimpleDirectoryReader.load_file( input_file=_Path(resource_id), file_metadata=file_metadata, file_extractor=file_extractor, filename_as_id=filename_as_id, encoding=encoding, errors=errors, raise_on_error=raise_on_error, fs=fs, **kwargs, ) async def aload_resource( self, resource_id: str, *args: Any, **kwargs: Any ) -> list[Document]: file_metadata = kwargs.get("file_metadata", self.file_metadata) file_extractor = kwargs.get("file_extractor", self.file_extractor) filename_as_id = kwargs.get("filename_as_id", self.filename_as_id) encoding = kwargs.get("encoding", self.encoding) errors = kwargs.get("errors", self.errors) raise_on_error = kwargs.get("raise_on_error", self.raise_on_error) fs = kwargs.get("fs", self.fs) _Path = Path if is_default_fs(fs) else PurePosixPath return await SimpleDirectoryReader.aload_file( input_file=_Path(resource_id), file_metadata=file_metadata, file_extractor=file_extractor, filename_as_id=filename_as_id, encoding=encoding, errors=errors, raise_on_error=raise_on_error, fs=fs, **kwargs, ) def read_file_content(self, input_file: Path, **kwargs: Any) -> bytes: """Read file content.""" fs: fsspec.AbstractFileSystem = kwargs.get("fs", self.fs) with fs.open(input_file, errors=self.errors, encoding=self.encoding) as f: # default mode is 'rb', we can cast the return value of f.read() return cast(bytes, f.read()) @staticmethod def load_file( input_file: Path | PurePosixPath, file_metadata: Callable[[str], dict], file_extractor: dict[str, BaseReader], filename_as_id: bool = False, encoding: str = "utf-8", errors: str = "ignore", raise_on_error: bool = False, fs: fsspec.AbstractFileSystem | None = None, ) -> list[Document]: """ Static method for loading file. NOTE: necessarily as a static method for parallel processing. Args: input_file (Path): File path to read file_metadata ([Callable[[str], Dict]]): A function that takes in a filename and returns a Dict of metadata for the Document. file_extractor (Dict[str, BaseReader]): A mapping of file extension to a BaseReader class that specifies how to convert that file to text. filename_as_id (bool): Whether to use the filename as the document id. encoding (str): Encoding of the files. Default is utf-8. errors (str): how encoding and decoding errors are to be handled, see https://docs.python.org/3/library/functions.html#open raise_on_error (bool): Whether to raise an error if a file cannot be read. fs (Optional[fsspec.AbstractFileSystem]): File system to use. Defaults to using the local file system. Can be changed to use any remote file system Returns: List[Document]: loaded documents """ # TODO: make this less redundant default_file_reader_cls = SimpleDirectoryReader.supported_suffix_fn() default_file_reader_suffix = list(default_file_reader_cls.keys()) metadata: dict | None = None documents: list[Document] = [] if file_metadata is not None: metadata = file_metadata(str(input_file)) file_suffix = input_file.suffix.lower() if file_suffix in default_file_reader_suffix or file_suffix in file_extractor: # use file readers if file_suffix not in file_extractor: # instantiate file reader if not already reader_cls = default_file_reader_cls[file_suffix] file_extractor[file_suffix] = reader_cls() reader = file_extractor[file_suffix] # load data -- catch all errors except for ImportError try: kwargs: dict[str, Any] = {"extra_info": metadata} if fs and not is_default_fs(fs): kwargs["fs"] = fs docs = reader.load_data(input_file, **kwargs) except ImportError as e: # ensure that ImportError is raised so user knows # about missing dependencies raise ImportError(str(e)) except Exception as e: if raise_on_error: raise Exception("Error loading file") from e # otherwise, just skip the file and report the error print( f"Failed to load file {input_file} with error: {e}. Skipping...", flush=True, ) return [] # iterate over docs if needed if filename_as_id: for i, doc in enumerate(docs): doc.id_ = f"{input_file!s}_part_{i}" documents.extend(docs) else: # do standard read fs = fs or get_default_fs() with fs.open(input_file, errors=errors, encoding=encoding) as f: data = cast(bytes, f.read()).decode(encoding, errors=errors) doc = Document(text=data, metadata=metadata or {}) # type: ignore if filename_as_id: doc.id_ = str(input_file) documents.append(doc) return documents @staticmethod async def aload_file( input_file: Path | PurePosixPath, file_metadata: Callable[[str], dict], file_extractor: dict[str, BaseReader], filename_as_id: bool = False, encoding: str = "utf-8", errors: str = "ignore", raise_on_error: bool = False, fs: fsspec.AbstractFileSystem | None = None, ) -> list[Document]: """Load file asynchronously.""" # TODO: make this less redundant default_file_reader_cls = SimpleDirectoryReader.supported_suffix_fn() default_file_reader_suffix = list(default_file_reader_cls.keys()) metadata: dict | None = None documents: list[Document] = [] if file_metadata is not None: metadata = file_metadata(str(input_file)) file_suffix = input_file.suffix.lower() if file_suffix in default_file_reader_suffix or file_suffix in file_extractor: # use file readers if file_suffix not in file_extractor: # instantiate file reader if not already reader_cls = default_file_reader_cls[file_suffix] file_extractor[file_suffix] = reader_cls() reader = file_extractor[file_suffix] # load data -- catch all errors except for ImportError try: kwargs: dict[str, Any] = {"extra_info": metadata} if fs and not is_default_fs(fs): kwargs["fs"] = fs docs = await reader.aload_data(input_file, **kwargs) except ImportError as e: # ensure that ImportError is raised so user knows # about missing dependencies raise ImportError(str(e)) except Exception as e: if raise_on_error: raise # otherwise, just skip the file and report the error print( f"Failed to load file {input_file} with error: {e}. Skipping...", flush=True, ) return [] # iterate over docs if needed if filename_as_id: for i, doc in enumerate(docs): doc.id_ = f"{input_file!s}_part_{i}" documents.extend(docs) else: # do standard read fs = fs or get_default_fs() with fs.open(input_file, errors=errors, encoding=encoding) as f: data = cast(bytes, f.read()).decode(encoding, errors=errors) doc = Document(text=data, metadata=metadata or {}) # type: ignore if filename_as_id: doc.id_ = str(input_file) documents.append(doc) return documents def load_data( self, show_progress: bool = False, num_workers: int | None = None, fs: fsspec.AbstractFileSystem | None = None, ) -> list[Document]: """ Load data from the input directory. Args: show_progress (bool): Whether to show tqdm progress bars. Defaults to False. num_workers (Optional[int]): Number of workers to parallelize data-loading over. fs (Optional[fsspec.AbstractFileSystem]): File system to use. If fs was specified in the constructor, it will override the fs parameter here. Returns: List[Document]: A list of documents. """ documents = [] fs = fs or self.fs load_file_with_args = partial( SimpleDirectoryReader.load_file, file_metadata=self.file_metadata, file_extractor=self.file_extractor, filename_as_id=self.filename_as_id, encoding=self.encoding, errors=self.errors, raise_on_error=self.raise_on_error, fs=fs, ) if num_workers and num_workers > 1: num_cpus = multiprocessing.cpu_count() if num_workers > num_cpus: warnings.warn( "Specified num_workers exceed number of CPUs in the system. " "Setting `num_workers` down to the maximum CPU count." ) num_workers = num_cpus with multiprocessing.get_context("spawn").Pool(num_workers) as pool: map_iterator = cast( Iterable[list[Document]], get_tqdm_iterable( pool.imap(load_file_with_args, self.input_files), show_progress=show_progress, desc="Loading files", total=len(self.input_files), ), ) for result in map_iterator: documents.extend(result) else: files_to_process = cast( list[Union[Path, PurePosixPath]], get_tqdm_iterable( self.input_files, show_progress=show_progress, desc="Loading files", ), ) for input_file in files_to_process: documents.extend(load_file_with_args(input_file)) return self._exclude_metadata(documents) async def aload_data( self, show_progress: bool = False, num_workers: int | None = None, fs: fsspec.AbstractFileSystem | None = None, ) -> list[Document]: """ Load data from the input directory. Args: show_progress (bool): Whether to show tqdm progress bars. Defaults to False. num_workers (Optional[int]): Number of workers to parallelize data-loading over. fs (Optional[fsspec.AbstractFileSystem]): File system to use. If fs was specified in the constructor, it will override the fs parameter here. Returns: List[Document]: A list of documents. """ files_to_process = self.input_files fs = fs or self.fs coroutines = [ SimpleDirectoryReader.aload_file( input_file, self.file_metadata, self.file_extractor, self.filename_as_id, self.encoding, self.errors, self.raise_on_error, fs, ) for input_file in files_to_process ] if num_workers: document_lists = await run_jobs( coroutines, show_progress=show_progress, workers=num_workers ) elif show_progress: _asyncio = get_asyncio_module(show_progress=show_progress) document_lists = await _asyncio.gather(*coroutines) else: document_lists = await asyncio.gather(*coroutines) documents = [doc for doc_list in document_lists for doc in doc_list] return self._exclude_metadata(documents) def iter_data( self, show_progress: bool = False ) -> Generator[list[Document], Any, Any]: """ Load data iteratively from the input directory. Args: show_progress (bool): Whether to show tqdm progress bars. Defaults to False. Returns: Generator[List[Document]]: A list of documents. """ files_to_process = cast( list[Union[Path, PurePosixPath]], get_tqdm_iterable( self.input_files, show_progress=show_progress, desc="Loading files", ), ) for input_file in files_to_process: documents = SimpleDirectoryReader.load_file( input_file=input_file, file_metadata=self.file_metadata, file_extractor=self.file_extractor, filename_as_id=self.filename_as_id, encoding=self.encoding, errors=self.errors, raise_on_error=self.raise_on_error, fs=self.fs, ) documents = self._exclude_metadata(documents) if len(documents) > 0: yield documents
SimpleDirectoryReader
python
davidhalter__jedi
jedi/inference/value/function.py
{ "start": 13613, "end": 14427 }
class ____(BaseFunctionExecutionContext): def __init__(self, function_value, arguments): super().__init__(function_value) self._arguments = arguments def get_filters(self, until_position=None, origin_scope=None): yield FunctionExecutionFilter( self, self._value, until_position=until_position, origin_scope=origin_scope, arguments=self._arguments ) def infer_annotations(self): from jedi.inference.gradual.annotation import infer_return_types return infer_return_types(self._value, self._arguments) def get_param_names(self): return [ ParamName(self._value, param.name, self._arguments) for param in self._value.tree_node.get_params() ]
FunctionExecutionContext
python
jazzband__django-formtools
tests/wizard/namedwizardtests/tests.py
{ "start": 13029, "end": 14056 }
class ____(NamedWizardTests, TestCase): wizard_urlname = 'nwiz_session' wizard_step_1_data = { 'session_contact_wizard-current_step': 'form1', } wizard_step_data = ( { 'form1-name': 'Pony', 'form1-thirsty': '2', 'session_contact_wizard-current_step': 'form1', }, { 'form2-address1': '123 Main St', 'form2-address2': 'Djangoland', 'session_contact_wizard-current_step': 'form2', }, { 'form3-random_crap': 'blah blah', 'session_contact_wizard-current_step': 'form3', }, { 'form4-INITIAL_FORMS': '0', 'form4-TOTAL_FORMS': '2', 'form4-MAX_NUM_FORMS': '0', 'form4-0-random_crap': 'blah blah', 'form4-1-random_crap': 'blah blah', 'session_contact_wizard-current_step': 'form4', } ) @override_settings(ROOT_URLCONF='tests.wizard.namedwizardtests.urls')
NamedSessionWizardTests
python
scipy__scipy
scipy/optimize/tests/test__numdiff.py
{ "start": 5235, "end": 22285 }
class ____: def fun_scalar_scalar(self, x): return np.sinh(x) def jac_scalar_scalar(self, x): return np.cosh(x) def fun_scalar_vector(self, x): return np.array([x[0]**2, np.tan(x[0]), np.exp(x[0])]) def jac_scalar_vector(self, x): return np.array( [2 * x[0], np.cos(x[0]) ** -2, np.exp(x[0])]).reshape(-1, 1) def fun_vector_scalar(self, x): return np.sin(x[0] * x[1]) * np.log(x[0]) def wrong_dimensions_fun(self, x): return np.array([x**2, np.tan(x), np.exp(x)]) def jac_vector_scalar(self, x): return np.array([ x[1] * np.cos(x[0] * x[1]) * np.log(x[0]) + np.sin(x[0] * x[1]) / x[0], x[0] * np.cos(x[0] * x[1]) * np.log(x[0]) ]) def fun_vector_vector(self, x): return np.array([ x[0] * np.sin(x[1]), x[1] * np.cos(x[0]), x[0] ** 3 * x[1] ** -0.5 ]) def fun_vector_vector_with_arg(self, x, arg): """Used to test passing custom arguments with check_derivative()""" assert arg == 42 return np.array([ x[0] * np.sin(x[1]), x[1] * np.cos(x[0]), x[0] ** 3 * x[1] ** -0.5 ]) def jac_vector_vector(self, x): return np.array([ [np.sin(x[1]), x[0] * np.cos(x[1])], [-x[1] * np.sin(x[0]), np.cos(x[0])], [3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5] ]) def jac_vector_vector_with_arg(self, x, arg): """Used to test passing custom arguments with check_derivative()""" assert arg == 42 return np.array([ [np.sin(x[1]), x[0] * np.cos(x[1])], [-x[1] * np.sin(x[0]), np.cos(x[0])], [3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5] ]) def fun_parametrized(self, x, c0, c1=1.0): return np.array([np.exp(c0 * x[0]), np.exp(c1 * x[1])]) def jac_parametrized(self, x, c0, c1=0.1): return np.array([ [c0 * np.exp(c0 * x[0]), 0], [0, c1 * np.exp(c1 * x[1])] ]) def fun_with_nan(self, x): return x if np.abs(x) <= 1e-8 else np.nan def jac_with_nan(self, x): return 1.0 if np.abs(x) <= 1e-8 else np.nan def fun_zero_jacobian(self, x): return np.array([x[0] * x[1], np.cos(x[0] * x[1])]) def jac_zero_jacobian(self, x): return np.array([ [x[1], x[0]], [-x[1] * np.sin(x[0] * x[1]), -x[0] * np.sin(x[0] * x[1])] ]) def jac_non_numpy(self, x): # x can be a scalar or an array [val]. # Cast to true scalar before handing over to math.exp xp = np.asarray(x).item() return math.exp(xp) def test_scalar_scalar(self): x0 = 1.0 jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0, method='2-point') jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0) jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0, method='cs') jac_true = self.jac_scalar_scalar(x0) assert_allclose(jac_diff_2, jac_true, rtol=1e-6) assert_allclose(jac_diff_3, jac_true, rtol=1e-9) assert_allclose(jac_diff_4, jac_true, rtol=1e-12) def test_scalar_scalar_abs_step(self): # can approx_derivative use abs_step? x0 = 1.0 jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0, method='2-point', abs_step=1.49e-8) jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0, abs_step=1.49e-8) jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0, method='cs', abs_step=1.49e-8) jac_true = self.jac_scalar_scalar(x0) assert_allclose(jac_diff_2, jac_true, rtol=1e-6) assert_allclose(jac_diff_3, jac_true, rtol=1e-9) assert_allclose(jac_diff_4, jac_true, rtol=1e-12) def test_scalar_vector(self): x0 = 0.5 with MapWrapper(2) as mapper: jac_diff_2 = approx_derivative(self.fun_scalar_vector, x0, method='2-point', workers=mapper) jac_diff_3 = approx_derivative(self.fun_scalar_vector, x0, workers=map) jac_diff_4 = approx_derivative(self.fun_scalar_vector, x0, method='cs', workers=None) jac_true = self.jac_scalar_vector(np.atleast_1d(x0)) assert_allclose(jac_diff_2, jac_true, rtol=1e-6) assert_allclose(jac_diff_3, jac_true, rtol=1e-9) assert_allclose(jac_diff_4, jac_true, rtol=1e-12) @pytest.mark.fail_slow(5.0) def test_workers_evaluations_and_nfev(self): # check that nfev consumed by approx_derivative is tracked properly # and that parallel evaluation is same as series x0 = [0.5, 1.5, 2.0] with MapWrapper(2) as mapper: md2, mdct2 = approx_derivative(rosen, x0, method='2-point', workers=mapper, full_output=True) md3, mdct3 = approx_derivative(rosen, x0, workers=mapper, full_output=True) # supply a number for workers. This is not normally recommended # for upstream workers as setting up processes incurs a large overhead md4, mdct4 = approx_derivative(rosen, x0, method='cs', workers=2, full_output=True) sfr = _ScalarFunctionWrapper(rosen) d2, dct2 = approx_derivative(sfr, x0, method='2-point', full_output=True) assert_equal(dct2['nfev'], sfr.nfev) sfr.nfev = 0 d3, dct3 = approx_derivative(sfr, x0, full_output=True) assert_equal(dct3['nfev'], sfr.nfev) sfr.nfev = 0 d4, dct4 = approx_derivative(sfr, x0, method='cs', full_output=True) assert_equal(dct4['nfev'], sfr.nfev) assert_equal(mdct2['nfev'], dct2['nfev']) assert_equal(mdct3['nfev'], dct3['nfev']) assert_equal(mdct4['nfev'], dct4['nfev']) # also check that gradients are equivalent assert_equal(md2, d2) assert_equal(md3, d3) assert_equal(md4, d4) def test_vector_scalar(self): x0 = np.array([100.0, -0.5]) jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0, method='2-point') jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0) jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0, method='cs') jac_true = self.jac_vector_scalar(x0) assert_allclose(jac_diff_2, jac_true, rtol=1e-6) assert_allclose(jac_diff_3, jac_true, rtol=1e-7) assert_allclose(jac_diff_4, jac_true, rtol=1e-12) def test_vector_scalar_abs_step(self): # can approx_derivative use abs_step? x0 = np.array([100.0, -0.5]) jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0, method='2-point', abs_step=1.49e-8) jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0, abs_step=1.49e-8, rel_step=np.inf) jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0, method='cs', abs_step=1.49e-8) jac_true = self.jac_vector_scalar(x0) assert_allclose(jac_diff_2, jac_true, rtol=1e-6) assert_allclose(jac_diff_3, jac_true, rtol=3e-9) assert_allclose(jac_diff_4, jac_true, rtol=1e-12) def test_vector_vector(self): x0 = np.array([-100.0, 0.2]) jac_diff_2 = approx_derivative(self.fun_vector_vector, x0, method='2-point') jac_diff_3 = approx_derivative(self.fun_vector_vector, x0) with MapWrapper(2) as mapper: jac_diff_4 = approx_derivative(self.fun_vector_vector, x0, method='cs', workers=mapper) jac_true = self.jac_vector_vector(x0) assert_allclose(jac_diff_2, jac_true, rtol=1e-5) assert_allclose(jac_diff_3, jac_true, rtol=1e-6) assert_allclose(jac_diff_4, jac_true, rtol=1e-12) def test_wrong_dimensions(self): x0 = 1.0 assert_raises(RuntimeError, approx_derivative, self.wrong_dimensions_fun, x0) f0 = self.wrong_dimensions_fun(np.atleast_1d(x0)) assert_raises(ValueError, approx_derivative, self.wrong_dimensions_fun, x0, f0=f0) def test_custom_rel_step(self): x0 = np.array([-0.1, 0.1]) jac_diff_2 = approx_derivative(self.fun_vector_vector, x0, method='2-point', rel_step=1e-4) jac_diff_3 = approx_derivative(self.fun_vector_vector, x0, rel_step=1e-4) jac_true = self.jac_vector_vector(x0) assert_allclose(jac_diff_2, jac_true, rtol=1e-2) assert_allclose(jac_diff_3, jac_true, rtol=1e-4) def test_options(self): x0 = np.array([1.0, 1.0]) c0 = -1.0 c1 = 1.0 lb = 0.0 ub = 2.0 f0 = self.fun_parametrized(x0, c0, c1=c1) rel_step = np.array([-1e-6, 1e-7]) jac_true = self.jac_parametrized(x0, c0, c1) jac_diff_2 = approx_derivative( self.fun_parametrized, x0, method='2-point', rel_step=rel_step, f0=f0, args=(c0,), kwargs=dict(c1=c1), bounds=(lb, ub)) jac_diff_3 = approx_derivative( self.fun_parametrized, x0, rel_step=rel_step, f0=f0, args=(c0,), kwargs=dict(c1=c1), bounds=(lb, ub)) assert_allclose(jac_diff_2, jac_true, rtol=1e-6) assert_allclose(jac_diff_3, jac_true, rtol=1e-9) def test_with_bounds_2_point(self): lb = -np.ones(2) ub = np.ones(2) x0 = np.array([-2.0, 0.2]) assert_raises(ValueError, approx_derivative, self.fun_vector_vector, x0, bounds=(lb, ub)) x0 = np.array([-1.0, 1.0]) jac_diff = approx_derivative(self.fun_vector_vector, x0, method='2-point', bounds=(lb, ub)) jac_true = self.jac_vector_vector(x0) assert_allclose(jac_diff, jac_true, rtol=1e-6) def test_with_bounds_3_point(self): lb = np.array([1.0, 1.0]) ub = np.array([2.0, 2.0]) x0 = np.array([1.0, 2.0]) jac_true = self.jac_vector_vector(x0) jac_diff = approx_derivative(self.fun_vector_vector, x0) assert_allclose(jac_diff, jac_true, rtol=1e-9) jac_diff = approx_derivative(self.fun_vector_vector, x0, bounds=(lb, np.inf)) assert_allclose(jac_diff, jac_true, rtol=1e-9) jac_diff = approx_derivative(self.fun_vector_vector, x0, bounds=(-np.inf, ub)) assert_allclose(jac_diff, jac_true, rtol=1e-9) jac_diff = approx_derivative(self.fun_vector_vector, x0, bounds=(lb, ub)) assert_allclose(jac_diff, jac_true, rtol=1e-9) def test_tight_bounds(self): x0 = np.array([10.0, 10.0]) lb = x0 - 3e-9 ub = x0 + 2e-9 jac_true = self.jac_vector_vector(x0) jac_diff = approx_derivative( self.fun_vector_vector, x0, method='2-point', bounds=(lb, ub)) assert_allclose(jac_diff, jac_true, rtol=1e-6) jac_diff = approx_derivative( self.fun_vector_vector, x0, method='2-point', rel_step=1e-6, bounds=(lb, ub)) assert_allclose(jac_diff, jac_true, rtol=1e-6) jac_diff = approx_derivative( self.fun_vector_vector, x0, bounds=(lb, ub)) assert_allclose(jac_diff, jac_true, rtol=1e-6) jac_diff = approx_derivative( self.fun_vector_vector, x0, rel_step=1e-6, bounds=(lb, ub)) assert_allclose(jac_true, jac_diff, rtol=1e-6) def test_bound_switches(self): lb = -1e-8 ub = 1e-8 x0 = 0.0 jac_true = self.jac_with_nan(x0) jac_diff_2 = approx_derivative( self.fun_with_nan, x0, method='2-point', rel_step=1e-6, bounds=(lb, ub)) jac_diff_3 = approx_derivative( self.fun_with_nan, x0, rel_step=1e-6, bounds=(lb, ub)) assert_allclose(jac_diff_2, jac_true, rtol=1e-6) assert_allclose(jac_diff_3, jac_true, rtol=1e-9) x0 = 1e-8 jac_true = self.jac_with_nan(x0) jac_diff_2 = approx_derivative( self.fun_with_nan, x0, method='2-point', rel_step=1e-6, bounds=(lb, ub)) jac_diff_3 = approx_derivative( self.fun_with_nan, x0, rel_step=1e-6, bounds=(lb, ub)) assert_allclose(jac_diff_2, jac_true, rtol=1e-6) assert_allclose(jac_diff_3, jac_true, rtol=1e-9) def test_non_numpy(self): x0 = 1.0 jac_true = self.jac_non_numpy(x0) jac_diff_2 = approx_derivative(self.jac_non_numpy, x0, method='2-point') jac_diff_3 = approx_derivative(self.jac_non_numpy, x0) assert_allclose(jac_diff_2, jac_true, rtol=1e-6) assert_allclose(jac_diff_3, jac_true, rtol=1e-8) # math.exp cannot handle complex arguments, hence this raises assert_raises(TypeError, approx_derivative, self.jac_non_numpy, x0, **dict(method='cs')) def test_fp(self): # checks that approx_derivative works for FP size other than 64. # Example is derived from the minimal working example in gh12991. rng = np.random.default_rng(1) def func(p, x): return p[0] + p[1] * x def err(p, x, y): return func(p, x) - y x = np.linspace(0, 1, 100, dtype=np.float64) y = rng.random(size=100, dtype=np.float64) p0 = np.array([-1.0, -1.0]) jac_fp64 = approx_derivative(err, p0, method='2-point', args=(x, y)) # parameter vector is float32, func output is float64 jac_fp = approx_derivative(err, p0.astype(np.float32), method='2-point', args=(x, y)) assert err(p0, x, y).dtype == np.float64 assert_allclose(jac_fp, jac_fp64, atol=1e-3) # parameter vector is float64, func output is float32 def err_fp32(p): assert p.dtype == np.float32 return err(p, x, y).astype(np.float32) jac_fp = approx_derivative(err_fp32, p0.astype(np.float32), method='2-point') assert_allclose(jac_fp, jac_fp64, atol=1e-3) # check upper bound of error on the derivative for 2-point def f(x): return np.sin(x) def g(x): return np.cos(x) def hess(x): return -np.sin(x) def calc_atol(h, x0, f, hess, EPS): # truncation error t0 = h / 2 * max(np.abs(hess(x0)), np.abs(hess(x0 + h))) # roundoff error. There may be a divisor (>1) missing from # the following line, so this contribution is possibly # overestimated t1 = EPS / h * max(np.abs(f(x0)), np.abs(f(x0 + h))) return t0 + t1 for dtype in [np.float16, np.float32, np.float64]: EPS = np.finfo(dtype).eps x0 = np.array(1.0).astype(dtype) h = _compute_absolute_step(None, x0, f(x0), '2-point') atol = calc_atol(h, x0, f, hess, EPS) err = approx_derivative(f, x0, method='2-point', abs_step=h) - g(x0) assert abs(err) < atol def test_check_derivative(self): x0 = np.array([-10.0, 10]) accuracy = check_derivative(self.fun_vector_vector, self.jac_vector_vector, x0) assert_(accuracy < 1e-9) accuracy = check_derivative(self.fun_vector_vector, self.jac_vector_vector, x0) assert_(accuracy < 1e-6) x0 = np.array([0.0, 0.0]) accuracy = check_derivative(self.fun_zero_jacobian, self.jac_zero_jacobian, x0) assert_(accuracy == 0) accuracy = check_derivative(self.fun_zero_jacobian, self.jac_zero_jacobian, x0) assert_(accuracy == 0) def test_check_derivative_with_kwargs(self): x0 = np.array([-10.0, 10]) accuracy = check_derivative(self.fun_vector_vector_with_arg, self.jac_vector_vector_with_arg, x0, kwargs={'arg': 42}) assert_(accuracy < 1e-9)
TestApproxDerivativesDense
python
openai__openai-python
src/openai/lib/_tools.py
{ "start": 815, "end": 1969 }
class ____(Dict[str, Any]): model: type[pydantic.BaseModel] def __init__(self, tool: ResponsesFunctionToolParam, model: type[pydantic.BaseModel]) -> None: super().__init__(tool) self.model = model def cast(self) -> ResponsesFunctionToolParam: return cast(ResponsesFunctionToolParam, self) def pydantic_function_tool( model: type[pydantic.BaseModel], *, name: str | None = None, # inferred from class name by default description: str | None = None, # inferred from class docstring by default ) -> ChatCompletionFunctionToolParam: if description is None: # note: we intentionally don't use `.getdoc()` to avoid # including pydantic's docstrings description = model.__doc__ function = PydanticFunctionTool( { "name": name or model.__name__, "strict": True, "parameters": to_strict_json_schema(model), }, model, ).cast() if description is not None: function["description"] = description return { "type": "function", "function": function, }
ResponsesPydanticFunctionTool
python
lepture__authlib
authlib/integrations/httpx_client/oauth2_client.py
{ "start": 6808, "end": 9215 }
class ____(_OAuth2Client, httpx.Client): SESSION_REQUEST_PARAMS = HTTPX_CLIENT_KWARGS client_auth_class = OAuth2ClientAuth token_auth_class = OAuth2Auth oauth_error_class = OAuthError def __init__( self, client_id=None, client_secret=None, token_endpoint_auth_method=None, revocation_endpoint_auth_method=None, scope=None, redirect_uri=None, token=None, token_placement="header", update_token=None, **kwargs, ): # extract httpx.Client kwargs client_kwargs = self._extract_session_request_params(kwargs) # app keyword was dropped! app_value = client_kwargs.pop("app", None) if app_value is not None: client_kwargs["transport"] = httpx.WSGITransport(app=app_value) httpx.Client.__init__(self, **client_kwargs) _OAuth2Client.__init__( self, session=self, client_id=client_id, client_secret=client_secret, token_endpoint_auth_method=token_endpoint_auth_method, revocation_endpoint_auth_method=revocation_endpoint_auth_method, scope=scope, redirect_uri=redirect_uri, token=token, token_placement=token_placement, update_token=update_token, **kwargs, ) @staticmethod def handle_error(error_type, error_description): raise OAuthError(error_type, error_description) def request( self, method, url, withhold_token=False, auth=USE_CLIENT_DEFAULT, **kwargs ): if not withhold_token and auth is USE_CLIENT_DEFAULT: if not self.token: raise MissingTokenError() if not self.ensure_active_token(self.token): raise InvalidTokenError() auth = self.token_auth return super().request(method, url, auth=auth, **kwargs) def stream( self, method, url, withhold_token=False, auth=USE_CLIENT_DEFAULT, **kwargs ): if not withhold_token and auth is USE_CLIENT_DEFAULT: if not self.token: raise MissingTokenError() if not self.ensure_active_token(self.token): raise InvalidTokenError() auth = self.token_auth return super().stream(method, url, auth=auth, **kwargs)
OAuth2Client
python
getsentry__sentry
tests/sentry/sentry_apps/test_sentry_app_creator.py
{ "start": 6950, "end": 11316 }
class ____(TestCase): def setUp(self) -> None: self.user = self.create_user() self.org = self.create_organization(owner=self.user) self.project = self.create_project(organization=self.org) def run_creator(self, **kwargs): return SentryAppCreator( is_internal=True, verify_install=False, author=kwargs.pop("author", self.org.name), name="nulldb", organization_id=self.org.id, scopes=[ "project:read", ], webhook_url="http://example.com", schema={"elements": [self.create_issue_link_schema()]}, **kwargs, ).run(user=self.user, request=kwargs.pop("request", None)) def test_slug(self) -> None: sentry_app = self.run_creator() # test slug is the name + a UUID assert sentry_app.slug[:7] == "nulldb-" assert len(sentry_app.slug) == 13 def test_creates_internal_sentry_app(self) -> None: sentry_app = self.run_creator() assert sentry_app.author == self.org.name assert SentryApp.objects.filter(slug=sentry_app.slug).exists() def test_installs_to_org(self) -> None: sentry_app = self.run_creator() assert SentryAppInstallation.objects.filter( organization_id=self.org.id, sentry_app=sentry_app ).exists() def test_author(self) -> None: sentry_app = self.run_creator(author="custom") assert sentry_app.author == "custom" @patch("sentry.sentry_apps.tasks.sentry_apps.installation_webhook.delay") def test_does_not_notify_service(self, delay: MagicMock) -> None: self.run_creator() assert not len(delay.mock_calls) def test_creates_access_token(self) -> None: sentry_app = self.run_creator() install = SentryAppInstallation.objects.get( organization_id=self.org.id, sentry_app=sentry_app ) assert install.api_token def test_skips_creating_auth_token_when_flag_is_true(self) -> None: app = SentryAppCreator( is_internal=True, verify_install=False, author=self.org.name, name="nulldb", organization_id=self.org.id, scopes=[ "project:read", ], webhook_url="http://example.com", schema={"elements": [self.create_issue_link_schema()]}, ).run(user=self.user, request=None, skip_default_auth_token=True) install = SentryAppInstallation.objects.get(organization_id=self.org.id, sentry_app=app) assert install.api_token is None @patch("sentry.utils.audit.create_audit_entry") def test_audits(self, create_audit_entry: MagicMock) -> None: SentryAppCreator( name="nulldb", author="Sentry", organization_id=self.org.id, is_internal=True, verify_install=False, scopes=[ "project:read", ], webhook_url="http://example.com", schema={"elements": [self.create_issue_link_schema()]}, ).run(user=self.user, request=MagicMock()) ( _, _, (_, kwargs), ) = create_audit_entry.call_args_list assert kwargs["organization_id"] == self.org.id assert kwargs["target_object"] == self.org.id assert kwargs["event"] == audit_log.get_event_id("INTERNAL_INTEGRATION_ADD") @patch("sentry.analytics.record") @patch("sentry.utils.audit.create_audit_entry") def test_records_analytics(self, create_audit_entry: MagicMock, record: MagicMock) -> None: sentry_app = SentryAppCreator( name="nulldb", author="Sentry", organization_id=self.org.id, is_internal=True, verify_install=False, scopes=["project:read"], webhook_url="http://example.com", schema={"elements": [self.create_issue_link_schema()]}, ).run(user=self.user, request=MagicMock()) assert_any_analytics_event( record, InternalIntegrationCreatedEvent( user_id=self.user.id, organization_id=self.org.id, sentry_app=sentry_app.slug, ), )
TestInternalCreator
python
python__mypy
mypy/fixup.py
{ "start": 1204, "end": 9118 }
class ____(NodeVisitor[None]): current_info: TypeInfo | None = None def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None: self.modules = modules self.allow_missing = allow_missing self.type_fixer = TypeFixer(self.modules, allow_missing) # NOTE: This method isn't (yet) part of the NodeVisitor API. def visit_type_info(self, info: TypeInfo) -> None: save_info = self.current_info try: self.current_info = info if info.defn: info.defn.accept(self) if info.names: self.visit_symbol_table(info.names, info.fullname) if info.bases: for base in info.bases: base.accept(self.type_fixer) if info._promote: for p in info._promote: p.accept(self.type_fixer) if info.tuple_type: info.tuple_type.accept(self.type_fixer) info.update_tuple_type(info.tuple_type) if info.special_alias: info.special_alias.alias_tvars = list(info.defn.type_vars) for i, t in enumerate(info.defn.type_vars): if isinstance(t, TypeVarTupleType): info.special_alias.tvar_tuple_index = i if info.typeddict_type: info.typeddict_type.accept(self.type_fixer) info.update_typeddict_type(info.typeddict_type) if info.special_alias: info.special_alias.alias_tvars = list(info.defn.type_vars) for i, t in enumerate(info.defn.type_vars): if isinstance(t, TypeVarTupleType): info.special_alias.tvar_tuple_index = i if info.declared_metaclass: info.declared_metaclass.accept(self.type_fixer) if info.metaclass_type: info.metaclass_type.accept(self.type_fixer) if info.self_type: info.self_type.accept(self.type_fixer) if info.alt_promote: info.alt_promote.accept(self.type_fixer) instance = Instance(info, []) # Hack: We may also need to add a backwards promotion (from int to native int), # since it might not be serialized. if instance not in info.alt_promote.type._promote: info.alt_promote.type._promote.append(instance) if info._mro_refs: info.mro = [ lookup_fully_qualified_typeinfo( self.modules, name, allow_missing=self.allow_missing ) for name in info._mro_refs ] info._mro_refs = None finally: self.current_info = save_info # NOTE: This method *definitely* isn't part of the NodeVisitor API. def visit_symbol_table(self, symtab: SymbolTable, table_fullname: str) -> None: # Copy the items because we may mutate symtab. for key in list(symtab): value = symtab[key] cross_ref = value.cross_ref if cross_ref is not None: # Fix up cross-reference. value.cross_ref = None if cross_ref in self.modules: value.node = self.modules[cross_ref] else: stnode = lookup_fully_qualified( cross_ref, self.modules, raise_on_missing=not self.allow_missing ) if stnode is not None: if stnode is value: # The node seems to refer to itself, which can mean that # the target is a deleted submodule of the current module, # and thus lookup falls back to the symbol table of the parent # package. Here's how this may happen: # # pkg/__init__.py: # from pkg import sub # # Now if pkg.sub is deleted, the pkg.sub symbol table entry # appears to refer to itself. Replace the entry with a # placeholder to avoid a crash. We can't delete the entry, # as it would stop dependency propagation. value.node = Var(key + "@deleted") else: assert stnode.node is not None, (table_fullname + "." + key, cross_ref) value.node = stnode.node elif not self.allow_missing: assert False, f"Could not find cross-ref {cross_ref}" else: # We have a missing crossref in allow missing mode, need to put something value.node = missing_info(self.modules) else: if isinstance(value.node, TypeInfo): # TypeInfo has no accept(). TODO: Add it? self.visit_type_info(value.node) elif value.node is not None: value.node.accept(self) else: assert False, f"Unexpected empty node {key!r}: {value}" def visit_func_def(self, func: FuncDef) -> None: if self.current_info is not None: func.info = self.current_info if func.type is not None: func.type.accept(self.type_fixer) if isinstance(func.type, CallableType): func.type.definition = func def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None: if self.current_info is not None: o.info = self.current_info if o.type: o.type.accept(self.type_fixer) for item in o.items: item.accept(self) if o.impl: o.impl.accept(self) if isinstance(o.type, Overloaded): # For error messages we link the original definition for each item. for typ, item in zip(o.type.items, o.items): typ.definition = item def visit_decorator(self, d: Decorator) -> None: if self.current_info is not None: d.var.info = self.current_info if d.func: d.func.accept(self) if d.var: d.var.accept(self) for node in d.decorators: node.accept(self) typ = d.var.type if isinstance(typ, ProperType) and isinstance(typ, CallableType): typ.definition = d.func def visit_class_def(self, c: ClassDef) -> None: for v in c.type_vars: v.accept(self.type_fixer) def visit_type_var_expr(self, tv: TypeVarExpr) -> None: for value in tv.values: value.accept(self.type_fixer) tv.upper_bound.accept(self.type_fixer) tv.default.accept(self.type_fixer) def visit_paramspec_expr(self, p: ParamSpecExpr) -> None: p.upper_bound.accept(self.type_fixer) p.default.accept(self.type_fixer) def visit_type_var_tuple_expr(self, tv: TypeVarTupleExpr) -> None: tv.upper_bound.accept(self.type_fixer) tv.tuple_fallback.accept(self.type_fixer) tv.default.accept(self.type_fixer) def visit_var(self, v: Var) -> None: if self.current_info is not None: v.info = self.current_info if v.type is not None: v.type.accept(self.type_fixer) if v.setter_type is not None: v.setter_type.accept(self.type_fixer) def visit_type_alias(self, a: TypeAlias) -> None: a.target.accept(self.type_fixer) for v in a.alias_tvars: v.accept(self.type_fixer)
NodeFixer
python
python__mypy
mypy/stubutil.py
{ "start": 16098, "end": 21871 }
class ____: """Record necessary imports during stub generation.""" def __init__(self) -> None: # module_for['foo'] has the module name where 'foo' was imported from, or None if # 'foo' is a module imported directly; # direct_imports['foo'] is the module path used when the name 'foo' was added to the # namespace. # reverse_alias['foo'] is the name that 'foo' had originally when imported with an # alias; examples # 'from pkg import mod' ==> module_for['mod'] == 'pkg' # 'from pkg import mod as m' ==> module_for['m'] == 'pkg' # ==> reverse_alias['m'] == 'mod' # 'import pkg.mod as m' ==> module_for['m'] == None # ==> reverse_alias['m'] == 'pkg.mod' # 'import pkg.mod' ==> module_for['pkg'] == None # ==> module_for['pkg.mod'] == None # ==> direct_imports['pkg'] == 'pkg.mod' # ==> direct_imports['pkg.mod'] == 'pkg.mod' self.module_for: dict[str, str | None] = {} self.direct_imports: dict[str, str] = {} self.reverse_alias: dict[str, str] = {} # required_names is the set of names that are actually used in a type annotation self.required_names: set[str] = set() # Names that should be reexported if they come from another module self.reexports: set[str] = set() def add_import_from( self, module: str, names: list[tuple[str, str | None]], require: bool = False ) -> None: for name, alias in names: if alias: # 'from {module} import {name} as {alias}' self.module_for[alias] = module self.reverse_alias[alias] = name else: # 'from {module} import {name}' self.module_for[name] = module self.reverse_alias.pop(name, None) if require: self.require_name(alias or name) self.direct_imports.pop(alias or name, None) def add_import(self, module: str, alias: str | None = None, require: bool = False) -> None: if alias: # 'import {module} as {alias}' assert "." not in alias # invalid syntax self.module_for[alias] = None self.reverse_alias[alias] = module if require: self.required_names.add(alias) else: # 'import {module}' name = module if require: self.required_names.add(name) # add module and its parent packages while name: self.module_for[name] = None self.direct_imports[name] = module self.reverse_alias.pop(name, None) name = name.rpartition(".")[0] def require_name(self, name: str) -> None: while name not in self.direct_imports and "." in name: name = name.rsplit(".", 1)[0] self.required_names.add(name) def reexport(self, name: str) -> None: """Mark a given non qualified name as needed in __all__. This means that in case it comes from a module, it should be imported with an alias even if the alias is the same as the name. """ self.require_name(name) self.reexports.add(name) def import_lines(self) -> list[str]: """The list of required import lines (as strings with python code). In order for a module be included in this output, an identifier must be both 'required' via require_name() and 'imported' via add_import_from() or add_import() """ result = [] # To summarize multiple names imported from a same module, we collect those # in the `module_map` dictionary, mapping a module path to the list of names that should # be imported from it. the names can also be alias in the form 'original as alias' module_map: Mapping[str, list[str]] = defaultdict(list) for name in sorted( self.required_names, key=lambda n: (self.reverse_alias[n], n) if n in self.reverse_alias else (n, ""), ): # If we haven't seen this name in an import statement, ignore it if name not in self.module_for: continue m = self.module_for[name] if m is not None: # This name was found in a from ... import ... # Collect the name in the module_map if name in self.reverse_alias: name = f"{self.reverse_alias[name]} as {name}" elif name in self.reexports: name = f"{name} as {name}" module_map[m].append(name) else: # This name was found in an import ... # We can already generate the import line if name in self.reverse_alias: source = self.reverse_alias[name] result.append(f"import {source} as {name}\n") elif name in self.reexports: assert "." not in name # Because reexports only has nonqualified names result.append(f"import {name} as {name}\n") else: result.append(f"import {name}\n") # Now generate all the from ... import ... lines collected in module_map for module, names in sorted(module_map.items()): result.append(f"from {module} import {', '.join(sorted(names))}\n") return result @mypyc_attr(allow_interpreted_subclasses=True)
ImportTracker
python
matplotlib__matplotlib
lib/matplotlib/transforms.py
{ "start": 7788, "end": 23215 }
class ____(TransformNode): """ The base class of all bounding boxes. This class is immutable; `Bbox` is a mutable subclass. The canonical representation is as two points, with no restrictions on their ordering. Convenience properties are provided to get the left, bottom, right and top edges and width and height, but these are not stored explicitly. """ is_affine = True if DEBUG: @staticmethod def _check(points): if isinstance(points, np.ma.MaskedArray): _api.warn_external("Bbox bounds are a masked array.") points = np.asarray(points) if any((points[1, :] - points[0, :]) == 0): _api.warn_external("Singular Bbox.") def frozen(self): return Bbox(self.get_points().copy()) frozen.__doc__ = TransformNode.__doc__ def __array__(self, *args, **kwargs): return self.get_points() @property def x0(self): """ The first of the pair of *x* coordinates that define the bounding box. This is not guaranteed to be less than :attr:`x1` (for that, use :attr:`~BboxBase.xmin`). """ return self.get_points()[0, 0] @property def y0(self): """ The first of the pair of *y* coordinates that define the bounding box. This is not guaranteed to be less than :attr:`y1` (for that, use :attr:`~BboxBase.ymin`). """ return self.get_points()[0, 1] @property def x1(self): """ The second of the pair of *x* coordinates that define the bounding box. This is not guaranteed to be greater than :attr:`x0` (for that, use :attr:`~BboxBase.xmax`). """ return self.get_points()[1, 0] @property def y1(self): """ The second of the pair of *y* coordinates that define the bounding box. This is not guaranteed to be greater than :attr:`y0` (for that, use :attr:`~BboxBase.ymax`). """ return self.get_points()[1, 1] @property def p0(self): """ The first pair of (*x*, *y*) coordinates that define the bounding box. This is not guaranteed to be the bottom-left corner (for that, use :attr:`~BboxBase.min`). """ return self.get_points()[0] @property def p1(self): """ The second pair of (*x*, *y*) coordinates that define the bounding box. This is not guaranteed to be the top-right corner (for that, use :attr:`~BboxBase.max`). """ return self.get_points()[1] @property def xmin(self): """The left edge of the bounding box.""" return np.min(self.get_points()[:, 0]) @property def ymin(self): """The bottom edge of the bounding box.""" return np.min(self.get_points()[:, 1]) @property def xmax(self): """The right edge of the bounding box.""" return np.max(self.get_points()[:, 0]) @property def ymax(self): """The top edge of the bounding box.""" return np.max(self.get_points()[:, 1]) @property def min(self): """The bottom-left corner of the bounding box.""" return np.min(self.get_points(), axis=0) @property def max(self): """The top-right corner of the bounding box.""" return np.max(self.get_points(), axis=0) @property def intervalx(self): """ The pair of *x* coordinates that define the bounding box. This is not guaranteed to be sorted from left to right. """ return self.get_points()[:, 0] @property def intervaly(self): """ The pair of *y* coordinates that define the bounding box. This is not guaranteed to be sorted from bottom to top. """ return self.get_points()[:, 1] @property def width(self): """The (signed) width of the bounding box.""" points = self.get_points() return points[1, 0] - points[0, 0] @property def height(self): """The (signed) height of the bounding box.""" points = self.get_points() return points[1, 1] - points[0, 1] @property def size(self): """The (signed) width and height of the bounding box.""" points = self.get_points() return points[1] - points[0] @property def bounds(self): """ Return (:attr:`x0`, :attr:`y0`, :attr:`~BboxBase.width`, :attr:`~BboxBase.height`). """ (x0, y0), (x1, y1) = self.get_points() return (x0, y0, x1 - x0, y1 - y0) @property def extents(self): """Return (:attr:`x0`, :attr:`y0`, :attr:`x1`, :attr:`y1`).""" return self.get_points().flatten() # flatten returns a copy. def get_points(self): raise NotImplementedError def _is_finite(self): """ Return whether the bounding box is finite and not degenerate to a single point. We count the box as finite if neither width nor height are infinite and at least one direction is non-zero; i.e. a point is not finite, but a horizontal or vertical line is. .. versionadded:: 3.11 Notes ----- We keep this private for now because concise naming is hard and because we are not sure how universal the concept is. It is currently used only for filtering bboxes to be included in tightbbox calculation, but I'm unsure whether single points should be included there as well. """ width = self.width height = self.height return (width > 0 or height > 0) and width < np.inf and height < np.inf def containsx(self, x): """ Return whether *x* is in the closed (:attr:`x0`, :attr:`x1`) interval. """ x0, x1 = self.intervalx return x0 <= x <= x1 or x0 >= x >= x1 def containsy(self, y): """ Return whether *y* is in the closed (:attr:`y0`, :attr:`y1`) interval. """ y0, y1 = self.intervaly return y0 <= y <= y1 or y0 >= y >= y1 def contains(self, x, y): """ Return whether ``(x, y)`` is in the bounding box or on its edge. """ return self.containsx(x) and self.containsy(y) def overlaps(self, other): """ Return whether this bounding box overlaps with the other bounding box. Parameters ---------- other : `.BboxBase` """ ax1, ay1, ax2, ay2 = self.extents bx1, by1, bx2, by2 = other.extents if ax2 < ax1: ax2, ax1 = ax1, ax2 if ay2 < ay1: ay2, ay1 = ay1, ay2 if bx2 < bx1: bx2, bx1 = bx1, bx2 if by2 < by1: by2, by1 = by1, by2 return ax1 <= bx2 and bx1 <= ax2 and ay1 <= by2 and by1 <= ay2 def fully_containsx(self, x): """ Return whether *x* is in the open (:attr:`x0`, :attr:`x1`) interval. """ x0, x1 = self.intervalx return x0 < x < x1 or x0 > x > x1 def fully_containsy(self, y): """ Return whether *y* is in the open (:attr:`y0`, :attr:`y1`) interval. """ y0, y1 = self.intervaly return y0 < y < y1 or y0 > y > y1 def fully_contains(self, x, y): """ Return whether ``x, y`` is in the bounding box, but not on its edge. """ return self.fully_containsx(x) and self.fully_containsy(y) def fully_overlaps(self, other): """ Return whether this bounding box overlaps with the other bounding box, not including the edges. Parameters ---------- other : `.BboxBase` """ ax1, ay1, ax2, ay2 = self.extents bx1, by1, bx2, by2 = other.extents if ax2 < ax1: ax2, ax1 = ax1, ax2 if ay2 < ay1: ay2, ay1 = ay1, ay2 if bx2 < bx1: bx2, bx1 = bx1, bx2 if by2 < by1: by2, by1 = by1, by2 return ax1 < bx2 and bx1 < ax2 and ay1 < by2 and by1 < ay2 def transformed(self, transform): """ Construct a `Bbox` by statically transforming this one by *transform*. """ pts = self.get_points() ll, ul, lr = transform.transform(np.array( [pts[0], [pts[0, 0], pts[1, 1]], [pts[1, 0], pts[0, 1]]])) return Bbox([ll, [lr[0], ul[1]]]) coefs = {'C': (0.5, 0.5), 'SW': (0, 0), 'S': (0.5, 0), 'SE': (1.0, 0), 'E': (1.0, 0.5), 'NE': (1.0, 1.0), 'N': (0.5, 1.0), 'NW': (0, 1.0), 'W': (0, 0.5)} def anchored(self, c, container): """ Return a copy of the `Bbox` anchored to *c* within *container*. Parameters ---------- c : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} Either an (*x*, *y*) pair of relative coordinates (0 is left or bottom, 1 is right or top), 'C' (center), or a cardinal direction ('SW', southwest, is bottom left, etc.). container : `Bbox` The box within which the `Bbox` is positioned. See Also -------- .Axes.set_anchor """ l, b, w, h = container.bounds L, B, W, H = self.bounds cx, cy = self.coefs[c] if isinstance(c, str) else c return Bbox(self._points + [(l + cx * (w - W)) - L, (b + cy * (h - H)) - B]) def shrunk(self, mx, my): """ Return a copy of the `Bbox`, shrunk by the factor *mx* in the *x* direction and the factor *my* in the *y* direction. The lower left corner of the box remains unchanged. Normally *mx* and *my* will be less than 1, but this is not enforced. """ w, h = self.size return Bbox([self._points[0], self._points[0] + [mx * w, my * h]]) def shrunk_to_aspect(self, box_aspect, container=None, fig_aspect=1.0): """ Return a copy of the `Bbox`, shrunk so that it is as large as it can be while having the desired aspect ratio, *box_aspect*. If the box coordinates are relative (i.e. fractions of a larger box such as a figure) then the physical aspect ratio of that figure is specified with *fig_aspect*, so that *box_aspect* can also be given as a ratio of the absolute dimensions, not the relative dimensions. """ if box_aspect <= 0 or fig_aspect <= 0: raise ValueError("'box_aspect' and 'fig_aspect' must be positive") if container is None: container = self w, h = container.size H = w * box_aspect / fig_aspect if H <= h: W = w else: W = h * fig_aspect / box_aspect H = h return Bbox([self._points[0], self._points[0] + (W, H)]) def splitx(self, *args): """ Return a list of new `Bbox` objects formed by splitting the original one with vertical lines at fractional positions given by *args*. """ xf = [0, *args, 1] x0, y0, x1, y1 = self.extents w = x1 - x0 return [Bbox([[x0 + xf0 * w, y0], [x0 + xf1 * w, y1]]) for xf0, xf1 in itertools.pairwise(xf)] def splity(self, *args): """ Return a list of new `Bbox` objects formed by splitting the original one with horizontal lines at fractional positions given by *args*. """ yf = [0, *args, 1] x0, y0, x1, y1 = self.extents h = y1 - y0 return [Bbox([[x0, y0 + yf0 * h], [x1, y0 + yf1 * h]]) for yf0, yf1 in itertools.pairwise(yf)] def count_contains(self, vertices): """ Count the number of vertices contained in the `Bbox`. Any vertices with a non-finite x or y value are ignored. Parameters ---------- vertices : (N, 2) array """ if len(vertices) == 0: return 0 vertices = np.asarray(vertices) with np.errstate(invalid='ignore'): return (((self.min < vertices) & (vertices < self.max)).all(axis=1).sum()) def count_overlaps(self, bboxes): """ Count the number of bounding boxes that overlap this one. Parameters ---------- bboxes : sequence of `.BboxBase` """ return count_bboxes_overlapping_bbox( self, np.atleast_3d([np.array(x) for x in bboxes])) def expanded(self, sw, sh): """ Construct a `Bbox` by expanding this one around its center by the factors *sw* and *sh*. """ width = self.width height = self.height deltaw = (sw * width - width) / 2.0 deltah = (sh * height - height) / 2.0 a = np.array([[-deltaw, -deltah], [deltaw, deltah]]) return Bbox(self._points + a) def padded(self, w_pad, h_pad=None): """ Construct a `Bbox` by padding this one on all four sides. Parameters ---------- w_pad : float Width pad h_pad : float, optional Height pad. Defaults to *w_pad*. """ points = self.get_points() if h_pad is None: h_pad = w_pad return Bbox(points + [[-w_pad, -h_pad], [w_pad, h_pad]]) def translated(self, tx, ty): """Construct a `Bbox` by translating this one by *tx* and *ty*.""" return Bbox(self._points + (tx, ty)) def corners(self): """ Return the corners of this rectangle as an array of points. Specifically, this returns the array ``[[x0, y0], [x0, y1], [x1, y0], [x1, y1]]``. """ (x0, y0), (x1, y1) = self.get_points() return np.array([[x0, y0], [x0, y1], [x1, y0], [x1, y1]]) def rotated(self, radians): """ Return the axes-aligned bounding box that bounds the result of rotating this `Bbox` by an angle of *radians*. """ corners = self.corners() corners_rotated = Affine2D().rotate(radians).transform(corners) bbox = Bbox.unit() bbox.update_from_data_xy(corners_rotated, ignore=True) return bbox @staticmethod def union(bboxes): """Return a `Bbox` that contains all of the given *bboxes*.""" if not len(bboxes): raise ValueError("'bboxes' cannot be empty") x0 = np.min([bbox.xmin for bbox in bboxes]) x1 = np.max([bbox.xmax for bbox in bboxes]) y0 = np.min([bbox.ymin for bbox in bboxes]) y1 = np.max([bbox.ymax for bbox in bboxes]) return Bbox([[x0, y0], [x1, y1]]) @staticmethod def intersection(bbox1, bbox2): """ Return the intersection of *bbox1* and *bbox2* if they intersect, or None if they don't. """ x0 = np.maximum(bbox1.xmin, bbox2.xmin) x1 = np.minimum(bbox1.xmax, bbox2.xmax) y0 = np.maximum(bbox1.ymin, bbox2.ymin) y1 = np.minimum(bbox1.ymax, bbox2.ymax) return Bbox([[x0, y0], [x1, y1]]) if x0 <= x1 and y0 <= y1 else None _default_minpos = np.array([np.inf, np.inf])
BboxBase
python
tiangolo__fastapi
tests/test_pydantic_v1_v2_multifile/modelsv2.py
{ "start": 277, "end": 321 }
class ____(BaseModel): name2: str
ItemInList
python
doocs__leetcode
solution/1100-1199/1167.Minimum Cost to Connect Sticks/Solution.py
{ "start": 0, "end": 264 }
class ____: def connectSticks(self, sticks: List[int]) -> int: heapify(sticks) ans = 0 while len(sticks) > 1: z = heappop(sticks) + heappop(sticks) ans += z heappush(sticks, z) return ans
Solution
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/control_flow/cond_v2_test.py
{ "start": 50241, "end": 53674 }
class ____(test.TestCase): def testContainer(self): """Set containers outside & inside of cond_v2. Make sure the containers are set correctly for both variable creation (tested by variables.Variable) and for stateful ops (tested by FIFOQueue) """ self.skipTest("b/113048653") with ops.Graph().as_default() as g: with self.session(graph=g): v0 = variables.Variable([0]) q0 = data_flow_ops.FIFOQueue(1, dtypes.float32) def container(node): return node.op.get_attr("container") self.assertEqual(compat.as_bytes(""), container(v0)) self.assertEqual(compat.as_bytes(""), container(q0.queue_ref)) def true_fn(): # When this branch is created in cond below, # the container should begin with 'l1' v1 = variables.Variable([1]) q1 = data_flow_ops.FIFOQueue(1, dtypes.float32) with ops.container("l2t"): v2 = variables.Variable([2]) q2 = data_flow_ops.FIFOQueue(1, dtypes.float32) v3 = variables.Variable([1]) q3 = data_flow_ops.FIFOQueue(1, dtypes.float32) self.assertEqual(compat.as_bytes("l1"), container(v1)) self.assertEqual(compat.as_bytes("l1"), container(q1.queue_ref)) self.assertEqual(compat.as_bytes("l2t"), container(v2)) self.assertEqual(compat.as_bytes("l2t"), container(q2.queue_ref)) self.assertEqual(compat.as_bytes("l1"), container(v3)) self.assertEqual(compat.as_bytes("l1"), container(q3.queue_ref)) return constant_op.constant(2.0) def false_fn(): # When this branch is created in cond below, # the container should begin with 'l1' v1 = variables.Variable([1]) q1 = data_flow_ops.FIFOQueue(1, dtypes.float32) with ops.container("l2f"): v2 = variables.Variable([2]) q2 = data_flow_ops.FIFOQueue(1, dtypes.float32) v3 = variables.Variable([1]) q3 = data_flow_ops.FIFOQueue(1, dtypes.float32) self.assertEqual(compat.as_bytes("l1"), container(v1)) self.assertEqual(compat.as_bytes("l1"), container(q1.queue_ref)) self.assertEqual(compat.as_bytes("l2f"), container(v2)) self.assertEqual(compat.as_bytes("l2f"), container(q2.queue_ref)) self.assertEqual(compat.as_bytes("l1"), container(v3)) self.assertEqual(compat.as_bytes("l1"), container(q3.queue_ref)) return constant_op.constant(6.0) with ops.container("l1"): cnd_true = cond_v2.cond_v2( constant_op.constant(True), true_fn, false_fn) self.assertEqual(self.evaluate(cnd_true), 2) cnd_false = cond_v2.cond_v2( constant_op.constant(False), true_fn, false_fn) self.assertEqual(self.evaluate(cnd_false), 6) v4 = variables.Variable([3]) q4 = data_flow_ops.FIFOQueue(1, dtypes.float32) v5 = variables.Variable([4]) q5 = data_flow_ops.FIFOQueue(1, dtypes.float32) self.assertEqual(compat.as_bytes("l1"), container(v4)) self.assertEqual(compat.as_bytes("l1"), container(q4.queue_ref)) self.assertEqual(compat.as_bytes(""), container(v5)) self.assertEqual(compat.as_bytes(""), container(q5.queue_ref)) @test_util.disable_tfrt("b/171412104: This test requires distributed support.")
CondV2ContainerTest
python
getsentry__sentry
tests/sentry/tasks/test_groupowner.py
{ "start": 908, "end": 20473 }
class ____(TestCase): def setUp(self) -> None: self.project = self.create_project() self.repo = Repository.objects.create( organization_id=self.organization.id, name=self.organization.id ) self.release = self.create_release(project=self.project, version="v1337") self.group = self.create_group( project=self.project, message="Kaboom!", first_release=self.release ) GroupRelease.objects.create( group_id=self.group.id, release_id=self.release.id, project_id=self.project.id ) self.event = self.store_event( data={ "message": "Kaboom!", "platform": "python", "timestamp": before_now(seconds=10).isoformat(), "stacktrace": { "frames": [ { "function": "handle_set_commits", "abs_path": "/usr/src/sentry/src/sentry/tasks.py", "module": "sentry.tasks", "in_app": True, "lineno": 30, "filename": "sentry/tasks.py", }, { "function": "set_commits", "abs_path": "/usr/src/sentry/src/sentry/models/release.py", "module": "sentry.models.release", "in_app": True, "lineno": 39, "filename": "sentry/models/release.py", }, ] }, "tags": {"sentry:release": self.release.version}, "fingerprint": ["put-me-in-the-control-group"], }, project_id=self.project.id, ) assert self.event.group is not None GroupRelease.objects.create( group_id=self.event.group.id, project_id=self.project.id, release_id=self.release.id ) def set_release_commits(self, author_email): self.commitSha = "a" * 40 self.release.set_commits( [ { "id": self.commitSha, "repository": self.repo.name, "author_email": author_email, "author_name": "Bob", "message": "i fixed a bug", "patch_set": [{"path": "src/sentry/models/release.py", "type": "M"}], } ] ) def test_simple(self) -> None: self.set_release_commits(self.user.email) assert not GroupOwner.objects.filter(group=self.event.group).exists() event_frames = get_frame_paths(self.event) process_suspect_commits( event_id=self.event.event_id, event_platform=self.event.platform, event_frames=event_frames, group_id=self.event.group_id, project_id=self.event.project_id, ) assert GroupOwner.objects.get( group=self.event.group, project=self.event.project, organization=self.event.project.organization, type=GroupOwnerType.SUSPECT_COMMIT.value, ) def test_user_deletion_cascade(self) -> None: other_user = self.create_user() group = self.create_group() other_group = self.create_group() GroupOwner.objects.create( group=group, project=group.project, organization=group.project.organization, type=0, user_id=self.user.id, ) GroupOwner.objects.create( group=other_group, project=other_group.project, organization=other_group.project.organization, type=0, user_id=other_user.id, ) assert GroupOwner.objects.count() == 2 with assume_test_silo_mode(SiloMode.CONTROL), outbox_runner(): self.user.delete() assert GroupOwner.objects.count() == 2 with TaskRunner(): schedule_hybrid_cloud_foreign_key_jobs() assert GroupOwner.objects.count() == 1 def test_delete_old_entries(self) -> None: # As new events come in associated with new owners, we should delete old ones. self.set_release_commits(self.user.email) event_frames = get_frame_paths(self.event) process_suspect_commits( event_id=self.event.event_id, event_platform=self.event.platform, event_frames=event_frames, group_id=self.event.group_id, project_id=self.event.project_id, ) process_suspect_commits( event_id=self.event.event_id, event_platform=self.event.platform, event_frames=event_frames, group_id=self.event.group_id, project_id=self.event.project_id, ) process_suspect_commits( event_id=self.event.event_id, event_platform=self.event.platform, event_frames=event_frames, group_id=self.event.group_id, project_id=self.event.project_id, ) assert GroupOwner.objects.filter(group=self.event.group).count() == 1 assert GroupOwner.objects.filter(group=self.event.group, user_id=self.user.id).exists() event_2 = self.store_event( data={ "message": "BANG!", "platform": "python", "timestamp": before_now(seconds=1).isoformat(), "stacktrace": { "frames": [ { "function": "process_suspect_commits", "abs_path": "/usr/src/sentry/src/sentry/tasks/groupowner.py", "module": "sentry.tasks.groupowner", "in_app": True, "lineno": 48, "filename": "sentry/tasks/groupowner.py", }, ] }, "tags": {"sentry:release": self.release.version}, "fingerprint": ["put-me-in-the-control-group"], }, project_id=self.project.id, ) event_3 = self.store_event( data={ "message": "BOP!", "platform": "python", "timestamp": before_now(seconds=1).isoformat(), "stacktrace": { "frames": [ { "function": "process_suspect_commits", "abs_path": "/usr/src/sentry/src/sentry/tasks/groupowner.py", "module": "sentry.tasks.groupowner", "in_app": True, "lineno": 48, "filename": "sentry/tasks/groupowner.py", }, ] }, "tags": {"sentry:release": self.release.version}, "fingerprint": ["put-me-in-the-control-group"], }, project_id=self.project.id, ) self.user_2 = self.create_user("another@user.com", is_superuser=True) self.create_member(teams=[self.team], user=self.user_2, organization=self.organization) self.user_3 = self.create_user("user_3@sentry.io", is_superuser=True) self.create_member(teams=[self.team], user=self.user_3, organization=self.organization) self.release.set_commits( [ { "id": "a" * 40, "repository": self.repo.name, "author_email": self.user_2.email, "author_name": "joe", "message": "i fixed another bug", "patch_set": [{"path": "src/sentry/tasks/groupowner.py", "type": "M"}], } ] ) assert event_2.group == self.event.group assert event_3.group == self.event.group self.set_release_commits(self.user_2.email) event_2_frames = get_frame_paths(event_2) process_suspect_commits( event_id=event_2.event_id, event_platform=event_2.platform, event_frames=event_2_frames, group_id=event_2.group_id, project_id=event_2.project_id, ) assert GroupOwner.objects.filter(group=self.event.group).count() == 2 assert GroupOwner.objects.filter(group=self.event.group, user_id=self.user.id).exists() assert GroupOwner.objects.filter(group=event_2.group, user_id=self.user_2.id).exists() self.set_release_commits(self.user_3.email) event_3_frames = get_frame_paths(event_3) process_suspect_commits( event_id=event_3.event_id, event_platform=event_3.platform, event_frames=event_3_frames, group_id=event_3.group_id, project_id=event_3.project_id, ) assert GroupOwner.objects.filter(group=self.event.group).count() == 2 assert GroupOwner.objects.filter(group=self.event.group, user_id=self.user.id).exists() assert GroupOwner.objects.filter(group=event_2.group, user_id=self.user_2.id).exists() assert not GroupOwner.objects.filter(group=event_2.group, user_id=self.user_3.id).exists() go = GroupOwner.objects.get(group=event_2.group, user_id=self.user_2.id) go.date_added = timezone.now() - PREFERRED_GROUP_OWNER_AGE * 2 go.save() self.set_release_commits(self.user_3.email) process_suspect_commits( event_id=event_3.event_id, event_platform=event_3.platform, event_frames=event_3_frames, group_id=event_3.group_id, project_id=event_3.project_id, ) # Won't be processed because the cache is present and this group has owners assert GroupOwner.objects.filter(group=self.event.group).count() == 2 assert GroupOwner.objects.filter(group=self.event.group, user_id=self.user.id).exists() assert not GroupOwner.objects.filter(group=event_2.group, user_id=self.user_2.id).exists() assert GroupOwner.objects.filter(group=event_2.group, user_id=self.user_3.id).exists() def test_update_existing_entries(self) -> None: # As new events come in associated with existing owners, we should update the date_added of that owner. self.set_release_commits(self.user.email) suspect_commit = Commit.objects.get(key=self.commitSha) event_frames = get_frame_paths(self.event) process_suspect_commits( event_id=self.event.event_id, event_platform=self.event.platform, event_frames=event_frames, group_id=self.event.group_id, project_id=self.event.project_id, ) go = GroupOwner.objects.get( group=self.event.group, project=self.event.project, organization=self.event.project.organization, type=GroupOwnerType.SUSPECT_COMMIT.value, ) date_added_before_update = go.date_added assert "commitId" in go.context assert go.context["commitId"] == suspect_commit.id assert go.context["suspectCommitStrategy"] == SuspectCommitStrategy.RELEASE_BASED process_suspect_commits( event_id=self.event.event_id, event_platform=self.event.platform, event_frames=event_frames, group_id=self.event.group_id, project_id=self.event.project_id, ) go.refresh_from_db() assert go.date_added > date_added_before_update assert "commitId" in go.context assert go.context["commitId"] == suspect_commit.id assert go.context["suspectCommitStrategy"] == SuspectCommitStrategy.RELEASE_BASED assert GroupOwner.objects.filter(group=self.event.group).count() == 1 assert GroupOwner.objects.get( group=self.event.group, project=self.event.project, organization=self.event.project.organization, type=GroupOwnerType.SUSPECT_COMMIT.value, ) def test_no_release_or_commit(self) -> None: event_with_no_release = self.store_event( data={ "message": "BOOM!", "platform": "python", "timestamp": before_now(seconds=1).isoformat(), "stacktrace": { "frames": [ { "function": "process_suspect_commits", "abs_path": "/usr/src/sentry/src/sentry/tasks/groupowner.py", "module": "sentry.tasks.groupowner", "in_app": True, "lineno": 48, "filename": "sentry/tasks/groupowner.py", }, ] }, "fingerprint": ["i-have-no-release"], }, project_id=self.project.id, ) process_suspect_commits( event_with_no_release.event_id, event_with_no_release.platform, get_frame_paths(event_with_no_release), event_with_no_release.group_id, event_with_no_release.project_id, ) assert GroupOwner.objects.filter(group=event_with_no_release.group).count() == 0 @patch("sentry.tasks.groupowner.get_event_file_committers") def test_keep_highest_score(self, patched_committers: MagicMock) -> None: self.user2 = self.create_user(email="user2@sentry.io") self.user3 = self.create_user(email="user3@sentry.io") mock_commit1 = MagicMock(id=1) mock_commit2 = MagicMock(id=2) mock_commit3 = MagicMock(id=3) patched_committers.return_value = [ { "commits": [(mock_commit1, 3)], "author": { "username": self.user.email, "lastLogin": None, "isSuperuser": True, "isManaged": False, "experiments": {}, "lastActive": timezone.now(), "isStaff": True, "id": self.user.id, "isActive": True, "has2fa": False, "name": self.user.email, "avatarUrl": "https://secure.gravatar.com/avatar/46d229b033af06a191ff2267bca9ae56?s=32&d=mm", "dateJoined": timezone.now(), "emails": [ {"is _verified": True, "id": self.user.id, "email": self.user.email} ], "avatar": {"avatarUuid": None, "avatarType": "letter_avatar"}, "hasPasswordAuth": True, "email": self.user.email, }, }, { "commits": [(mock_commit2, 1)], "author": { "username": self.user2.email, "lastLogin": None, "isSuperuser": True, "isManaged": False, "experiments": {}, "lastActive": timezone.now(), "isStaff": True, "id": self.user2.id, "isActive": True, "has2fa": False, "name": self.user2.email, "avatarUrl": "https://secure.gravatar.com/avatar/46d229b033af06a191ff2267bca9ae56?s=32&d=mm", "dateJoined": timezone.now(), "emails": [ {"is_verified": True, "id": self.user2.id, "email": self.user2.email} ], "avatar": {"avatarUuid": None, "avatarType": "letter_avatar"}, "hasPasswordAuth": True, "email": self.user2.email, }, }, { "commits": [(mock_commit3, 2)], "author": { "username": self.user3.email, "lastLogin": None, "isSuperuser": True, "isManaged": False, "experiments": {}, "lastActive": timezone.now(), "isStaff": True, "id": self.user3.id, "isActive": True, "has2fa": False, "name": self.user3.email, "avatarUrl": "https://secure.gravatar.com/avatar/46d229b033af06a191ff2267bca9ae56?s=32&d=mm", "dateJoined": timezone.now(), "emails": [ {"is_verified": True, "id": self.user3.id, "email": self.user3.email} ], "avatar": {"avatarUuid": None, "avatarType": "letter_avatar"}, "hasPasswordAuth": True, "email": self.user3.email, }, }, ] event_frames = get_frame_paths(self.event) process_suspect_commits( event_id=self.event.event_id, event_platform=self.event.platform, event_frames=event_frames, group_id=self.event.group_id, project_id=self.event.project_id, ) # Doesn't use self.user2 due to low score. user1_owner = GroupOwner.objects.get(user_id=self.user.id) user3_owner = GroupOwner.objects.get(user_id=self.user3.id) assert not GroupOwner.objects.filter(user_id=self.user2.id).exists() assert user1_owner.context["commitId"] == 1 assert user3_owner.context["commitId"] == 3 @patch("sentry.tasks.groupowner.get_event_file_committers") def test_low_suspect_committer_score(self, patched_committers: MagicMock) -> None: self.user = self.create_user() mock_commit = MagicMock(id=1) patched_committers.return_value = [ { # score < MIN_COMMIT_SCORE "commits": [(mock_commit, 1)], "author": { "id": self.user.id, }, }, ] event_frames = get_frame_paths(self.event) process_suspect_commits( event_id=self.event.event_id, event_platform=self.event.platform, event_frames=event_frames, group_id=self.event.group_id, project_id=self.event.project_id, ) assert not GroupOwner.objects.filter(user_id=self.user.id).exists() def test_owners_count(self) -> None: self.set_release_commits(self.user.email) self.user = self.create_user() event_frames = get_frame_paths(self.event) process_suspect_commits( event_id=self.event.event_id, event_platform=self.event.platform, event_frames=event_frames, group_id=self.event.group_id, project_id=self.event.project_id, ) owners = GroupOwner.objects.filter( group_id=self.event.group_id, project=self.event.project, organization_id=self.event.project.organization_id, type=GroupOwnerType.SUSPECT_COMMIT.value, ) assert owners.count() == 1
TestGroupOwners
python
huggingface__transformers
tests/models/perceiver/test_modeling_perceiver.py
{ "start": 38856, "end": 45599 }
class ____(unittest.TestCase): @slow def test_inference_masked_lm(self): tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver") model = PerceiverForMaskedLM.from_pretrained("deepmind/language-perceiver") model.to(torch_device) # prepare inputs text = "This is an incomplete sentence where some words are missing." encoding = tokenizer(text, padding="max_length", return_tensors="pt") # mask " missing.". encoding.input_ids[0, 52:61] = tokenizer.mask_token_id inputs, input_mask = encoding.input_ids.to(torch_device), encoding.attention_mask.to(torch_device) # forward pass with torch.no_grad(): outputs = model(inputs=inputs, attention_mask=input_mask) logits = outputs.logits # verify logits expected_shape = torch.Size((1, tokenizer.model_max_length, len(tokenizer))) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor( [[-10.8609, -10.7651, -10.9187], [-12.1689, -11.9389, -12.1479], [-12.1518, -11.9707, -12.2073]], device=torch_device, ) torch.testing.assert_close(logits[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4) expected_greedy_predictions = [38, 115, 111, 121, 121, 111, 116, 109, 52] masked_tokens_predictions = logits[0, 52:61].argmax(dim=-1).tolist() self.assertListEqual(expected_greedy_predictions, masked_tokens_predictions) @slow def test_inference_image_classification(self): image_processor = PerceiverImageProcessor() model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned") model.to(torch_device) # prepare inputs image = prepare_img() inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device) input_mask = None # forward pass with torch.no_grad(): outputs = model(inputs=inputs, attention_mask=input_mask) logits = outputs.logits # verify logits expected_shape = torch.Size((1, model.config.num_labels)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor([-1.1652, -0.1992, -0.7520], device=torch_device) atol = 1e-3 if IS_ROCM_SYSTEM else 1e-4 torch.testing.assert_close(logits[0, :3], expected_slice, rtol=atol, atol=atol) @slow def test_inference_image_classification_fourier(self): image_processor = PerceiverImageProcessor() model = PerceiverForImageClassificationFourier.from_pretrained("deepmind/vision-perceiver-fourier") model.to(torch_device) # prepare inputs image = prepare_img() inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device) input_mask = None # forward pass with torch.no_grad(): outputs = model(inputs=inputs, attention_mask=input_mask) logits = outputs.logits # verify logits expected_shape = torch.Size((1, model.config.num_labels)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor([-1.1295, -0.2832, 0.3226], device=torch_device) torch.testing.assert_close(logits[0, :3], expected_slice, rtol=1e-4, atol=1e-4) @slow def test_inference_image_classification_conv(self): image_processor = PerceiverImageProcessor() model = PerceiverForImageClassificationConvProcessing.from_pretrained("deepmind/vision-perceiver-conv") model.to(torch_device) # prepare inputs image = prepare_img() inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device) input_mask = None # forward pass with torch.no_grad(): outputs = model(inputs=inputs, attention_mask=input_mask) logits = outputs.logits # verify logits expected_shape = torch.Size((1, model.config.num_labels)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor([-1.1186, 0.0554, 0.0897], device=torch_device) torch.testing.assert_close(logits[0, :3], expected_slice, rtol=1e-4, atol=1e-4) @slow def test_inference_optical_flow(self): model = PerceiverForOpticalFlow.from_pretrained("deepmind/optical-flow-perceiver") model.to(torch_device) # prepare inputs image1, image2 = prepare_optical_flow_images() img1 = normalize(np.array(image1)) img2 = normalize(np.array(image1)) # stack images img1 = torch.tensor(np.moveaxis(img1, -1, 0)) img2 = torch.tensor(np.moveaxis(img2, -1, 0)) images = torch.stack([img1, img2], dim=0) # extract 3x3 patches patch_size = model.config.train_size inputs = images[..., : patch_size[0], : patch_size[1]].unsqueeze(0) batch_size, _, C, H, W = inputs.shape patches = extract_image_patches(inputs.view(batch_size * 2, C, H, W), kernel=3) _, C, H, W = patches.shape patches = patches.view(batch_size, -1, C, H, W).float() # forward pass with torch.no_grad(): outputs = model(inputs=patches.to(torch_device)) logits = outputs.logits # verify logits expected_shape = torch.Size((1, 368, 496, 2)) self.assertEqual(logits.shape, expected_shape) expected_slice = torch.tensor( [ [[0.0025, -0.0050], [0.0025, -0.0049], [0.0025, -0.0048]], [[0.0026, -0.0049], [0.0026, -0.0048], [0.0026, -0.0047]], [[0.0026, -0.0049], [0.0026, -0.0048], [0.0026, -0.0046]], ], device=torch_device, ) torch.testing.assert_close(logits[0, :3, :3, :3], expected_slice, rtol=1e-4, atol=1e-4) @slow def test_inference_interpolate_pos_encoding(self): image_processor = PerceiverImageProcessor(size={"height": 384, "width": 384}) model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned") model.to(torch_device) # prepare inputs image = prepare_img() inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device) input_mask = None # forward pass with torch.no_grad(): outputs = model(inputs=inputs, attention_mask=input_mask, interpolate_pos_encoding=True) logits = outputs.logits # verify logits expected_shape = torch.Size((1, model.config.num_labels)) self.assertEqual(logits.shape, expected_shape)
PerceiverModelIntegrationTest
python
PyCQA__pylint
tests/functional/d/dotted_ancestor.py
{ "start": 57, "end": 241 }
class ____(non_init_parent_called.AAAA): # [too-few-public-methods] """test dotted name in ancestors""" def __init__(self): non_init_parent_called.AAAA.__init__(self)
Aaaa
python
vyperlang__vyper
vyper/venom/analysis/available_expression.py
{ "start": 4496, "end": 7112 }
class ____: """ Class that holds available expression and provides API for handling them """ exprs: immutables.Map[_Expression, list[IRInstruction]] def __init__(self): self.exprs = immutables.Map() def __eq__(self, other) -> bool: if not isinstance(other, _AvailableExpressions): return False return self.exprs == other.exprs def __repr__(self) -> str: res = "available expr\n" for key, val in self.exprs.items(): res += f"\t{key}: {val}\n" return res def add(self, expr: _Expression, src_inst: IRInstruction): with self.exprs.mutate() as mt: if expr not in mt: mt[expr] = [] else: mt[expr] = mt[expr].copy() mt[expr].append(src_inst) self.exprs = mt.finish() def remove_effect(self, effect: Effects, ignore_msize): if effect == effects.EMPTY: return to_remove = set() for expr in self.exprs.keys(): op_effect = _get_effects(expr.opcode, ignore_msize) if op_effect & effect != effects.EMPTY: to_remove.add(expr) with self.exprs.mutate() as mt: for expr in to_remove: del mt[expr] self.exprs = mt.finish() def get_source_instruction(self, expr: _Expression) -> IRInstruction | None: """ Get source instruction of expression if currently available """ tmp = self.exprs.get(expr) if tmp is not None: # arbitrarily choose the first instruction return tmp[0] return None def copy(self) -> _AvailableExpressions: res = _AvailableExpressions() res.exprs = self.exprs return res @staticmethod def lattice_meet(lattices: list[_AvailableExpressions]): if len(lattices) == 0: return _AvailableExpressions() res = lattices[0].copy() # compute intersection for item in lattices[1:]: tmp = res res = _AvailableExpressions() mt = res.exprs.mutate() for expr, insts in item.exprs.items(): if expr not in tmp.exprs: continue new_insts = [] for i in tmp.exprs[expr]: if i in insts: new_insts.append(i) if len(new_insts) == 0: continue mt[expr] = new_insts res.exprs = mt.finish() return res
_AvailableExpressions
python
arrow-py__arrow
arrow/locales.py
{ "start": 44648, "end": 47428 }
class ____(Locale): past = "vor {0}" future = "in {0}" and_word = "und" timeframes: ClassVar[Dict[TimeFrameLiteral, str]] = { "now": "gerade eben", "second": "einer Sekunde", "seconds": "{0} Sekunden", "minute": "einer Minute", "minutes": "{0} Minuten", "hour": "einer Stunde", "hours": "{0} Stunden", "day": "einem Tag", "days": "{0} Tagen", "week": "einer Woche", "weeks": "{0} Wochen", "month": "einem Monat", "months": "{0} Monaten", "year": "einem Jahr", "years": "{0} Jahren", } timeframes_only_distance = timeframes.copy() timeframes_only_distance["second"] = "eine Sekunde" timeframes_only_distance["minute"] = "eine Minute" timeframes_only_distance["hour"] = "eine Stunde" timeframes_only_distance["day"] = "ein Tag" timeframes_only_distance["days"] = "{0} Tage" timeframes_only_distance["week"] = "eine Woche" timeframes_only_distance["month"] = "ein Monat" timeframes_only_distance["months"] = "{0} Monate" timeframes_only_distance["year"] = "ein Jahr" timeframes_only_distance["years"] = "{0} Jahre" month_names = [ "", "Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember", ] month_abbreviations = [ "", "Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez", ] day_names = [ "", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag", ] day_abbreviations = ["", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"] def _ordinal_number(self, n: int) -> str: return f"{n}." def describe( self, timeframe: TimeFrameLiteral, delta: Union[int, float] = 0, only_distance: bool = False, ) -> str: """Describes a delta within a timeframe in plain language. :param timeframe: a string representing a timeframe. :param delta: a quantity representing a delta in a timeframe. :param only_distance: return only distance eg: "11 seconds" without "in" or "ago" keywords """ if not only_distance: return super().describe(timeframe, delta, only_distance) # German uses a different case without 'in' or 'ago' humanized: str = self.timeframes_only_distance[timeframe].format( trunc(abs(delta)) ) return humanized
GermanBaseLocale
python
skorch-dev__skorch
skorch/tests/test_utils.py
{ "start": 14318, "end": 17671 }
class ____: @pytest.fixture def data_from_dataset(self): from skorch.utils import data_from_dataset return data_from_dataset @pytest.fixture def data(self): X = np.arange(8).reshape(4, 2) y = np.array([1, 3, 0, 2]) return X, y @pytest.fixture def tensors(self, data): X, y = data return torch.from_numpy(X), torch.from_numpy(y) @pytest.fixture def skorch_ds(self, data): from skorch.dataset import Dataset return Dataset(*data) @pytest.fixture def subset(self, skorch_ds): from torch.utils.data.dataset import Subset return Subset(skorch_ds, [1, 3]) @pytest.fixture def subset_subset(self, subset): from torch.utils.data.dataset import Subset return Subset(subset, [0]) # pylint: disable=missing-docstring @pytest.fixture def other_ds(self, data): class MyDataset: """Non-compliant dataset""" def __init__(self, data): self.data = data def __getitem__(self, idx): return self.data[0][idx], self.data[1][idx] def __len__(self): return len(self.data[0]) return MyDataset(data) def test_with_skorch_ds(self, data_from_dataset, data, skorch_ds): X, y = data_from_dataset(skorch_ds) assert (X == data[0]).all() assert (y == data[1]).all() def test_with_subset(self, data_from_dataset, data, subset): X, y = data_from_dataset(subset) assert (X == data[0][[1, 3]]).all() assert (y == data[1][[1, 3]]).all() def test_with_subset_subset(self, data_from_dataset, data, subset_subset): X, y = data_from_dataset(subset_subset) assert (X == data[0][1]).all() assert (y == data[1][1]).all() def test_with_other_ds(self, data_from_dataset, other_ds): with pytest.raises(AttributeError): data_from_dataset(other_ds) def test_with_dict_data(self, data_from_dataset, data, subset): subset.dataset.X = {'X': subset.dataset.X} X, y = data_from_dataset(subset) assert (X['X'] == data[0][[1, 3]]).all() assert (y == data[1][[1, 3]]).all() def test_subset_with_y_none(self, data_from_dataset, data, subset): subset.dataset.y = None X, y = data_from_dataset(subset) assert (X == data[0][[1, 3]]).all() assert y is None def test_with_tensordataset_2_vals(self, data_from_dataset, tensors): dataset = torch.utils.data.dataset.TensorDataset(*tensors) X, y = data_from_dataset(dataset) assert (X == tensors[0]).all() assert (y == tensors[1]).all() def test_with_tensordataset_1_val_raises(self, data_from_dataset, tensors): dataset = torch.utils.data.dataset.TensorDataset(tensors[0]) msg = "Could not access X and y from dataset." with pytest.raises(AttributeError, match=msg): data_from_dataset(dataset) def test_with_tensordataset_3_vals_raises(self, data_from_dataset, tensors): dataset = torch.utils.data.dataset.TensorDataset(*tensors, tensors[0]) msg = "Could not access X and y from dataset." with pytest.raises(AttributeError, match=msg): data_from_dataset(dataset)
TestDataFromDataset
python
zarr-developers__zarr-python
src/zarr/storage/_obstore.py
{ "start": 9899, "end": 10455 }
class ____(TypedDict): """Offset or suffix range requests. These requests cannot be concurrent on the Rust side, and each need their own call to `obstore.get_async`, passing in the `range` parameter. """ original_request_index: int """The positional index in the original key_ranges input""" path: str """The path to request from.""" range: OffsetRange | None # Note: suffix requests are handled separately because some object stores (Azure) # don't support them """The range request type."""
_OtherRequest
python
python-poetry__poetry
src/poetry/console/commands/cache/list.py
{ "start": 130, "end": 634 }
class ____(Command): name = "cache list" description = "List Poetry's caches." def handle(self) -> int: config = Config.create() if config.repository_cache_directory.exists(): caches = sorted(config.repository_cache_directory.iterdir()) if caches: for cache in caches: self.line(f"<info>{cache.name}</>") return 0 self.line_error("<warning>No caches found</>") return 0
CacheListCommand
python
getsentry__sentry
src/sentry/issues/endpoints/project_ownership.py
{ "start": 1244, "end": 7013 }
class ____(serializers.Serializer): raw = serializers.CharField( required=False, allow_blank=True, help_text="Raw input for ownership configuration. See the [Ownership Rules Documentation](/product/issues/ownership-rules/) to learn more.", ) fallthrough = serializers.BooleanField( required=False, help_text="A boolean determining who to assign ownership to when an ownership rule has no match. If set to `True`, all project members are made owners. Otherwise, no owners are set.", ) autoAssignment = serializers.CharField( required=False, allow_blank=False, help_text="""Auto-assignment settings. The available options are: - Auto Assign to Issue Owner - Auto Assign to Suspect Commits - Turn off Auto-Assignment""", ) codeownersAutoSync = serializers.BooleanField( required=False, default=True, help_text="Set to `True` to sync issue owners with CODEOWNERS updates in a release.", ) @staticmethod def _validate_no_codeowners(rules): """ codeowner matcher types cannot be added via ProjectOwnership, only through codeowner specific serializers """ for rule in rules: if rule["matcher"]["type"] == CODEOWNERS: raise serializers.ValidationError( {"raw": "Codeowner type paths can only be added by importing CODEOWNER files"} ) def get_max_length(self): organization = self.context["ownership"].project.organization if features.has("organizations:ownership-size-limit-xlarge", organization): return XLARGE_MAX_RAW_LENGTH if features.has("organizations:ownership-size-limit-large", organization): return LARGE_MAX_RAW_LENGTH return DEFAULT_MAX_RAW_LENGTH def validate_autoAssignment(self, value): if value not in [ "Auto Assign to Suspect Commits", "Auto Assign to Issue Owner", "Turn off Auto-Assignment", ]: raise serializers.ValidationError({"autoAssignment": "Invalid selection."}) return value def validate(self, attrs): if "raw" not in attrs: return attrs # We want to limit `raw` to a reasonable length, so that people don't end up with values # that are several megabytes large. To not break this functionality for existing customers # we temporarily allow rows that already exceed this limit to still be updated. existing_raw = self.context["ownership"].raw or "" max_length = self.get_max_length() if len(attrs["raw"]) > max_length and len(existing_raw) <= max_length: raise serializers.ValidationError( {"raw": f"Raw needs to be <= {max_length} characters in length"} ) schema = create_schema_from_issue_owners( project_id=self.context["ownership"].project_id, issue_owners=attrs["raw"], ) if schema: self._validate_no_codeowners(schema["rules"]) attrs["schema"] = schema return attrs def save(self, **kwargs: Any) -> ProjectOwnership: ownership = self.context["ownership"] changed = False if "raw" in self.validated_data: raw = self.validated_data["raw"] if not raw.strip(): raw = None if ownership.raw != raw: ownership.raw = raw ownership.schema = self.validated_data.get("schema") changed = True if "fallthrough" in self.validated_data: fallthrough = self.validated_data["fallthrough"] if ownership.fallthrough != fallthrough: ownership.fallthrough = fallthrough changed = True if "codeownersAutoSync" in self.validated_data: codeowners_auto_sync = self.validated_data["codeownersAutoSync"] if ownership.codeowners_auto_sync != codeowners_auto_sync: ownership.codeowners_auto_sync = codeowners_auto_sync changed = True changed = self.__modify_auto_assignment(ownership) or changed if changed: now = timezone.now() if ownership.date_created is None: ownership.date_created = now ownership.last_updated = now ownership.save() return ownership def __modify_auto_assignment(self, ownership): auto_assignment = self.validated_data.get("autoAssignment") if auto_assignment is None: return False new_values = {} if auto_assignment == "Auto Assign to Suspect Commits": new_values["auto_assignment"] = True new_values["suspect_committer_auto_assignment"] = True if auto_assignment == "Auto Assign to Issue Owner": new_values["auto_assignment"] = True new_values["suspect_committer_auto_assignment"] = False if auto_assignment == "Turn off Auto-Assignment": new_values["auto_assignment"] = False new_values["suspect_committer_auto_assignment"] = False changed = ( ownership.auto_assignment != new_values["auto_assignment"] or ownership.suspect_committer_auto_assignment != new_values["suspect_committer_auto_assignment"] ) if changed: ownership.auto_assignment = new_values["auto_assignment"] ownership.suspect_committer_auto_assignment = new_values[ "suspect_committer_auto_assignment" ] return changed @region_silo_endpoint @extend_schema(tags=["Projects"])
ProjectOwnershipRequestSerializer
python
mlflow__mlflow
mlflow/telemetry/events.py
{ "start": 3387, "end": 3662 }
class ____(Event): name: str = "get_logged_model" @classmethod def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None: return { "imports": [pkg for pkg in MODULES_TO_CHECK_IMPORT if pkg in sys.modules], }
GetLoggedModelEvent
python
walkccc__LeetCode
solutions/632. Smallest Range Covering Elements from K Lists/632.py
{ "start": 0, "end": 675 }
class ____: def smallestRange(self, nums: list[list[int]]) -> list[int]: minHeap = [(row[0], i, 0) for i, row in enumerate(nums)] heapq.heapify(minHeap) maxRange = max(row[0] for row in nums) minRange = heapq.nsmallest(1, minHeap)[0][0] ans = [minRange, maxRange] while len(minHeap) == len(nums): num, r, c = heapq.heappop(minHeap) if c + 1 < len(nums[r]): heapq.heappush(minHeap, (nums[r][c + 1], r, c + 1)) maxRange = max(maxRange, nums[r][c + 1]) minRange = heapq.nsmallest(1, minHeap)[0][0] if maxRange - minRange < ans[1] - ans[0]: ans[0], ans[1] = minRange, maxRange return ans
Solution
python
mitmproxy__pdoc
test/testdata/misc.py
{ "start": 1064, "end": 1349 }
class ____: """ You can either do >>> ClassmethodLink.bar() 42 or ```python ClassmethodLink.bar() ``` neither will be linked. """ @classmethod def bar(cls): return 42 # Testing generic bases T = TypeVar("T")
ClassmethodLink
python
ansible__ansible
test/lib/ansible_test/_internal/python_requirements.py
{ "start": 1382, "end": 1683 }
class ____: """Base class for pip commands.""" def serialize(self) -> tuple[str, dict[str, t.Any]]: """Return a serialized representation of this command.""" name = type(self).__name__[3:].lower() return name, self.__dict__ @dataclasses.dataclass(frozen=True)
PipCommand
python
airbytehq__airbyte
airbyte-integrations/connectors/source-recharge/source_recharge/streams.py
{ "start": 832, "end": 5555 }
class ____(HttpStream, ABC): """ Orders Stream: https://developer.rechargepayments.com/v1-shopify?python#list-orders Notes: Using `2021-01` the: `email`, `first_name`, `last_name` columns are not available, because these are not present in `2021-11` as DEPRECATED fields. """ primary_key: str = "id" url_base: str = "https://api.rechargeapps.com/" cursor_field: str = "updated_at" page_size: int = 250 page_num: int = 1 period_in_days: int = 30 # Slice data request for 1 month raise_on_http_errors: bool = True state_checkpoint_interval: int = 250 # registering the default schema transformation transformer: TypeTransformer = TypeTransformer(TransformConfig.DefaultSchemaNormalization) def __init__(self, config: Mapping[str, Any], **kwargs) -> None: super().__init__(**kwargs) self._start_date = config["start_date"] self.api_version = ApiVersion.DEPRECATED if config.get("use_orders_deprecated_api") else ApiVersion.MODERN @property def data_path(self) -> str: return self.name def request_headers(self, **kwargs) -> Mapping[str, Any]: return {"x-recharge-version": self.api_version.value} def path(self, **kwargs) -> str: return self.name def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]: next_page_token = None if self.api_version == ApiVersion.MODERN: cursor = response.json().get("next_cursor") if cursor: next_page_token = {"cursor": cursor} else: stream_data = self.get_stream_data(response.json()) if len(stream_data) == self.page_size: self.page_num += 1 next_page_token = {"page": self.page_num} return next_page_token def _update_params_with_min_max_date_range( self, params: MutableMapping[str, Any], stream_slice: Optional[Mapping[str, Any]] = None, ) -> MutableMapping[str, Any]: params.update( { "sort_by": "updated_at-asc", "updated_at_min": (stream_slice or {}).get("start_date"), "updated_at_max": (stream_slice or {}).get("end_date"), } ) return params def request_params( self, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None, **kwargs ) -> MutableMapping[str, Any]: params = {"limit": self.page_size} if self.api_version == ApiVersion.MODERN: # if a cursor value is passed, only limit can be passed with it! if next_page_token: params.update(next_page_token) else: params = self._update_params_with_min_max_date_range(params, stream_slice) return params else: params = self._update_params_with_min_max_date_range(params, stream_slice) if next_page_token: params.update(next_page_token) return params def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]: response_data = response.json() stream_data = self.get_stream_data(response_data) yield from stream_data def get_stream_data(self, response_data: Any) -> List[dict]: if self.data_path: return response_data.get(self.data_path, []) else: return [response_data] def get_error_handler(self) -> ErrorHandler: return RechargeErrorHandler(logger=self.logger) def stream_slices(self, stream_state: Mapping[str, Any] = None, **kwargs) -> Iterable[Optional[Mapping[str, Any]]]: start_date_value = (stream_state or {}).get(self.cursor_field, self._start_date) if self.cursor_field else self._start_date now = pendulum.now() # dates are inclusive, so we add 1 second so that time periods do not overlap start_date = pendulum.parse(start_date_value).add(seconds=1) while start_date <= now: end_date = start_date.add(days=self.period_in_days) yield {"start_date": start_date.strftime("%Y-%m-%d %H:%M:%S"), "end_date": end_date.strftime("%Y-%m-%d %H:%M:%S")} start_date = end_date.add(seconds=1) def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]: latest_benchmark = latest_record[self.cursor_field] if current_stream_state.get(self.cursor_field): return {self.cursor_field: max(latest_benchmark, current_stream_state[self.cursor_field])} return {self.cursor_field: latest_benchmark}
Orders
python
apache__airflow
kubernetes-tests/tests/kubernetes_tests/test_base.py
{ "start": 1900, "end": 16684 }
class ____: """Base class for K8S Tests.""" host: str = KUBERNETES_HOST_PORT + "/api/v2" temp_dir = Path(tempfile.gettempdir()) # Refers to global temp directory, in linux it usual "/tmp" session: requests.Session test_id: str use_fab_auth_manager: bool = os.environ.get("USE_FAB_AUTH_MANAGER", "true").lower() == "true" password: str = "admin" # Default password for FAB auth manager @pytest.fixture(autouse=True) def base_tests_setup(self, request): # Replacement for unittests.TestCase.id() self.test_id = f"{request.node.cls.__name__}_{request.node.name}" # Ensure the api-server deployment is healthy at kubernetes level before calling the any API self.ensure_resource_health("airflow-api-server") if not self.use_fab_auth_manager: # If we are not using FAB auth manager, we need to retrieve the admin password from # the airflow-api-server pod self.password = self.get_generated_admin_password(namespace="airflow") print("Using retrieved admin password for API calls from generated file") else: print("Using default 'admin' password for API calls") try: self.session = self._get_session_with_retries() self._ensure_airflow_api_server_is_healthy() yield finally: if hasattr(self, "session") and self.session is not None: self.session.close() def _describe_resources(self, namespace: str): kubeconfig_basename = os.path.basename(os.environ.get("KUBECONFIG", "default")) output_file_path = ( self.temp_dir / f"k8s_test_resources_{namespace}_{kubeconfig_basename}_{self.test_id}.txt" ) print(f"Dumping resources to {output_file_path}") ci = os.environ.get("CI") if ci and ci.lower() == "true": print("The resource dump will be uploaded as artifact of the CI job") with open(output_file_path, "w") as output_file: print("=" * 80, file=output_file) print(f"Describe resources for namespace {namespace}", file=output_file) print(f"Datetime: {datetime.now(tz=timezone.utc)}", file=output_file) print("=" * 80, file=output_file) print("Describing pods", file=output_file) print("-" * 80, file=output_file) subprocess.call( ["kubectl", "describe", "pod", "--namespace", namespace], stdout=output_file, stderr=subprocess.STDOUT, ) print("=" * 80, file=output_file) print("Describing persistent volumes", file=output_file) print("-" * 80, file=output_file) subprocess.call( ["kubectl", "describe", "pv", "--namespace", namespace], stdout=output_file, stderr=subprocess.STDOUT, ) print("=" * 80, file=output_file) print("Describing persistent volume claims", file=output_file) print("-" * 80, file=output_file) subprocess.call( ["kubectl", "describe", "pvc", "--namespace", namespace], stdout=output_file, stderr=subprocess.STDOUT, ) print("=" * 80, file=output_file) @staticmethod def _num_pods_in_namespace(namespace: str): air_pod = check_output(["kubectl", "get", "pods", "-n", namespace]).decode() air_pod = air_pod.splitlines() names = [re.compile(r"\s+").split(x)[0] for x in air_pod if "airflow" in x] return len(names) @staticmethod def _delete_airflow_pod(name=""): suffix = f"-{name}" if name else "" air_pod = check_output(["kubectl", "get", "pods"]).decode() air_pod = air_pod.splitlines() names = [re.compile(r"\s+").split(x)[0] for x in air_pod if "airflow" + suffix in x] if names: check_call(["kubectl", "delete", "pod", names[0]]) def _get_session_with_retries(self): class JWTRefreshAdapter(HTTPAdapter): def __init__(self, **kwargs): super().__init__(**kwargs) def send(self, request, **kwargs): response = super().send(request, **kwargs) if response.status_code in (401, 403): # Refresh token and update the Authorization header with retry logic. attempts = 0 jwt_token = None while attempts < 5: try: jwt_token = generate_access_token( "admin", BaseK8STest.password, KUBERNETES_HOST_PORT ) break except Exception: attempts += 1 time.sleep(1) if jwt_token is None: raise Exception("Failed to refresh JWT token after 5 attempts") request.headers["Authorization"] = f"Bearer {jwt_token}" response = super().send(request, **kwargs) return response jwt_token = generate_access_token("admin", self.password, KUBERNETES_HOST_PORT) session = requests.Session() session.headers.update({"Authorization": f"Bearer {jwt_token}"}) retries = Retry( total=5, backoff_factor=10, status_forcelist=[404], allowed_methods=Retry.DEFAULT_ALLOWED_METHODS | frozenset(["PATCH", "POST"]), ) adapter = JWTRefreshAdapter(max_retries=retries) session.mount("http://", adapter) session.mount("https://", adapter) return session def _ensure_airflow_api_server_is_healthy(self): max_tries = 10 timeout_seconds = 5 for i in range(max_tries): try: response = self.session.get( f"http://{KUBERNETES_HOST_PORT}/monitor/health", timeout=1, ) if response.status_code == 200: print("Airflow api server is healthy!") return except Exception as e: print(f"Exception when checking if api server is healthy {e}") if i < max_tries - 1: print(f"Waiting {timeout_seconds} s and retrying.") time.sleep(timeout_seconds) raise Exception( f"Giving up. The api server of Airflow was not healthy after {max_tries} tries " f"with {timeout_seconds} s delays" ) def monitor_task(self, host, dag_run_id, dag_id, task_id, expected_final_state, timeout): tries = 0 state = "" max_tries = max(int(timeout / 5), 1) # Wait some time for the operator to complete while tries < max_tries: time.sleep(5) # Check task state try: get_string = f"http://{host}/dags/{dag_id}/dagRuns/{dag_run_id}/taskInstances/{task_id}" print(f"Calling [monitor_task]#1 {get_string}") result = self.session.get(get_string) if result.status_code == 404: check_call(["echo", "api returned 404."]) tries += 1 continue assert result.status_code == 200, "Could not get the status" result_json = result.json() print(f"Received [monitor_task]#2: {result_json}") state = result_json["state"] print(f"Attempt {tries}: Current state of operator is {state}") if state == expected_final_state: break if state in {"failed", "upstream_failed", "removed"}: # If the TI is in failed state (and that's not the state we want) there's no point # continuing to poll, it won't change break self._describe_resources(namespace="airflow") self._describe_resources(namespace="default") tries += 1 except requests.exceptions.ConnectionError as e: check_call(["echo", f"api call failed. trying again. error {e}"]) if state != expected_final_state: print(f"The expected state is wrong {state} != {expected_final_state} (expected)!") assert state == expected_final_state @staticmethod def ensure_resource_health( resource_name: str, namespace: str = "airflow", resource_type: Literal["deployment", "statefulset"] = "deployment", ): """Watch the resource until it is healthy. Args: resource_name (str): Name of the resource to check. resource_type (str): Type of the resource (e.g., deployment, statefulset). namespace (str): Kubernetes namespace where the resource is located. """ rollout_status = check_output( ["kubectl", "rollout", "status", f"{resource_type}/{resource_name}", "-n", namespace, "--watch"], ).decode() if resource_type == "deployment": assert "successfully rolled out" in rollout_status else: assert "roll out complete" in rollout_status def ensure_dag_expected_state(self, host, logical_date, dag_id, expected_final_state, timeout): tries = 0 state = "" max_tries = max(int(timeout / 5), 1) # Wait some time for the operator to complete while tries < max_tries: time.sleep(5) get_string = f"http://{host}/dags/{dag_id}/dagRuns" print(f"Calling {get_string}") # Get all dagruns result = self.session.get(get_string) assert result.status_code == 200, "Could not get the status" result_json = result.json() print(f"Received: {result}") state = None for dag_run in result_json["dag_runs"]: if dag_run["logical_date"] == logical_date: state = dag_run["state"] check_call(["echo", f"Attempt {tries}: Current state of dag is {state}"]) print(f"Attempt {tries}: Current state of dag is {state}") if state == expected_final_state: break if state == "failed": # If the DR is in failed state there's no point continuing to poll! break self._describe_resources("airflow") self._describe_resources("default") tries += 1 assert state == expected_final_state # Maybe check if we can retrieve the logs, but then we need to extend the API def start_dag(self, dag_id, host): patch_string = f"http://{host}/dags/{dag_id}" print(f"Calling [start_dag]#1 {patch_string}") max_attempts = 10 result = {} # This loop retries until the DAG parser finishes with max_attempts and the DAG is available for execution. # Keep the try/catch block, as the session object has a default retry configuration. # If a MaxRetryError, RetryError is raised, it can be safely ignored, indicating that the DAG is not yet parsed. while max_attempts: try: result = self.session.patch(patch_string, json={"is_paused": False}) if result.status_code == 200: break except (MaxRetryError, RetryError): pass time.sleep(30) max_attempts -= 1 try: result_json = result.json() except ValueError: result_json = str(result) print(f"Received [start_dag]#1 {result_json}") assert result.status_code == 200, f"Could not enable DAG: {result_json}" post_string = f"http://{host}/dags/{dag_id}/dagRuns" print(f"Calling [start_dag]#2 {post_string}") logical_date = datetime.now(timezone.utc).isoformat() # Trigger a new dagrun result = self.session.post(post_string, json={"logical_date": logical_date}) try: result_json = result.json() except ValueError: result_json = str(result) print(f"Received [start_dag]#2 {result_json}") assert result.status_code == 200, f"Could not trigger a DAG-run: {result_json}" time.sleep(1) get_string = f"http://{host}/dags/{dag_id}/dagRuns" print(f"Calling [start_dag]#3 {get_string}") result = self.session.get(get_string) assert result.status_code == 200, f"Could not get DAGRuns: {result.json()}" result_json = result.json() print(f"Received: [start_dag]#3 {result_json}") return result_json def start_job_in_kubernetes(self, dag_id, host): result_json = self.start_dag(dag_id=dag_id, host=host) dag_runs = result_json["dag_runs"] assert len(dag_runs) > 0 logical_date = None dag_run_id = None for dag_run in dag_runs: if dag_run["dag_id"] == dag_id: logical_date = dag_run["logical_date"] run_after = dag_run["run_after"] dag_run_id = dag_run["dag_run_id"] break assert run_after is not None, f"No run_after can be found for the dag with {dag_id}" return dag_run_id, logical_date def get_generated_admin_password(self, namespace: str) -> str: api_sever_pod = ( check_output(["kubectl", "get", "pods", "--namespace", namespace]).decode().splitlines() ) names = [re.compile(r"\s+").split(x)[0] for x in api_sever_pod if "airflow-api-server" in x] if not names: self._describe_resources(namespace) raise ValueError("There should be exactly one airflow-api-server pod running.") airflow_api_server_pod_name = names[0] temp_generated_passwords_json_file_path = ( self.temp_dir / "simple_auth_manager_passwords.json.generated" ) check_call( [ "kubectl", "cp", "--container", "api-server", f"{namespace}/{airflow_api_server_pod_name}:simple_auth_manager_passwords.json.generated", temp_generated_passwords_json_file_path.as_posix(), ] ) users = json.loads(temp_generated_passwords_json_file_path.read_text()) if "admin" not in users: raise ValueError(f"There should be an admin user in the generated passwords file: {users}") return users["admin"]
BaseK8STest
python
huggingface__transformers
src/transformers/models/phi4_multimodal/modeling_phi4_multimodal.py
{ "start": 31785, "end": 32841 }
class ____(nn.Module): def __init__(self, config: Phi4MultimodalAudioConfig): super().__init__() self.feed_forward_in = Phi4MultimodalAudioMLP(config) self.self_attn = Phi4MultimodalAudioAttention(config) self.conv = Phi4MultimodalAudioConvModule(config) self.feed_forward_out = Phi4MultimodalAudioMLP(config) self.layer_norm_att = nn.LayerNorm(config.hidden_size) self.layer_norm = nn.LayerNorm(config.hidden_size) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, ): residual = hidden_states + 0.5 * self.feed_forward_in(hidden_states) hidden_states = self.layer_norm_att(residual) hidden_states = residual + self.self_attn(hidden_states, attention_mask) hidden_states = hidden_states + self.conv(hidden_states) hidden_states = hidden_states + 0.5 * self.feed_forward_out(hidden_states) out = self.layer_norm(hidden_states) return out
Phi4MultimodalAudioConformerEncoderLayer
python
PyCQA__pylint
tests/functional/i/invalid/invalid_name.py
{ "start": 2667, "end": 2961 }
class ____(FooBar): tearDown = FooBar.tearDown tearDownNotInAncestor = None # [invalid-name] from enum import Enum Color = Enum('Color', [('RED', 1), ('GREEN', 2), ('BLUE', 3)]) from typing import TypedDict MyExampleType = TypedDict("MyExampleType", {"some_field": str})
FooBarSubclass
python
tornadoweb__tornado
demos/blog/blog.py
{ "start": 5176, "end": 5463 }
class ____(BaseHandler): async def get(self): entries = await self.query( "SELECT * FROM entries ORDER BY published DESC LIMIT 10" ) self.set_header("Content-Type", "application/atom+xml") self.render("feed.xml", entries=entries)
FeedHandler
python
great-expectations__great_expectations
great_expectations/data_context/types/base.py
{ "start": 8641, "end": 11991 }
class ____(SerializableDictDot): def __init__( # noqa: C901, PLR0912, PLR0913 # FIXME CoP self, name: Optional[str] = None, class_name: Optional[str] = None, module_name: Optional[str] = None, bucket: Optional[str] = None, prefix: Optional[str] = None, delimiter: Optional[str] = None, max_keys: Optional[int] = None, schema_name: Optional[str] = None, batch_spec_passthrough: Optional[Dict[str, Any]] = None, batch_identifiers: Optional[List[str]] = None, partitioner_method: Optional[str] = None, partitioner_kwargs: Optional[Dict[str, str]] = None, sorters: Optional[dict] = None, sampling_method: Optional[str] = None, sampling_kwargs: Optional[Dict[str, str]] = None, reader_options: Optional[Dict[str, Any]] = None, **kwargs: Optional[dict], ) -> None: if name is not None: self.name = name self._class_name = class_name self._module_name = module_name if bucket is not None: self.bucket = bucket if prefix is not None: self.prefix = prefix if delimiter is not None: self.delimiter = delimiter if max_keys is not None: self.max_keys = max_keys if schema_name is not None: self.schema_name = schema_name if batch_spec_passthrough is not None: self.batch_spec_passthrough = batch_spec_passthrough if batch_identifiers is not None: self.batch_identifiers = batch_identifiers if partitioner_method is not None: self.partitioner_method = partitioner_method if partitioner_kwargs is not None: self.partitioner_kwargs = partitioner_kwargs if sorters is not None: self.sorters = sorters if sampling_method is not None: self.sampling_method = sampling_method if sampling_kwargs is not None: self.sampling_kwargs = sampling_kwargs if reader_options is not None: self.reader_options = reader_options for k, v in kwargs.items(): setattr(self, k, v) @property def class_name(self) -> Optional[str]: return self._class_name @property def module_name(self) -> Optional[str]: return self._module_name @override def to_json_dict(self) -> Dict[str, JSONValues]: """Returns a JSON-serializable dict representation of this AssetConfig. Returns: A JSON-serializable dict representation of this AssetConfig. """ # TODO: <Alex>2/4/2022</Alex> # This implementation of "SerializableDictDot.to_json_dict() occurs frequently and should ideally serve as the # noqa: E501 # FIXME CoP # reference implementation in the "SerializableDictDot" class itself. However, the circular import dependencies, # noqa: E501 # FIXME CoP # due to the location of the "great_expectations/types/__init__.py" and "great_expectations/core/util.py" modules # noqa: E501 # FIXME CoP # make this refactoring infeasible at the present time. dict_obj: dict = self.to_dict() serializeable_dict: dict = convert_to_json_serializable(data=dict_obj) return serializeable_dict
AssetConfig
python
run-llama__llama_index
llama-index-integrations/callbacks/llama-index-callbacks-openinference/llama_index/callbacks/openinference/base.py
{ "start": 1150, "end": 2669 }
class ____: """ Query data with column names following the OpenInference specification. """ id: str = field( default_factory=_generate_random_id, metadata={OPENINFERENCE_COLUMN_NAME: ":id.id:"}, ) timestamp: Optional[str] = field( default=None, metadata={OPENINFERENCE_COLUMN_NAME: ":timestamp.iso_8601:"} ) query_text: Optional[str] = field( default=None, metadata={OPENINFERENCE_COLUMN_NAME: ":feature.text:prompt"}, ) query_embedding: Optional[Embedding] = field( default=None, metadata={OPENINFERENCE_COLUMN_NAME: ":feature.[float].embedding:prompt"}, ) llm_prompt: Optional[str] = field( default=None, metadata={OPENINFERENCE_COLUMN_NAME: ":feature.text:llm_prompt"}, ) llm_messages: Optional[Tuple[str, str]] = field( default=None, metadata={OPENINFERENCE_COLUMN_NAME: ":feature.[str]:llm_messages"}, ) response_text: Optional[str] = field( default=None, metadata={OPENINFERENCE_COLUMN_NAME: ":prediction.text:response"} ) node_ids: List[str] = field( default_factory=list, metadata={ OPENINFERENCE_COLUMN_NAME: ":feature.[str].retrieved_document_ids:prompt" }, ) scores: List[float] = field( default_factory=list, metadata={ OPENINFERENCE_COLUMN_NAME: ( ":feature.[float].retrieved_document_scores:prompt" ) }, ) @dataclass
QueryData
python
pypa__installer
tests/test_sources.py
{ "start": 1978, "end": 12829 }
class ____: def test_rejects_not_okay_name(self, tmp_path): # Create an empty zipfile path = tmp_path / "not_a_valid_name.whl" with zipfile.ZipFile(str(path), "w"): pass with ( pytest.raises(ValueError, match=r"Not a valid wheel filename: .+"), WheelFile.open(str(path)), ): pass def test_provides_correct_dist_info_filenames(self, fancy_wheel): with WheelFile.open(fancy_wheel) as source: assert sorted(source.dist_info_filenames) == [ "METADATA", "RECORD", "WHEEL", "entry_points.txt", "top_level.txt", ] def test_correctly_reads_from_dist_info_files(self, fancy_wheel): files = {} with zipfile.ZipFile(fancy_wheel) as archive: for file in archive.namelist(): if ".dist-info" not in file: continue files[posixpath.basename(file)] = archive.read(file).decode("utf-8") got_files = {} with WheelFile.open(fancy_wheel) as source: for file in files: got_files[file] = source.read_dist_info(file) assert got_files == files def test_provides_correct_contents(self, fancy_wheel): # Know the contents of the wheel files = {} with zipfile.ZipFile(fancy_wheel) as archive: for file in archive.namelist(): if file[-1:] == "/": continue files[file] = archive.read(file) expected_record_lines = ( files["fancy-1.0.0.dist-info/RECORD"].decode("utf-8").splitlines() ) expected_records = list(parse_record_file(expected_record_lines)) # Check that the object's output is appropriate got_records = [] got_files = {} with WheelFile.open(fancy_wheel) as source: for record_elements, stream, is_executable in source.get_contents(): got_records.append(record_elements) got_files[record_elements[0]] = stream.read() assert not is_executable assert sorted(got_records) == sorted(expected_records) assert got_files == files def test_finds_dist_info(self, fancy_wheel): denorm = fancy_wheel.rename(fancy_wheel.parent / "Fancy-1.0.0-py3-none-any.whl") # Python 3.7: rename doesn't return the new name: denorm = fancy_wheel.parent / "Fancy-1.0.0-py3-none-any.whl" with WheelFile.open(denorm) as source: assert source.dist_info_filenames def test_requires_dist_info_name_match(self, fancy_wheel): misnamed = fancy_wheel.rename( fancy_wheel.parent / "misnamed-1.0.0-py3-none-any.whl" ) # Python 3.7: rename doesn't return the new name: misnamed = fancy_wheel.parent / "misnamed-1.0.0-py3-none-any.whl" with pytest.raises(InstallerError) as ctx, WheelFile.open(misnamed) as source: _ = source.dist_info_filenames error = ctx.value assert error.filename == str(misnamed) assert error.dist_info == "fancy-1.0.0.dist-info" assert "" in error.reason assert error.dist_info in str(error) def test_enforces_single_dist_info(self, fancy_wheel): with zipfile.ZipFile(fancy_wheel, "a") as archive: archive.writestr( "name-1.0.0.dist-info/random.txt", b"This is a random file.", ) with ( pytest.raises(InstallerError) as ctx, WheelFile.open(fancy_wheel) as source, ): _ = source.dist_info_filenames error = ctx.value assert error.filename == str(fancy_wheel) assert error.dist_info == str(["fancy-1.0.0.dist-info", "name-1.0.0.dist-info"]) assert "exactly one .dist-info" in error.reason assert error.dist_info in str(error) def test_rejects_no_record_on_validate(self, fancy_wheel): # Remove RECORD replace_file_in_zip( fancy_wheel, filename="fancy-1.0.0.dist-info/RECORD", content=None, ) with ( WheelFile.open(fancy_wheel) as source, pytest.raises( WheelFile.validation_error, match="Unable to retrieve `RECORD`" ), ): source.validate_record(validate_contents=False) def test_rejects_invalid_record_entry(self, fancy_wheel): with WheelFile.open(fancy_wheel) as source: record_file_contents = source.read_dist_info("RECORD") replace_file_in_zip( fancy_wheel, filename="fancy-1.0.0.dist-info/RECORD", content="\n".join( line.replace("sha256=", "") for line in record_file_contents ), ) with ( WheelFile.open(fancy_wheel) as source, pytest.raises( WheelFile.validation_error, match="Unable to retrieve `RECORD`", ), ): source.validate_record() def test_rejects_record_missing_file_on_validate(self, fancy_wheel): with WheelFile.open(fancy_wheel) as source: record_file_contents = source.read_dist_info("RECORD") # Remove the first two entries from the RECORD file new_record_file_contents = "\n".join(record_file_contents.split("\n")[2:]) replace_file_in_zip( fancy_wheel, filename="fancy-1.0.0.dist-info/RECORD", content=new_record_file_contents, ) with ( WheelFile.open(fancy_wheel) as source, pytest.raises(WheelFile.validation_error, match="not mentioned in RECORD"), ): source.validate_record(validate_contents=False) def test_rejects_record_missing_hash(self, fancy_wheel): with WheelFile.open(fancy_wheel) as source: record_file_contents = source.read_dist_info("RECORD") new_record_file_contents = "\n".join( line.split(",")[0] + ",," # file name with empty size and hash for line in record_file_contents.split("\n") ) replace_file_in_zip( fancy_wheel, filename="fancy-1.0.0.dist-info/RECORD", content=new_record_file_contents, ) with ( WheelFile.open(fancy_wheel) as source, pytest.raises( WheelFile.validation_error, match=r"hash / size of (.+) is not included in RECORD", ), ): source.validate_record(validate_contents=False) def test_accept_wheel_with_signature_file(self, fancy_wheel): with WheelFile.open(fancy_wheel) as source: record_file_contents = source.read_dist_info("RECORD") hash_b64_nopad = ( urlsafe_b64encode(sha256(record_file_contents.encode()).digest()) .decode("utf-8") .rstrip("=") ) jws_content = json.dumps({"hash": f"sha256={hash_b64_nopad}"}) with zipfile.ZipFile(fancy_wheel, "a") as archive: archive.writestr("fancy-1.0.0.dist-info/RECORD.jws", jws_content) with WheelFile.open(fancy_wheel) as source: source.validate_record() def test_reject_signature_file_in_record(self, fancy_wheel): with WheelFile.open(fancy_wheel) as source: record_file_contents = source.read_dist_info("RECORD") record_hash_nopad = ( urlsafe_b64encode(sha256(record_file_contents.encode()).digest()) .decode("utf-8") .rstrip("=") ) jws_content = json.dumps({"hash": f"sha256={record_hash_nopad}"}) with zipfile.ZipFile(fancy_wheel, "a") as archive: archive.writestr("fancy-1.0.0.dist-info/RECORD.jws", jws_content) # Add signature file to RECORD jws_content = jws_content.encode() jws_hash_nopad = ( urlsafe_b64encode(sha256(jws_content).digest()).decode("utf-8").rstrip("=") ) replace_file_in_zip( fancy_wheel, filename="fancy-1.0.0.dist-info/RECORD", content=record_file_contents.rstrip("\n") + f"\nfancy-1.0.0.dist-info/RECORD.jws,sha256={jws_hash_nopad},{len(jws_content)}\n", ) with ( WheelFile.open(fancy_wheel) as source, pytest.raises( WheelFile.validation_error, match=r"digital signature file (.+) is incorrectly contained in RECORD.", ), ): source.validate_record(validate_contents=False) def test_rejects_record_contain_self_hash(self, fancy_wheel): with WheelFile.open(fancy_wheel) as source: record_file_contents = source.read_dist_info("RECORD") new_record_file_lines = [] for line in record_file_contents.split("\n"): if not line: continue filename, hash_, size = line.split(",") if filename.split("/")[-1] == "RECORD": hash_ = "sha256=pREiHcl39jRySUXMCOrwmSsnOay8FB7fOJP5mZQ3D3A" size = str(len(record_file_contents)) new_record_file_lines.append(f"{filename},{hash_},{size}") replace_file_in_zip( fancy_wheel, filename="fancy-1.0.0.dist-info/RECORD", content="\n".join(new_record_file_lines), ) with ( WheelFile.open(fancy_wheel) as source, pytest.raises( WheelFile.validation_error, match=r"RECORD file incorrectly contains hash / size.", ), ): source.validate_record(validate_contents=False) def test_rejects_record_validation_failed(self, fancy_wheel): with WheelFile.open(fancy_wheel) as source: record_file_contents = source.read_dist_info("RECORD") new_record_file_lines = [] for line in record_file_contents.split("\n"): if not line: continue filename, hash_, size = line.split(",") if filename.split("/")[-1] != "RECORD": hash_ = "sha256=pREiHcl39jRySUXMCOrwmSsnOay8FB7fOJP5mZQ3D3A" new_record_file_lines.append(f"{filename},{hash_},{size}") replace_file_in_zip( fancy_wheel, filename="fancy-1.0.0.dist-info/RECORD", content="\n".join(new_record_file_lines), ) with ( WheelFile.open(fancy_wheel) as source, pytest.raises( WheelFile.validation_error, match=r"hash / size of (.+) didn't match RECORD", ), ): source.validate_record()
TestWheelFile
python
openai__openai-python
src/openai/types/responses/file_search_tool.py
{ "start": 1341, "end": 1870 }
class ____(BaseModel): type: Literal["file_search"] """The type of the file search tool. Always `file_search`.""" vector_store_ids: List[str] """The IDs of the vector stores to search.""" filters: Optional[Filters] = None """A filter to apply.""" max_num_results: Optional[int] = None """The maximum number of results to return. This number should be between 1 and 50 inclusive. """ ranking_options: Optional[RankingOptions] = None """Ranking options for search."""
FileSearchTool
python
PrefectHQ__prefect
src/prefect/server/events/schemas/automations.py
{ "start": 15630, "end": 21199 }
class ____(PrefectBaseModel, extra="ignore"): """Defines an action a user wants to take when a certain number of events do or don't happen to the matching resources""" name: str = Field(default=..., description="The name of this automation") description: str = Field( default="", description="A longer description of this automation" ) enabled: bool = Field( default=True, description="Whether this automation will be evaluated" ) tags: list[str] = Field( default_factory=list, description="A list of tags associated with this automation", ) trigger: ServerTriggerTypes = Field( default=..., description=( "The criteria for which events this Automation covers and how it will " "respond to the presence or absence of those events" ), ) actions: list[ServerActionTypes] = Field( default=..., description="The actions to perform when this Automation triggers", ) actions_on_trigger: list[ServerActionTypes] = Field( default_factory=list, description="The actions to perform when an Automation goes into a triggered state", ) actions_on_resolve: list[ServerActionTypes] = Field( default_factory=list, description="The actions to perform when an Automation goes into a resolving state", ) def triggers(self) -> Sequence[Trigger]: """Returns all triggers within this automation""" return self.trigger.all_triggers() def triggers_of_type(self, trigger_type: Type[T]) -> Sequence[T]: """Returns all triggers of the specified type within this automation""" return [t for t in self.triggers() if isinstance(t, trigger_type)] def trigger_by_id(self, trigger_id: UUID) -> Optional[Trigger]: """Returns the trigger with the given ID, or None if no such trigger exists""" for trigger in self.triggers(): if trigger.id == trigger_id: return trigger return None @model_validator(mode="after") def prevent_run_deployment_loops(self) -> Self: """Detects potential infinite loops in automations with RunDeployment actions""" from prefect.server.events.actions import RunDeployment if not self.enabled: # Disabled automations can't cause problems return self if ( not self.trigger or not isinstance(self.trigger, EventTrigger) or self.trigger.posture != Posture.Reactive ): # Only reactive automations can cause infinite amplification return self if not any(e.startswith("prefect.flow-run.") for e in self.trigger.expect): # Only flow run events can cause infinite amplification return self # Every flow run created by a Deployment goes through these states problematic_events = { "prefect.flow-run.Scheduled", "prefect.flow-run.Pending", "prefect.flow-run.Running", "prefect.flow-run.*", } if not problematic_events.intersection(self.trigger.expect): return self actions = [a for a in self.actions if isinstance(a, RunDeployment)] for action in actions: if action.source == "inferred": # Inferred deployments for flow run state change events will always # cause infinite loops, because no matter what filters we place on the # flow run, we're inferring the deployment from it, so we'll always # produce a new flow run that matches those filters. raise ValueError( "Running an inferred deployment from a flow run state change event " "will lead to an infinite loop of flow runs. Please choose a " "specific deployment and add additional filtering labels to the " "match or match_related for this automation's trigger." ) if action.source == "selected": # Selected deployments for flow run state changes can cause infinite # loops if there aren't enough filtering labels on the trigger's match # or match_related. While it's still possible to have infinite loops # with additional filters, it's less likely. if self.trigger.match.matches_every_resource_of_kind( "prefect.flow-run" ): relateds = ( self.trigger.match_related if isinstance(self.trigger.match_related, list) else [self.trigger.match_related] ) if any( related.matches_every_resource_of_kind("prefect.flow-run") for related in relateds ): raise ValueError( "Running a selected deployment from a flow run state " "change event may lead to an infinite loop of flow runs. " "Please include additional filtering labels on either " "match or match_related to narrow down which flow runs " "will trigger this automation to exclude flow runs from " "the deployment you've selected." ) return self
AutomationCore
python
pandas-dev__pandas
pandas/tests/scalar/timestamp/test_comparisons.py
{ "start": 165, "end": 10027 }
class ____: def test_compare_non_nano_dt64(self): # don't raise when converting dt64 to Timestamp in __richcmp__ dt = np.datetime64("1066-10-14") ts = Timestamp(dt) assert dt == ts def test_comparison_dt64_ndarray(self): ts = Timestamp("2021-01-01") ts2 = Timestamp("2019-04-05") arr = np.array([[ts.asm8, ts2.asm8]], dtype="M8[ns]") result = ts == arr expected = np.array([[True, False]], dtype=bool) tm.assert_numpy_array_equal(result, expected) result = arr == ts tm.assert_numpy_array_equal(result, expected) result = ts != arr tm.assert_numpy_array_equal(result, ~expected) result = arr != ts tm.assert_numpy_array_equal(result, ~expected) result = ts2 < arr tm.assert_numpy_array_equal(result, expected) result = arr < ts2 tm.assert_numpy_array_equal(result, np.array([[False, False]], dtype=bool)) result = ts2 <= arr tm.assert_numpy_array_equal(result, np.array([[True, True]], dtype=bool)) result = arr <= ts2 tm.assert_numpy_array_equal(result, ~expected) result = ts >= arr tm.assert_numpy_array_equal(result, np.array([[True, True]], dtype=bool)) result = arr >= ts tm.assert_numpy_array_equal(result, np.array([[True, False]], dtype=bool)) @pytest.mark.parametrize("reverse", [True, False]) def test_comparison_dt64_ndarray_tzaware(self, reverse, comparison_op): ts = Timestamp("2021-01-01 00:00:00.00000", tz="UTC") arr = np.array([ts.asm8, ts.asm8], dtype="M8[ns]") left, right = ts, arr if reverse: left, right = arr, ts if comparison_op is operator.eq: expected = np.array([False, False], dtype=bool) result = comparison_op(left, right) tm.assert_numpy_array_equal(result, expected) elif comparison_op is operator.ne: expected = np.array([True, True], dtype=bool) result = comparison_op(left, right) tm.assert_numpy_array_equal(result, expected) else: msg = "Cannot compare tz-naive and tz-aware timestamps" with pytest.raises(TypeError, match=msg): comparison_op(left, right) def test_comparison_object_array(self): # GH#15183 ts = Timestamp("2011-01-03 00:00:00-0500", tz="US/Eastern") other = Timestamp("2011-01-01 00:00:00-0500", tz="US/Eastern") naive = Timestamp("2011-01-01 00:00:00") arr = np.array([other, ts], dtype=object) res = arr == ts expected = np.array([False, True], dtype=bool) assert (res == expected).all() # 2D case arr = np.array([[other, ts], [ts, other]], dtype=object) res = arr != ts expected = np.array([[True, False], [False, True]], dtype=bool) assert res.shape == expected.shape assert (res == expected).all() # tzaware mismatch arr = np.array([naive], dtype=object) msg = "Cannot compare tz-naive and tz-aware timestamps" with pytest.raises(TypeError, match=msg): arr < ts def test_comparison(self): # 5-18-2012 00:00:00.000 stamp = 1337299200000000000 val = Timestamp(stamp) assert val == val assert not val != val assert not val < val assert val <= val assert not val > val assert val >= val other = datetime(2012, 5, 18) assert val == other assert not val != other assert not val < other assert val <= other assert not val > other assert val >= other other = Timestamp(stamp + 100) assert val != other assert val != other assert val < other assert val <= other assert other > val assert other >= val def test_compare_invalid(self): # GH#8058 val = Timestamp("20130101 12:01:02") assert not val == "foo" assert not val == 10.0 assert not val == 1 assert not val == [] assert not val == {"foo": 1} assert not val == np.float64(1) assert not val == np.int64(1) assert val != "foo" assert val != 10.0 assert val != 1 assert val != [] assert val != {"foo": 1} assert val != np.float64(1) assert val != np.int64(1) @pytest.mark.parametrize("tz", [None, "US/Pacific"]) def test_compare_date(self, tz): # GH#36131 comparing Timestamp with date object is deprecated ts = Timestamp("2021-01-01 00:00:00.00000", tz=tz) dt = ts.to_pydatetime().date() # in 2.0 we disallow comparing pydate objects with Timestamps, # following the stdlib datetime behavior. msg = "Cannot compare Timestamp with datetime.date" for left, right in [(ts, dt), (dt, ts)]: assert not left == right assert left != right with pytest.raises(TypeError, match=msg): left < right with pytest.raises(TypeError, match=msg): left <= right with pytest.raises(TypeError, match=msg): left > right with pytest.raises(TypeError, match=msg): left >= right def test_cant_compare_tz_naive_w_aware(self, utc_fixture): # see GH#1404 a = Timestamp("3/12/2012") b = Timestamp("3/12/2012", tz=utc_fixture) msg = "Cannot compare tz-naive and tz-aware timestamps" assert not a == b assert a != b with pytest.raises(TypeError, match=msg): a < b with pytest.raises(TypeError, match=msg): a <= b with pytest.raises(TypeError, match=msg): a > b with pytest.raises(TypeError, match=msg): a >= b assert not b == a assert b != a with pytest.raises(TypeError, match=msg): b < a with pytest.raises(TypeError, match=msg): b <= a with pytest.raises(TypeError, match=msg): b > a with pytest.raises(TypeError, match=msg): b >= a assert not a == b.to_pydatetime() assert not a.to_pydatetime() == b def test_timestamp_compare_scalars(self): # case where ndim == 0 lhs = np.datetime64(datetime(2013, 12, 6)) rhs = Timestamp("now") nat = Timestamp("nat") ops = {"gt": "lt", "lt": "gt", "ge": "le", "le": "ge", "eq": "eq", "ne": "ne"} for left, right in ops.items(): left_f = getattr(operator, left) right_f = getattr(operator, right) expected = left_f(lhs, rhs) result = right_f(rhs, lhs) assert result == expected expected = left_f(rhs, nat) result = right_f(nat, rhs) assert result == expected def test_timestamp_compare_with_early_datetime(self): # e.g. datetime.min stamp = Timestamp("2012-01-01") assert not stamp == datetime.min assert not stamp == datetime(1600, 1, 1) assert not stamp == datetime(2700, 1, 1) assert stamp != datetime.min assert stamp != datetime(1600, 1, 1) assert stamp != datetime(2700, 1, 1) assert stamp > datetime(1600, 1, 1) assert stamp >= datetime(1600, 1, 1) assert stamp < datetime(2700, 1, 1) assert stamp <= datetime(2700, 1, 1) other = Timestamp.min.to_pydatetime(warn=False) assert other - timedelta(microseconds=1) < Timestamp.min def test_timestamp_compare_oob_dt64(self): us = np.timedelta64(1, "us") other = np.datetime64(Timestamp.min).astype("M8[us]") # This may change if the implementation bound is dropped to match # DatetimeArray/DatetimeIndex GH#24124 assert Timestamp.min > other # Note: numpy gets the reversed comparison wrong other = np.datetime64(Timestamp.max).astype("M8[us]") assert Timestamp.max > other # not actually OOB assert other < Timestamp.max assert Timestamp.max < other + us # Note: numpy gets the reversed comparison wrong # GH-42794 other = datetime(9999, 9, 9) assert Timestamp.min < other assert other > Timestamp.min assert Timestamp.max < other assert other > Timestamp.max other = datetime(1, 1, 1) assert Timestamp.max > other assert other < Timestamp.max assert Timestamp.min > other assert other < Timestamp.min def test_compare_zerodim_array(self, fixed_now_ts): # GH#26916 ts = fixed_now_ts dt64 = np.datetime64("2016-01-01", "ns") arr = np.array(dt64) assert arr.ndim == 0 result = arr < ts assert result is np.bool_(True) result = arr > ts assert result is np.bool_(False) def test_rich_comparison_with_unsupported_type(): # Comparisons with unsupported objects should return NotImplemented # (it previously raised TypeError, see #24011) class Inf: def __lt__(self, o): return False def __le__(self, o): return isinstance(o, Inf) def __gt__(self, o): return not isinstance(o, Inf) def __ge__(self, o): return True def __eq__(self, other) -> bool: return isinstance(other, Inf) inf = Inf() timestamp = Timestamp("2018-11-30") for left, right in [(inf, timestamp), (timestamp, inf)]: assert left > right or left < right assert left >= right or left <= right assert not left == right assert left != right
TestTimestampComparison
python
keras-team__keras
keras/src/saving/serialization_lib_test.py
{ "start": 536, "end": 1198 }
class ____(keras.layers.Layer): def __init__(self, factor, dense=None, activation=None): super().__init__() self.factor = factor if dense is None: self.dense = keras.layers.Dense(1, activation=custom_fn) else: self.dense = serialization_lib.deserialize_keras_object(dense) self.activation = serialization_lib.deserialize_keras_object(activation) def call(self, x): return self.dense(x * self.factor) def get_config(self): return { "factor": self.factor, "dense": self.dense, "activation": self.activation, }
NestedCustomLayer
python
getsentry__sentry
src/sentry/rules/filters/assigned_to.py
{ "start": 622, "end": 2993 }
class ____(EventFilter): id = "sentry.rules.filters.assigned_to.AssignedToFilter" label = "The issue is assigned to {targetType}" prompt = "The issue is assigned to {no one/team/member}" form_fields = {"targetType": {"type": "assignee", "choices": ASSIGNEE_CHOICES}} def get_assignees(self, group: Group) -> list[GroupAssignee]: cache_key = f"group:{group.id}:assignees" assignee_list = cache.get(cache_key) if assignee_list is None: assignee_list = list(group.assignee_set.all()) cache.set(cache_key, assignee_list, 60) return assignee_list def passes(self, event: GroupEvent, state: EventState) -> bool: target_type = AssigneeTargetType(self.get_option("targetType")) if target_type == AssigneeTargetType.UNASSIGNED: return len(self.get_assignees(event.group)) == 0 else: target_id = self.get_option("targetIdentifier", None) if target_type == AssigneeTargetType.TEAM: for assignee in self.get_assignees(event.group): if assignee.team_id and assignee.team_id == target_id: return True elif target_type == AssigneeTargetType.MEMBER: for assignee in self.get_assignees(event.group): if assignee.user_id and assignee.user_id == target_id: return True return False def get_form_instance(self) -> forms.Form: return AssignedToForm(self.project, self.data) def render_label(self) -> str: target_type = AssigneeTargetType(self.get_option("targetType")) target_identifer = self.get_option("targetIdentifier") if target_type == AssigneeTargetType.TEAM: try: team = Team.objects.get(id=target_identifer) except Team.DoesNotExist: return self.label.format(**self.data) return self.label.format(targetType=f"team #{team.slug}") elif target_type == AssigneeTargetType.MEMBER: user = user_service.get_user(user_id=target_identifer) if user is not None: return self.label.format(targetType=user.username) else: return self.label.format(**self.data) return self.label.format(**self.data)
AssignedToFilter
python
encode__django-rest-framework
tests/test_validation.py
{ "start": 1757, "end": 2353 }
class ____(TestCase): def test_renamed_fields_are_model_validated(self): """ Ensure fields with 'source' applied do get still get model validation. """ # We've set `required=False` on the serializer, but the model # does not have `blank=True`, so this serializer should not validate. serializer = ShouldValidateModelSerializer(data={'renamed': ''}) assert serializer.is_valid() is False assert 'renamed' in serializer.errors assert 'should_validate_field' not in serializer.errors
TestPreSaveValidationExclusionsSerializer
python
kamyu104__LeetCode-Solutions
Python/count-of-matches-in-tournament.py
{ "start": 29, "end": 171 }
class ____(object): def numberOfMatches(self, n): """ :type n: int :rtype: int """ return n-1
Solution
python
celery__celery
celery/backends/database/models.py
{ "start": 2432, "end": 3494 }
class ____(ResultModelBase): """TaskSet result.""" __tablename__ = 'celery_tasksetmeta' __table_args__ = {'sqlite_autoincrement': True} id = sa.Column(DialectSpecificInteger, sa.Sequence('taskset_id_sequence'), autoincrement=True, primary_key=True) taskset_id = sa.Column(sa.String(155), unique=True) result = sa.Column(PickleType, nullable=True) date_done = sa.Column(sa.DateTime, default=datetime.now(timezone.utc), nullable=True) def __init__(self, taskset_id, result): self.taskset_id = taskset_id self.result = result def to_dict(self): return { 'taskset_id': self.taskset_id, 'result': self.result, 'date_done': self.date_done, } def __repr__(self): return f'<TaskSet: {self.taskset_id}>' @classmethod def configure(cls, schema=None, name=None): cls.__table__.schema = schema cls.id.default.schema = schema cls.__table__.name = name or cls.__tablename__
TaskSet
python
django__django
tests/auth_tests/test_mixins.py
{ "start": 1079, "end": 1292 }
class ____( PermissionRequiredMixin, LoginRequiredMixin, EmptyResponseView ): permission_required = ["auth_tests.add_customuser", "auth_tests.change_customuser"] raise_exception = True
StackedMixinsView2
python
numba__numba
numba/cuda/cudadrv/error.py
{ "start": 139, "end": 238 }
class ____(Exception): def __str__(self): return '\n'.join(map(str, self.args))
NvvmError
python
facebookresearch__faiss
tests/test_local_search_quantizer.py
{ "start": 10311, "end": 12791 }
class ____(unittest.TestCase): def test_IndexLocalSearchQuantizer(self): ds = datasets.SyntheticDataset(32, 1000, 200, 100) gt = ds.get_groundtruth(10) ir = faiss.IndexLocalSearchQuantizer(ds.d, 4, 5) ir.train(ds.get_train()) ir.add(ds.get_database()) Dref, Iref = ir.search(ds.get_queries(), 10) inter_ref = faiss.eval_intersection(Iref, gt) # 467 self.assertGreater(inter_ref, 460) AQ = faiss.AdditiveQuantizer ir2 = faiss.IndexLocalSearchQuantizer( ds.d, 4, 5, faiss.METRIC_L2, AQ.ST_norm_float) ir2.train(ds.get_train()) # just to set flags properly ir2.lsq.codebooks = ir.lsq.codebooks ir2.add(ds.get_database()) D2, I2 = ir2.search(ds.get_queries(), 10) np.testing.assert_array_almost_equal(Dref, D2, decimal=5) self.assertLess((Iref != I2).sum(), Iref.size * 0.01) # test I/O ir3 = faiss.deserialize_index(faiss.serialize_index(ir)) D3, I3 = ir3.search(ds.get_queries(), 10) np.testing.assert_array_equal(Iref, I3) np.testing.assert_array_equal(Dref, D3) def test_coarse_quantizer(self): ds = datasets.SyntheticDataset(32, 5000, 1000, 100) gt = ds.get_groundtruth(10) quantizer = faiss.LocalSearchCoarseQuantizer(ds.d, 2, 4) quantizer.lsq.nperts quantizer.lsq.nperts = 2 index = faiss.IndexIVFFlat(quantizer, ds.d, 256) index.quantizer_trains_alone = True index.train(ds.get_train()) index.add(ds.get_database()) index.nprobe = 4 Dref, Iref = index.search(ds.get_queries(), 10) inter_ref = faiss.eval_intersection(Iref, gt) # 249 self.assertGreater(inter_ref, 235) def test_factory(self): index = faiss.index_factory(20, "LSQ5x6_Nqint8") self.assertEqual(index.lsq.M, 5) self.assertEqual(index.lsq.K, 1 << 6) self.assertEqual( index.lsq.search_type, faiss.AdditiveQuantizer.ST_norm_qint8 ) index = faiss.index_factory(20, "LSQ5x6_Ncqint8") self.assertEqual( index.lsq.search_type, faiss.AdditiveQuantizer.ST_norm_cqint8 ) index = faiss.index_factory(20, "LSQ5x6_Ncqint4") self.assertEqual( index.lsq.search_type, faiss.AdditiveQuantizer.ST_norm_cqint4 )
TestIndexLocalSearchQuantizer
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
{ "start": 28776, "end": 31111 }
class ____(GradientCheckpointingLayer): def __init__(self, config: Qwen3OmniMoeAudioEncoderConfig): super().__init__() self.embed_dim = config.d_model self.self_attn = Qwen3OmniMoeAudioAttention(config) self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.dropout = config.dropout self.activation_fn = ACT2FN[config.activation_function] self.activation_dropout = config.activation_dropout self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim) self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) self.final_layer_norm = nn.LayerNorm(self.embed_dim) def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs, ) -> torch.Tensor: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states hidden_states = self.self_attn_layer_norm(hidden_states) hidden_states = self.self_attn( hidden_states=hidden_states, cu_seqlens=cu_seqlens, attention_mask=attention_mask, **kwargs, ) hidden_states = residual + hidden_states residual = hidden_states hidden_states = self.final_layer_norm(hidden_states) hidden_states = self.fc1(hidden_states) hidden_states = self.activation_fn(hidden_states) hidden_states = self.fc2(hidden_states) hidden_states = residual + hidden_states if hidden_states.dtype == torch.float16: clamp_value = torch.finfo(hidden_states.dtype).max - 1000 hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value) outputs = (hidden_states,) return outputs
Qwen3OmniMoeAudioEncoderLayer
python
viewflow__viewflow
viewflow/views/base.py
{ "start": 1492, "end": 1958 }
class ____(forms.Form): def __init__(self, *args, **kwargs): model = kwargs.pop("model") super().__init__(*args, **kwargs) self.fields["pk"] = forms.ModelMultipleChoiceField( queryset=model._default_manager.all(), widget=forms.MultipleHiddenInput, required=False, ) self.fields["select_all"] = forms.CharField( widget=forms.HiddenInput, required=False )
BulkActionForm
python
PyCQA__pylint
tests/functional/s/super/super_init_not_called_extensions_py310.py
{ "start": 355, "end": 518 }
class ____(TestParent): """An implementation which should call the init of TestParent.""" def __init__(self): # [super-init-not-called] ...
TestChild
python
apache__airflow
airflow-core/src/airflow/example_dags/plugins/listener_plugin.py
{ "start": 930, "end": 1048 }
class ____(AirflowPlugin): name = "MetadataCollectionPlugin" listeners = [event_listener]
MetadataCollectionPlugin
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/super7.py
{ "start": 160, "end": 227 }
class ____: def my_method(self, value: int) -> int: ...
BaseClass
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/matchSequence1.py
{ "start": 14331, "end": 18109 }
class ____: ... AAlias = A AInt = A[int] BOrC = B | C def test_illegal_type_alias(m: object): match m: case AAlias(a=i): pass # This should generate an error because it raises an # exception at runtime. case AInt(a=i): pass # This should generate an error because it raises an # exception at runtime. case BOrC(a=i): pass def test_negative_narrowing1(subj: tuple[Literal[0]] | tuple[Literal[1]]): match subj: case (1, *a) | (*a): reveal_type(subj, expected_text="tuple[Literal[1]] | tuple[Literal[0]]") reveal_type(a, expected_text="list[Any] | list[int]") case b: reveal_type(subj, expected_text="Never") reveal_type(b, expected_text="Never") def test_negative_narrowing2(subj: tuple[int, ...]): match subj: case (1, *a): reveal_type(subj, expected_text="tuple[int, ...]") reveal_type(a, expected_text="list[int]") case (b,): reveal_type(subj, expected_text="tuple[int]") reveal_type(b, expected_text="int") case (*c,): reveal_type(subj, expected_text="tuple[int, ...]") reveal_type(c, expected_text="list[int]") case d: reveal_type(subj, expected_text="Never") reveal_type(d, expected_text="Never") def test_negative_narrowing3(subj: tuple[Any, Any]): match subj: case (a, b): reveal_type(a, expected_text="Any") reveal_type(b, expected_text="Any") case x: reveal_type(x, expected_text="Never") def test_negative_narrowing4(a: str | None, b: str | None): match (a, b): case (None, _) as x: reveal_type(x, expected_text="tuple[None, str | None]") case (_, None) as x: reveal_type(x, expected_text="tuple[str, None]") case (a, b) as x: reveal_type(x, expected_text="tuple[str, str]") def test_negative_narrowing5(a: str | None, b: str | None): match (a, b): case (None, _) | (_, None) as x: reveal_type(x, expected_text="tuple[None, str | None] | tuple[str, None]") case (a, b) as x: reveal_type(x, expected_text="tuple[str, str]") def test_negative_narrowing6(a: str | None, b: str | None): match (a, b): case (None, None) as x: reveal_type(x, expected_text="tuple[None, None]") reveal_type(a, expected_text="None") reveal_type(b, expected_text="None") case (None, _) as x if 2 > 1: reveal_type(x, expected_text="tuple[None, str]") reveal_type(a, expected_text="None") reveal_type(b, expected_text="str") case (a, b) as x: reveal_type( x, expected_text="tuple[str, str | None] | tuple[str | None, str]" ) reveal_type(a, expected_text="str | None") reveal_type(b, expected_text="str | None") def test_negative_narrowing7(a: tuple[str, str] | str): match a: case (_, _): reveal_type(a, expected_text="tuple[str, str]") case _: reveal_type(a, expected_text="str") def test_negative_narrowing8(a: str | int, b: str | int): t = a, b match t: case int(), int(): reveal_type(t, expected_text="tuple[int, int]") case str(), int(): reveal_type(t, expected_text="tuple[str, int]") case int(), str(): reveal_type(t, expected_text="tuple[int, str]") case x, y: reveal_type(t, expected_text="tuple[str, str]") reveal_type(x, expected_text="str") reveal_type(y, expected_text="str")
C
python
huggingface__transformers
src/transformers/models/informer/modular_informer.py
{ "start": 20847, "end": 21781 }
class ____(TimeSeriesTransformerDecoder): def __init__(self, config: InformerConfig): super().__init__(config) self.dropout = config.dropout self.layerdrop = config.decoder_layerdrop if config.prediction_length is None: raise ValueError("The `prediction_length` config needs to be specified.") self.value_embedding = InformerValueEmbedding(feature_size=config.feature_size, d_model=config.d_model) self.embed_positions = InformerSinusoidalPositionalEmbedding( config.context_length + config.prediction_length, config.d_model ) self.layers = nn.ModuleList([InformerDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)]) self.layernorm_embedding = nn.LayerNorm(config.d_model) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init()
InformerDecoder
python
walkccc__LeetCode
solutions/465. Optimal Account Balancing/465.py
{ "start": 0, "end": 647 }
class ____: def minTransfers(self, transactions: list[list[int]]) -> int: balance = [0] * 21 for u, v, amount in transactions: balance[u] -= amount balance[v] += amount debts = [b for b in balance if b] def dfs(s: int) -> int: while s < len(debts) and not debts[s]: s += 1 if s == len(debts): return 0 ans = math.inf for i in range(s + 1, len(debts)): if debts[i] * debts[s] < 0: debts[i] += debts[s] # `debts[s]` is settled. ans = min(ans, 1 + dfs(s + 1)) debts[i] -= debts[s] # Backtrack. return ans return dfs(0)
Solution
python
realpython__materials
python-self-type/accounts_future_module.py
{ "start": 651, "end": 1658 }
class ____(BankAccount): interest_rate: float @classmethod def from_application( cls, deposit: float = 0, interest_rate: float = 1 ) -> SavingsAccount: # Generate a random seven-digit bank account number account_number = random.randint(1000000, 9999999) return cls(account_number, deposit, interest_rate) def calculate_interest(self) -> float: return self.balance * self.interest_rate / 100 def add_interest(self) -> SavingsAccount: self.deposit(self.calculate_interest()) return self account = BankAccount(account_number=1534899324, balance=50) ( account.display_balance() .deposit(50) .display_balance() .withdraw(30) .display_balance() ) savings = SavingsAccount.from_application(deposit=100, interest_rate=5) ( savings.display_balance() .add_interest() .display_balance() .deposit(50) .display_balance() .withdraw(30) .add_interest() .display_balance() )
SavingsAccount
python
getsentry__sentry
tests/sentry/sudo/test_forms.py
{ "start": 359, "end": 1707 }
class ____(BaseTestCase): def setUp(self) -> None: super().setUp() self.login() def test_integration_empty(self) -> None: self.assertFalse(SudoForm(self.user).is_valid()) def test_integration_invalid_password(self) -> None: self.assertFalse(SudoForm(self.user, {"password": "lol"}).is_valid()) def test_integration_valid_password(self) -> None: self.assertTrue(SudoForm(self.user, {"password": "foo"}).is_valid()) def test_integration_secondary_auth_valid_password(self) -> None: self.assertTrue(SudoForm(self.user, {"password": "stub"}).is_valid()) def test_clean_password_invalid_password(self) -> None: with pytest.raises(ValidationError): SudoForm(self.user, {"password": "lol"}).clean_password() def test_clean_password_valid_password(self) -> None: password = "foo" self.assertEqual(SudoForm(self.user, {"password": password}).clean_password(), password) def test_clean_password_secondary_auth_valid_password(self) -> None: password = "stub" self.assertEqual(SudoForm(self.user, {"password": password}).clean_password(), password) def test_integration_custom_user(self) -> None: self.login(EmailUser) self.assertTrue(SudoForm(self.user, {"password": "foo"}).is_valid())
SudoFormTestCase
python
encode__django-rest-framework
rest_framework/utils/field_mapping.py
{ "start": 495, "end": 12126 }
class ____: """ Takes a dictionary with classes as keys. Lookups against this object will traverses the object's inheritance hierarchy in method resolution order, and returns the first matching value from the dictionary or raises a KeyError if nothing matches. """ def __init__(self, mapping): self.mapping = mapping def __getitem__(self, key): if hasattr(key, '_proxy_class'): # Deal with proxy classes. Ie. BoundField behaves as if it # is a Field instance when using ClassLookupDict. base_class = key._proxy_class else: base_class = key.__class__ for cls in inspect.getmro(base_class): if cls in self.mapping: return self.mapping[cls] raise KeyError('Class %s not found in lookup.' % base_class.__name__) def __setitem__(self, key, value): self.mapping[key] = value def needs_label(model_field, field_name): """ Returns `True` if the label based on the model's verbose name is not equal to the default label it would have based on it's field name. """ default_label = field_name.replace('_', ' ').capitalize() return capfirst(model_field.verbose_name) != default_label def get_detail_view_name(model): """ Given a model class, return the view name to use for URL relationships that refer to instances of the model. """ return '%(model_name)s-detail' % { 'model_name': model._meta.object_name.lower() } def get_unique_validators(field_name, model_field): """ Returns a list of UniqueValidators that should be applied to the field. """ field_set = {field_name} conditions = { c.condition for c in model_field.model._meta.constraints if isinstance(c, models.UniqueConstraint) and set(c.fields) == field_set } if getattr(model_field, 'unique', False): conditions.add(None) if not conditions: return unique_error_message = get_unique_error_message(model_field) queryset = model_field.model._default_manager for condition in conditions: yield UniqueValidator( queryset=queryset if condition is None else queryset.filter(condition), message=unique_error_message ) def get_field_kwargs(field_name, model_field): """ Creates a default instance of a basic non-relational field. """ kwargs = {} validator_kwarg = list(model_field.validators) # The following will only be used by ModelField classes. # Gets removed for everything else. kwargs['model_field'] = model_field if model_field.verbose_name and needs_label(model_field, field_name): kwargs['label'] = capfirst(model_field.verbose_name) if model_field.help_text: kwargs['help_text'] = model_field.help_text max_digits = getattr(model_field, 'max_digits', None) if max_digits is not None: kwargs['max_digits'] = max_digits decimal_places = getattr(model_field, 'decimal_places', None) if decimal_places is not None: kwargs['decimal_places'] = decimal_places if isinstance(model_field, models.SlugField): kwargs['allow_unicode'] = model_field.allow_unicode if isinstance(model_field, models.TextField) and not model_field.choices or \ (postgres_fields and isinstance(model_field, postgres_fields.JSONField)) or \ (hasattr(models, 'JSONField') and isinstance(model_field, models.JSONField)): kwargs['style'] = {'base_template': 'textarea.html'} if model_field.null: kwargs['allow_null'] = True if isinstance(model_field, models.AutoField) or not model_field.editable: # If this field is read-only, then return early. # Further keyword arguments are not valid. kwargs['read_only'] = True return kwargs if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False if model_field.blank and (isinstance(model_field, (models.CharField, models.TextField))): kwargs['allow_blank'] = True if not model_field.blank and (postgres_fields and isinstance(model_field, postgres_fields.ArrayField)): kwargs['allow_empty'] = False if isinstance(model_field, models.FilePathField): kwargs['path'] = model_field.path if model_field.match is not None: kwargs['match'] = model_field.match if model_field.recursive is not False: kwargs['recursive'] = model_field.recursive if model_field.allow_files is not True: kwargs['allow_files'] = model_field.allow_files if model_field.allow_folders is not False: kwargs['allow_folders'] = model_field.allow_folders if model_field.choices: kwargs['choices'] = model_field.choices else: # Ensure that max_value is passed explicitly as a keyword arg, # rather than as a validator. max_value = next(( validator.limit_value for validator in validator_kwarg if isinstance(validator, validators.MaxValueValidator) ), None) if max_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES): kwargs['max_value'] = max_value validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MaxValueValidator) ] # Ensure that min_value is passed explicitly as a keyword arg, # rather than as a validator. min_value = next(( validator.limit_value for validator in validator_kwarg if isinstance(validator, validators.MinValueValidator) ), None) if min_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES): kwargs['min_value'] = min_value validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MinValueValidator) ] # URLField does not need to include the URLValidator argument, # as it is explicitly added in. if isinstance(model_field, models.URLField): validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.URLValidator) ] # EmailField does not need to include the validate_email argument, # as it is explicitly added in. if isinstance(model_field, models.EmailField): validator_kwarg = [ validator for validator in validator_kwarg if validator is not validators.validate_email ] # SlugField do not need to include the 'validate_slug' argument, if isinstance(model_field, models.SlugField): validator_kwarg = [ validator for validator in validator_kwarg if validator is not validators.validate_slug ] # IPAddressField do not need to include the 'validate_ipv46_address' argument, if isinstance(model_field, models.GenericIPAddressField): validator_kwarg = [ validator for validator in validator_kwarg if validator is not validators.validate_ipv46_address ] # Our decimal validation is handled in the field code, not validator code. if isinstance(model_field, models.DecimalField): validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.DecimalValidator) ] # Ensure that max_length is passed explicitly as a keyword arg, # rather than as a validator. max_length = getattr(model_field, 'max_length', None) if max_length is not None and (isinstance(model_field, (models.CharField, models.TextField, models.FileField))): kwargs['max_length'] = max_length validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MaxLengthValidator) ] # Ensure that min_length is passed explicitly as a keyword arg, # rather than as a validator. min_length = next(( validator.limit_value for validator in validator_kwarg if isinstance(validator, validators.MinLengthValidator) ), None) if min_length is not None and isinstance(model_field, models.CharField): kwargs['min_length'] = min_length validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MinLengthValidator) ] validator_kwarg += get_unique_validators(field_name, model_field) if validator_kwarg: kwargs['validators'] = validator_kwarg return kwargs def get_relation_kwargs(field_name, relation_info): """ Creates a default instance of a flat relational field. """ model_field, related_model, to_many, to_field, has_through_model, reverse = relation_info kwargs = { 'queryset': related_model._default_manager, 'view_name': get_detail_view_name(related_model) } if to_many: kwargs['many'] = True if to_field: kwargs['to_field'] = to_field limit_choices_to = model_field and model_field.get_limit_choices_to() if limit_choices_to: if not isinstance(limit_choices_to, models.Q): limit_choices_to = models.Q(**limit_choices_to) kwargs['queryset'] = kwargs['queryset'].filter(limit_choices_to) if has_through_model: kwargs['read_only'] = True kwargs.pop('queryset', None) if model_field: if model_field.verbose_name and needs_label(model_field, field_name): kwargs['label'] = capfirst(model_field.verbose_name) help_text = model_field.help_text if help_text: kwargs['help_text'] = help_text if not model_field.editable: kwargs['read_only'] = True kwargs.pop('queryset', None) if model_field.null: kwargs['allow_null'] = True if kwargs.get('read_only', False): # If this field is read-only, then return early. # No further keyword arguments are valid. return kwargs if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False if model_field.validators: kwargs['validators'] = model_field.validators if getattr(model_field, 'unique', False): validator = UniqueValidator( queryset=model_field.model._default_manager, message=get_unique_error_message(model_field)) kwargs['validators'] = kwargs.get('validators', []) + [validator] if to_many and not model_field.blank: kwargs['allow_empty'] = False return kwargs def get_nested_relation_kwargs(relation_info): kwargs = {'read_only': True} if relation_info.to_many: kwargs['many'] = True return kwargs def get_url_kwargs(model_field): return { 'view_name': get_detail_view_name(model_field) } def get_unique_error_message(model_field): unique_error_message = model_field.error_messages.get('unique', None) if unique_error_message: unique_error_message = unique_error_message % { 'model_name': model_field.model._meta.verbose_name, 'field_label': model_field.verbose_name } return unique_error_message
ClassLookupDict
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 252001, "end": 254271 }
class ____(rv_continuous): r"""A non-central Student's t continuous random variable. %(before_notes)s Notes ----- If :math:`Y` is a standard normal random variable and :math:`V` is an independent chi-square random variable (`chi2`) with :math:`k` degrees of freedom, then .. math:: X = \frac{Y + c}{\sqrt{V/k}} has a non-central Student's t distribution on the real line. The degrees of freedom parameter :math:`k` (denoted ``df`` in the implementation) satisfies :math:`k > 0` and the noncentrality parameter :math:`c` (denoted ``nc`` in the implementation) is a real number. This distribution uses routines from the Boost Math C++ library for the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf`` methods. [1]_ %(after_notes)s References ---------- .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/. %(example)s """ def _argcheck(self, df, nc): return (df > 0) & (nc == nc) def _shape_info(self): idf = _ShapeInfo("df", False, (0, np.inf), (False, False)) inc = _ShapeInfo("nc", False, (-np.inf, np.inf), (False, False)) return [idf, inc] def _rvs(self, df, nc, size=None, random_state=None): n = norm.rvs(loc=nc, size=size, random_state=random_state) c2 = chi2.rvs(df, size=size, random_state=random_state) return n * np.sqrt(df) / np.sqrt(c2) def _pdf(self, x, df, nc): return scu._nct_pdf(x, df, nc) def _cdf(self, x, df, nc): return sc.nctdtr(df, nc, x) def _ppf(self, q, df, nc): return sc.nctdtrit(df, nc, q) def _sf(self, x, df, nc): with np.errstate(over='ignore'): # see gh-17432 return np.clip(scu._nct_sf(x, df, nc), 0, 1) def _isf(self, x, df, nc): with np.errstate(over='ignore'): # see gh-17432 return scu._nct_isf(x, df, nc) def _stats(self, df, nc, moments='mv'): mu = scu._nct_mean(df, nc) mu2 = scu._nct_variance(df, nc) g1 = scu._nct_skewness(df, nc) if 's' in moments else None g2 = scu._nct_kurtosis_excess(df, nc) if 'k' in moments else None return mu, mu2, g1, g2 nct = nct_gen(name="nct")
nct_gen
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_with.py
{ "start": 10663, "end": 13605 }
class ____(__TestCase, ContextmanagerAssertionMixin): def testSingleArgInlineGeneratorSyntax(self): with Nested(mock_contextmanager_generator()): pass def testSingleArgBoundToNonTuple(self): m = mock_contextmanager_generator() # This will bind all the arguments to nested() into a single list # assigned to foo. with Nested(m) as foo: self.assertInWithManagerInvariants(m) self.assertAfterWithManagerInvariantsNoError(m) def testSingleArgBoundToSingleElementParenthesizedList(self): m = mock_contextmanager_generator() # This will bind all the arguments to nested() into a single list # assigned to foo. with Nested(m) as (foo): self.assertInWithManagerInvariants(m) self.assertAfterWithManagerInvariantsNoError(m) def testSingleArgBoundToMultipleElementTupleError(self): def shouldThrowValueError(): with Nested(mock_contextmanager_generator()) as (foo, bar): pass self.assertRaises(ValueError, shouldThrowValueError) def testSingleArgUnbound(self): mock_contextmanager = mock_contextmanager_generator() mock_nested = MockNested(mock_contextmanager) with mock_nested: self.assertInWithManagerInvariants(mock_contextmanager) self.assertInWithManagerInvariants(mock_nested) self.assertAfterWithManagerInvariantsNoError(mock_contextmanager) self.assertAfterWithManagerInvariantsNoError(mock_nested) def testMultipleArgUnbound(self): m = mock_contextmanager_generator() n = mock_contextmanager_generator() o = mock_contextmanager_generator() mock_nested = MockNested(m, n, o) with mock_nested: self.assertInWithManagerInvariants(m) self.assertInWithManagerInvariants(n) self.assertInWithManagerInvariants(o) self.assertInWithManagerInvariants(mock_nested) self.assertAfterWithManagerInvariantsNoError(m) self.assertAfterWithManagerInvariantsNoError(n) self.assertAfterWithManagerInvariantsNoError(o) self.assertAfterWithManagerInvariantsNoError(mock_nested) def testMultipleArgBound(self): mock_nested = MockNested(mock_contextmanager_generator(), mock_contextmanager_generator(), mock_contextmanager_generator()) with mock_nested as (m, n, o): self.assertInWithGeneratorInvariants(m) self.assertInWithGeneratorInvariants(n) self.assertInWithGeneratorInvariants(o) self.assertInWithManagerInvariants(mock_nested) self.assertAfterWithGeneratorInvariantsNoError(m) self.assertAfterWithGeneratorInvariantsNoError(n) self.assertAfterWithGeneratorInvariantsNoError(o) self.assertAfterWithManagerInvariantsNoError(mock_nested)
NestedNonexceptionalTestCase
python
pytorch__pytorch
tools/experimental/torchfuzz/operators/layout.py
{ "start": 181, "end": 445 }
class ____(Operator): """Base class for tensor layout operations.""" def can_produce(self, output_spec: Spec) -> bool: """All layout operations can only produce tensor outputs.""" return isinstance(output_spec, TensorSpec)
LayoutOperatorBase
python
huggingface__transformers
src/transformers/models/zoedepth/modeling_zoedepth.py
{ "start": 1268, "end": 1956 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. domain_logits (`torch.FloatTensor` of shape `(batch_size, num_domains)`): Logits for each domain (e.g. NYU and KITTI) in case multiple metric heads are used. """ loss: Optional[torch.FloatTensor] = None predicted_depth: Optional[torch.FloatTensor] = None domain_logits: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None
ZoeDepthDepthEstimatorOutput
python
pallets__quart
src/quart/testing/connections.py
{ "start": 3833, "end": 7028 }
class ____: def __init__(self, app: Quart, scope: WebsocketScope) -> None: self.accepted = False self.app = app self.headers: Headers | None = None self.response_data = bytearray() self.scope = scope self.status_code: int | None = None self._send_queue: asyncio.Queue = asyncio.Queue() self._receive_queue: asyncio.Queue = asyncio.Queue() self._task: Awaitable[None] = None async def __aenter__(self) -> TestWebsocketConnection: self._task = asyncio.ensure_future( self.app(self.scope, self._asgi_receive, self._asgi_send) ) return self async def __aexit__( self, exc_type: type, exc_value: BaseException, tb: TracebackType ) -> None: await self.disconnect() await self._task while not self._receive_queue.empty(): data = await self._receive_queue.get() if isinstance(data, Exception) and not isinstance( data, WebsocketDisconnectError ): raise data async def receive(self) -> AnyStr: data = await self._receive_queue.get() if isinstance(data, Exception): raise data else: return data async def send(self, data: AnyStr) -> None: if isinstance(data, str): await self._send_queue.put({"type": "websocket.receive", "text": data}) else: await self._send_queue.put({"type": "websocket.receive", "bytes": data}) async def receive_json(self) -> Any: data = await self.receive() return loads(data) async def send_json(self, data: Any) -> None: raw = dumps(data) await self.send(raw) async def close(self, code: int) -> None: await self._send_queue.put({"type": "websocket.close", "code": code}) async def disconnect(self) -> None: await self._send_queue.put({"type": "websocket.disconnect"}) async def _asgi_receive(self) -> ASGIReceiveEvent: return await self._send_queue.get() async def _asgi_send(self, message: ASGISendEvent) -> None: if message["type"] == "websocket.accept": self.accepted = True elif message["type"] == "websocket.send": await self._receive_queue.put(message.get("bytes") or message.get("text")) elif message["type"] == "websocket.http.response.start": self.headers = decode_headers(message["headers"]) self.status_code = message["status"] elif message["type"] == "websocket.http.response.body": self.response_data.extend(message["body"]) if not message.get("more_body", False): await self._receive_queue.put( WebsocketResponseError( self.app.response_class( bytes(self.response_data), self.status_code, self.headers ) ) ) elif message["type"] == "websocket.close": await self._receive_queue.put( WebsocketDisconnectError(message.get("code", 1000)) )
TestWebsocketConnection
python
networkx__networkx
networkx/readwrite/tests/test_gexf.py
{ "start": 1984, "end": 21327 }
class ____: @classmethod def setup_class(cls): cls.simple_directed_data = """<?xml version="1.0" encoding="UTF-8"?> <gexf xmlns="http://www.gexf.net/1.2draft" version="1.2"> <graph mode="static" defaultedgetype="directed"> <nodes> <node id="0" label="Hello" /> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1" /> </edges> </graph> </gexf> """ cls.simple_directed_graph = nx.DiGraph() cls.simple_directed_graph.add_node("0", label="Hello") cls.simple_directed_graph.add_node("1", label="World") cls.simple_directed_graph.add_edge("0", "1", id="0") cls.simple_directed_fh = io.BytesIO(cls.simple_directed_data.encode("UTF-8")) cls.attribute_data = """<?xml version="1.0" encoding="UTF-8"?>\ <gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.\ org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.gexf.net/\ 1.2draft http://www.gexf.net/1.2draft/gexf.xsd" version="1.2"> <meta lastmodifieddate="2009-03-20"> <creator>Gephi.org</creator> <description>A Web network</description> </meta> <graph defaultedgetype="directed"> <attributes class="node"> <attribute id="0" title="url" type="string"/> <attribute id="1" title="indegree" type="integer"/> <attribute id="2" title="frog" type="boolean"> <default>true</default> </attribute> </attributes> <nodes> <node id="0" label="Gephi"> <attvalues> <attvalue for="0" value="https://gephi.org"/> <attvalue for="1" value="1"/> <attvalue for="2" value="false"/> </attvalues> </node> <node id="1" label="Webatlas"> <attvalues> <attvalue for="0" value="http://webatlas.fr"/> <attvalue for="1" value="2"/> <attvalue for="2" value="false"/> </attvalues> </node> <node id="2" label="RTGI"> <attvalues> <attvalue for="0" value="http://rtgi.fr"/> <attvalue for="1" value="1"/> <attvalue for="2" value="true"/> </attvalues> </node> <node id="3" label="BarabasiLab"> <attvalues> <attvalue for="0" value="http://barabasilab.com"/> <attvalue for="1" value="1"/> <attvalue for="2" value="true"/> </attvalues> </node> </nodes> <edges> <edge id="0" source="0" target="1" label="foo"/> <edge id="1" source="0" target="2"/> <edge id="2" source="1" target="0"/> <edge id="3" source="2" target="1"/> <edge id="4" source="0" target="3"/> </edges> </graph> </gexf> """ cls.attribute_graph = nx.DiGraph() cls.attribute_graph.graph["node_default"] = {"frog": True} cls.attribute_graph.add_node( "0", label="Gephi", url="https://gephi.org", indegree=1, frog=False ) cls.attribute_graph.add_node( "1", label="Webatlas", url="http://webatlas.fr", indegree=2, frog=False ) cls.attribute_graph.add_node( "2", label="RTGI", url="http://rtgi.fr", indegree=1, frog=True ) cls.attribute_graph.add_node( "3", label="BarabasiLab", url="http://barabasilab.com", indegree=1, frog=True, ) cls.attribute_graph.add_edge("0", "1", id="0", label="foo") cls.attribute_graph.add_edge("0", "2", id="1") cls.attribute_graph.add_edge("1", "0", id="2") cls.attribute_graph.add_edge("2", "1", id="3") cls.attribute_graph.add_edge("0", "3", id="4") cls.attribute_fh = io.BytesIO(cls.attribute_data.encode("UTF-8")) cls.simple_undirected_data = """<?xml version="1.0" encoding="UTF-8"?> <gexf xmlns="http://www.gexf.net/1.2draft" version="1.2"> <graph mode="static" defaultedgetype="undirected"> <nodes> <node id="0" label="Hello" /> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1" /> </edges> </graph> </gexf> """ cls.simple_undirected_graph = nx.Graph() cls.simple_undirected_graph.add_node("0", label="Hello") cls.simple_undirected_graph.add_node("1", label="World") cls.simple_undirected_graph.add_edge("0", "1", id="0") cls.simple_undirected_fh = io.BytesIO( cls.simple_undirected_data.encode("UTF-8") ) def test_read_simple_directed_graphml(self): G = self.simple_directed_graph H = nx.read_gexf(self.simple_directed_fh) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(G.edges()) == sorted(H.edges()) assert sorted(G.edges(data=True)) == sorted(H.edges(data=True)) self.simple_directed_fh.seek(0) def test_write_read_simple_directed_graphml(self): G = self.simple_directed_graph fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(G.edges()) == sorted(H.edges()) assert sorted(G.edges(data=True)) == sorted(H.edges(data=True)) self.simple_directed_fh.seek(0) def test_read_simple_undirected_graphml(self): G = self.simple_undirected_graph H = nx.read_gexf(self.simple_undirected_fh) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() ) self.simple_undirected_fh.seek(0) def test_read_attribute_graphml(self): G = self.attribute_graph H = nx.read_gexf(self.attribute_fh) assert sorted(G.nodes(True)) == sorted(H.nodes(data=True)) ge = sorted(G.edges(data=True)) he = sorted(H.edges(data=True)) for a, b in zip(ge, he): assert a == b self.attribute_fh.seek(0) def test_directed_edge_in_undirected(self): s = """<?xml version="1.0" encoding="UTF-8"?> <gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'> <graph mode="static" defaultedgetype="undirected" name=""> <nodes> <node id="0" label="Hello" /> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1" type="directed"/> </edges> </graph> </gexf> """ fh = io.BytesIO(s.encode("UTF-8")) pytest.raises(nx.NetworkXError, nx.read_gexf, fh) def test_undirected_edge_in_directed(self): s = """<?xml version="1.0" encoding="UTF-8"?> <gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'> <graph mode="static" defaultedgetype="directed" name=""> <nodes> <node id="0" label="Hello" /> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1" type="undirected"/> </edges> </graph> </gexf> """ fh = io.BytesIO(s.encode("UTF-8")) pytest.raises(nx.NetworkXError, nx.read_gexf, fh) def test_key_raises(self): s = """<?xml version="1.0" encoding="UTF-8"?> <gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'> <graph mode="static" defaultedgetype="directed" name=""> <nodes> <node id="0" label="Hello"> <attvalues> <attvalue for='0' value='1'/> </attvalues> </node> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1" type="undirected"/> </edges> </graph> </gexf> """ fh = io.BytesIO(s.encode("UTF-8")) pytest.raises(nx.NetworkXError, nx.read_gexf, fh) def test_relabel(self): s = """<?xml version="1.0" encoding="UTF-8"?> <gexf xmlns="http://www.gexf.net/1.2draft" version='1.2'> <graph mode="static" defaultedgetype="directed" name=""> <nodes> <node id="0" label="Hello" /> <node id="1" label="Word" /> </nodes> <edges> <edge id="0" source="0" target="1"/> </edges> </graph> </gexf> """ fh = io.BytesIO(s.encode("UTF-8")) G = nx.read_gexf(fh, relabel=True) assert sorted(G.nodes()) == ["Hello", "Word"] def test_default_attribute(self): G = nx.Graph() G.add_node(1, label="1", color="green") nx.add_path(G, [0, 1, 2, 3]) G.add_edge(1, 2, foo=3) G.graph["node_default"] = {"color": "yellow"} G.graph["edge_default"] = {"foo": 7} fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() ) # Reading a gexf graph always sets mode attribute to either # 'static' or 'dynamic'. Remove the mode attribute from the # read graph for the sake of comparing remaining attributes. del H.graph["mode"] assert G.graph == H.graph def test_serialize_ints_to_strings(self): G = nx.Graph() G.add_node(1, id=7, label=77) fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert list(H) == [7] assert H.nodes[7]["label"] == "77" def test_write_with_node_attributes(self): # Addresses #673. G = nx.Graph() G.add_edges_from([(0, 1), (1, 2), (2, 3)]) for i in range(4): G.nodes[i]["id"] = i G.nodes[i]["label"] = i G.nodes[i]["pid"] = i G.nodes[i]["start"] = i G.nodes[i]["end"] = i + 1 expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi\ ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=\ "http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/\ gexf.xsd" version="1.2"> <meta lastmodifieddate="{time.strftime("%Y-%m-%d")}"> <creator>NetworkX {nx.__version__}</creator> </meta> <graph defaultedgetype="undirected" mode="dynamic" name="" timeformat="long"> <nodes> <node id="0" label="0" pid="0" start="0" end="1" /> <node id="1" label="1" pid="1" start="1" end="2" /> <node id="2" label="2" pid="2" start="2" end="3" /> <node id="3" label="3" pid="3" start="3" end="4" /> </nodes> <edges> <edge source="0" target="1" id="0" /> <edge source="1" target="2" id="1" /> <edge source="2" target="3" id="2" /> </edges> </graph> </gexf>""" obtained = "\n".join(nx.generate_gexf(G)) assert expected == obtained def test_edge_id_construct(self): G = nx.Graph() G.add_edges_from([(0, 1, {"id": 0}), (1, 2, {"id": 2}), (2, 3)]) expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi\ ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.\ gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd" version="1.2"> <meta lastmodifieddate="{time.strftime("%Y-%m-%d")}"> <creator>NetworkX {nx.__version__}</creator> </meta> <graph defaultedgetype="undirected" mode="static" name=""> <nodes> <node id="0" label="0" /> <node id="1" label="1" /> <node id="2" label="2" /> <node id="3" label="3" /> </nodes> <edges> <edge source="0" target="1" id="0" /> <edge source="1" target="2" id="2" /> <edge source="2" target="3" id="1" /> </edges> </graph> </gexf>""" obtained = "\n".join(nx.generate_gexf(G)) assert expected == obtained def test_numpy_type(self): np = pytest.importorskip("numpy") G = nx.path_graph(4) nx.set_node_attributes(G, {n: n for n in np.arange(4)}, "number") G[0][1]["edge-number"] = np.float64(1.1) expected = f"""<gexf xmlns="http://www.gexf.net/1.2draft"\ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation\ ="http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd"\ version="1.2"> <meta lastmodifieddate="{time.strftime("%Y-%m-%d")}"> <creator>NetworkX {nx.__version__}</creator> </meta> <graph defaultedgetype="undirected" mode="static" name=""> <attributes mode="static" class="edge"> <attribute id="1" title="edge-number" type="float" /> </attributes> <attributes mode="static" class="node"> <attribute id="0" title="number" type="int" /> </attributes> <nodes> <node id="0" label="0"> <attvalues> <attvalue for="0" value="0" /> </attvalues> </node> <node id="1" label="1"> <attvalues> <attvalue for="0" value="1" /> </attvalues> </node> <node id="2" label="2"> <attvalues> <attvalue for="0" value="2" /> </attvalues> </node> <node id="3" label="3"> <attvalues> <attvalue for="0" value="3" /> </attvalues> </node> </nodes> <edges> <edge source="0" target="1" id="0"> <attvalues> <attvalue for="1" value="1.1" /> </attvalues> </edge> <edge source="1" target="2" id="1" /> <edge source="2" target="3" id="2" /> </edges> </graph> </gexf>""" obtained = "\n".join(nx.generate_gexf(G)) assert expected == obtained def test_bool(self): G = nx.Graph() G.add_node(1, testattr=True) fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert H.nodes[1]["testattr"] # Test for NaN, INF and -INF def test_specials(self): from math import isnan inf, nan = float("inf"), float("nan") G = nx.Graph() G.add_node(1, testattr=inf, strdata="inf", key="a") G.add_node(2, testattr=nan, strdata="nan", key="b") G.add_node(3, testattr=-inf, strdata="-inf", key="c") fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) filetext = fh.read() fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert b"INF" in filetext assert b"NaN" in filetext assert b"-INF" in filetext assert H.nodes[1]["testattr"] == inf assert isnan(H.nodes[2]["testattr"]) assert H.nodes[3]["testattr"] == -inf assert H.nodes[1]["strdata"] == "inf" assert H.nodes[2]["strdata"] == "nan" assert H.nodes[3]["strdata"] == "-inf" assert H.nodes[1]["networkx_key"] == "a" assert H.nodes[2]["networkx_key"] == "b" assert H.nodes[3]["networkx_key"] == "c" def test_simple_list(self): G = nx.Graph() list_value = [(1, 2, 3), (9, 1, 2)] G.add_node(1, key=list_value) fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert H.nodes[1]["networkx_key"] == list_value def test_dynamic_mode(self): G = nx.Graph() G.add_node(1, label="1", color="green") G.graph["mode"] = "dynamic" fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() ) def test_multigraph_with_missing_attributes(self): G = nx.MultiGraph() G.add_node(0, label="1", color="green") G.add_node(1, label="2", color="green") G.add_edge(0, 1, id="0", weight=3, type="undirected", start=0, end=1) G.add_edge(0, 1, id="1", label="foo", start=0, end=1) G.add_edge(0, 1) fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() ) def test_missing_viz_attributes(self): G = nx.Graph() G.add_node(0, label="1", color="green") G.nodes[0]["viz"] = {"size": 54} G.nodes[0]["viz"]["position"] = {"x": 0, "y": 1, "z": 0} G.nodes[0]["viz"]["color"] = {"r": 0, "g": 0, "b": 256} G.nodes[0]["viz"]["shape"] = "http://random.url" G.nodes[0]["viz"]["thickness"] = 2 fh = io.BytesIO() nx.write_gexf(G, fh, version="1.1draft") fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() ) # Test missing alpha value for version >draft1.1 - set default alpha value # to 1.0 instead of `None` when writing for better general compatibility fh = io.BytesIO() # G.nodes[0]["viz"]["color"] does not have an alpha value explicitly defined # so the default is used instead nx.write_gexf(G, fh, version="1.2draft") fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert H.nodes[0]["viz"]["color"]["a"] == 1.0 # Second graph for the other branch G = nx.Graph() G.add_node(0, label="1", color="green") G.nodes[0]["viz"] = {"size": 54} G.nodes[0]["viz"]["position"] = {"x": 0, "y": 1, "z": 0} G.nodes[0]["viz"]["color"] = {"r": 0, "g": 0, "b": 256, "a": 0.5} G.nodes[0]["viz"]["shape"] = "ftp://random.url" G.nodes[0]["viz"]["thickness"] = 2 fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() ) def test_slice_and_spell(self): # Test spell first, so version = 1.2 G = nx.Graph() G.add_node(0, label="1", color="green") G.nodes[0]["spells"] = [(1, 2)] fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() ) G = nx.Graph() G.add_node(0, label="1", color="green") G.nodes[0]["slices"] = [(1, 2)] fh = io.BytesIO() nx.write_gexf(G, fh, version="1.1draft") fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() ) def test_add_parent(self): G = nx.Graph() G.add_node(0, label="1", color="green", parents=[1, 2]) fh = io.BytesIO() nx.write_gexf(G, fh) fh.seek(0) H = nx.read_gexf(fh, node_type=int) assert sorted(G.nodes()) == sorted(H.nodes()) assert sorted(sorted(e) for e in G.edges()) == sorted( sorted(e) for e in H.edges() )
TestGEXF
python
pytorch__pytorch
test/inductor/extension_backends/cpp/extension_codegen_backend.py
{ "start": 459, "end": 1130 }
class ____(BaseScheduling): def __init__(self, scheduler): super().__init__(scheduler) self._scheduling = cpp.CppScheduling(scheduler) def can_fuse_vertical(self, node1, node2): return True def can_fuse_horizontal(self, node1, node2): return True def group_fn(self, sizes): return tuple(tuple(map(V.graph.sizevars.simplify, s)) for s in sizes) def codegen_template(self, template_node, epilogue_nodes): pass def codegen_node(self, node): self._scheduling.codegen_node(node) def codegen_sync(self): pass def flush(self): self._scheduling.flush()
ExtensionScheduling
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/engine/interfaces.py
{ "start": 15718, "end": 18041 }
class ____(Enum): """Define different methods of passing typing information for bound parameters in a statement to the database driver. .. versionadded:: 2.0 """ NONE = 1 """No steps are taken to pass typing information to the database driver. This is the default behavior for databases such as SQLite, MySQL / MariaDB, SQL Server. """ SETINPUTSIZES = 2 """Use the pep-249 setinputsizes method. This is only implemented for DBAPIs that support this method and for which the SQLAlchemy dialect has the appropriate infrastructure for that dialect set up. Current dialects include python-oracledb, cx_Oracle as well as optional support for SQL Server using pyodbc. When using setinputsizes, dialects also have a means of only using the method for certain datatypes using include/exclude lists. When SETINPUTSIZES is used, the :meth:`.Dialect.do_set_input_sizes` method is called for each statement executed which has bound parameters. """ RENDER_CASTS = 3 """Render casts or other directives in the SQL string. This method is used for all PostgreSQL dialects, including asyncpg, pg8000, psycopg, psycopg2. Dialects which implement this can choose which kinds of datatypes are explicitly cast in SQL statements and which aren't. When RENDER_CASTS is used, the compiler will invoke the :meth:`.SQLCompiler.render_bind_cast` method for the rendered string representation of each :class:`.BindParameter` object whose dialect-level type sets the :attr:`.TypeEngine.render_bind_cast` attribute. The :meth:`.SQLCompiler.render_bind_cast` is also used to render casts for one form of "insertmanyvalues" query, when both :attr:`.InsertmanyvaluesSentinelOpts.USE_INSERT_FROM_SELECT` and :attr:`.InsertmanyvaluesSentinelOpts.RENDER_SELECT_COL_CASTS` are set, where the casts are applied to the intermediary columns e.g. "INSERT INTO t (a, b, c) SELECT p0::TYP, p1::TYP, p2::TYP " "FROM (VALUES (?, ?), (?, ?), ...)". .. versionadded:: 2.0.10 - :meth:`.SQLCompiler.render_bind_cast` is now used within some elements of the "insertmanyvalues" implementation. """ VersionInfoType = Tuple[Union[int, str], ...] TableKey = Tuple[Optional[str], str]
BindTyping
python
dagster-io__dagster
python_modules/libraries/dagster-docker/dagster_docker/docker_run_launcher.py
{ "start": 862, "end": 8458 }
class ____(RunLauncher, ConfigurableClass): """Launches runs in a Docker container.""" def __init__( self, inst_data: Optional[ConfigurableClassData] = None, image=None, registry=None, env_vars=None, network=None, networks=None, container_kwargs=None, ): self._inst_data = inst_data self.image = image self.registry = registry self.env_vars = env_vars validate_docker_config(network, networks, container_kwargs) if network: self.networks = [network] elif networks: self.networks = networks else: self.networks = [] self.container_kwargs = check.opt_dict_param( container_kwargs, "container_kwargs", key_type=str ) super().__init__() @property def inst_data(self): return self._inst_data @classmethod def config_type(cls): return DOCKER_CONFIG_SCHEMA @classmethod def from_config_value( cls, inst_data: ConfigurableClassData, config_value: Mapping[str, Any] ) -> Self: return cls(inst_data=inst_data, **config_value) def get_container_context(self, dagster_run: DagsterRun) -> DockerContainerContext: return DockerContainerContext.create_for_run(dagster_run, self) def _get_client(self, container_context: DockerContainerContext): client = docker.client.from_env() if container_context.registry: client.login( registry=container_context.registry["url"], username=container_context.registry["username"], password=container_context.registry["password"], ) return client def _get_docker_image(self, job_code_origin): docker_image = job_code_origin.repository_origin.container_image if not docker_image: docker_image = self.image if not docker_image: raise Exception("No docker image specified by the instance config or repository") validate_docker_image(docker_image) return docker_image def _launch_container_with_command(self, run, docker_image, command): container_context = self.get_container_context(run) docker_env = dict([parse_env_var(env_var) for env_var in container_context.env_vars]) docker_env["DAGSTER_RUN_JOB_NAME"] = run.job_name client = self._get_client(container_context) container_kwargs = {**container_context.container_kwargs} labels = container_kwargs.pop("labels", {}) container_kwargs.pop("stop_timeout", None) if isinstance(labels, list): labels = {key: "" for key in labels} labels["dagster/run_id"] = run.run_id labels["dagster/job_name"] = run.job_name try: container = client.containers.create( image=docker_image, command=command, detach=True, environment=docker_env, network=container_context.networks[0] if len(container_context.networks) else None, labels=labels, **container_kwargs, ) except docker.errors.ImageNotFound: # pyright: ignore[reportAttributeAccessIssue] client.images.pull(docker_image) container = client.containers.create( image=docker_image, command=command, detach=True, environment=docker_env, network=container_context.networks[0] if len(container_context.networks) else None, labels=labels, **container_kwargs, ) if len(container_context.networks) > 1: for network_name in container_context.networks[1:]: network = client.networks.get(network_name) network.connect(container) self._instance.report_engine_event( message=f"Launching run in a new container {container.id} with image {docker_image}", dagster_run=run, cls=self.__class__, ) self._instance.add_run_tags( run.run_id, {DOCKER_CONTAINER_ID_TAG: container.id, DOCKER_IMAGE_TAG: docker_image}, # pyright: ignore[reportArgumentType] ) container.start() def launch_run(self, context: LaunchRunContext) -> None: run = context.dagster_run job_code_origin = check.not_none(context.job_code_origin) docker_image = self._get_docker_image(job_code_origin) command = ExecuteRunArgs( job_origin=job_code_origin, run_id=run.run_id, instance_ref=self._instance.get_ref(), ).get_command_args() self._launch_container_with_command(run, docker_image, command) @property def supports_resume_run(self): return True def resume_run(self, context: ResumeRunContext) -> None: run = context.dagster_run job_code_origin = check.not_none(context.job_code_origin) docker_image = self._get_docker_image(job_code_origin) command = ResumeRunArgs( job_origin=job_code_origin, run_id=run.run_id, instance_ref=self._instance.get_ref(), ).get_command_args() self._launch_container_with_command(run, docker_image, command) def _get_container(self, run): if not run: return None container_id = run.tags.get(DOCKER_CONTAINER_ID_TAG) if not container_id: return None container_context = self.get_container_context(run) try: return self._get_client(container_context).containers.get(container_id) except docker.errors.NotFound: # pyright: ignore[reportAttributeAccessIssue] return None def terminate(self, run_id): run = self._instance.get_run_by_id(run_id) if not run or run.is_finished: return False self._instance.report_run_canceling(run) container = self._get_container(run) container_context = self.get_container_context(run) stop_timeout = container_context.container_kwargs.get("stop_timeout") if not container: self._instance.report_engine_event( message="Unable to get docker container to send termination request to.", dagster_run=run, cls=self.__class__, ) return False container.stop(timeout=stop_timeout) return True @property def supports_check_run_worker_health(self): return True def check_run_worker_health(self, run: DagsterRun): container_id = run.tags.get(DOCKER_CONTAINER_ID_TAG) if not container_id: return CheckRunHealthResult(WorkerStatus.NOT_FOUND, msg="No container ID tag for run.") container = self._get_container(run) if container is None: return CheckRunHealthResult( WorkerStatus.NOT_FOUND, msg=f"Could not find container with ID {container_id}." ) if container.status == "running": return CheckRunHealthResult(WorkerStatus.RUNNING) container_state = container.attrs.get("State") failure_string = f"Container status is {container.status}." + ( f" Container state: {json.dumps(container_state)}" if container_state else "" ) return CheckRunHealthResult(WorkerStatus.FAILED, msg=failure_string)
DockerRunLauncher
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-deepset/unit_tests/test_util.py
{ "start": 348, "end": 4194 }
class ____(BaseModel): simple: Simple adjacent: bool @pytest.mark.parametrize( ("obj", "key_path", "expected"), [ ({}, "a.b", None), # default fallback value is None ({"a": {"b": 5}}, "a.b", 5), ({"a": {"b": 5}}, "a.b.c", None), # fallback # Should work for Pydantic models too (Simple(name="Jack"), "name", "Jack"), (Simple(name="Jack"), "name.last", None), # fallback (Nested(simple=Simple(name="Jack"), adjacent=False), "adjacent", False), (Nested(simple=Simple(name="Jack"), adjacent=False), "simple.name", "Jack"), ], ) def test_get(obj: Any, key_path: str, expected: Any) -> None: assert util.get(obj=obj, key_path=key_path) == expected def test_get_ignores_fallback_value_if_match_found() -> None: fallback = "I Fall Back" obj = {"a": {"b": {"c": "I Don't Fall Back"}}} assert util.get(obj=obj, key_path="a.b.c", default=fallback) != fallback assert util.get(obj=obj, key_path="a.b.c", default=fallback) == "I Don't Fall Back" def test_get_returns_fallback_value_if_no_match_found() -> None: fallback = "I Fall Back" assert util.get(obj={}, key_path="a.b.c", default=fallback) == fallback @pytest.mark.parametrize( ("message", "exception", "expected"), [ ("Hello", None, ("Hello", None)), ("Hello", Exception("World"), ("Hello", "World")), ], ) def test_get_trace_message(message: str, exception: Exception | None, expected: tuple[str, str | None]) -> None: error_message, internal_error_message = expected airbyte_message = util.get_trace_message(message, exception=exception) assert isinstance(airbyte_message, AirbyteMessage) assert airbyte_message.type == Type.TRACE assert airbyte_message.trace.type == TraceType.ERROR assert airbyte_message.trace.error.message == error_message assert airbyte_message.trace.error.internal_message == internal_error_message assert airbyte_message.trace.error.failure_type == FailureType.transient_error.value def test_get_log_message() -> None: log_message = "Hello, World!" airbyte_message = util.get_log_message(log_message) assert isinstance(airbyte_message, AirbyteMessage) assert airbyte_message.type == Type.LOG assert airbyte_message.log.level == Level.INFO assert airbyte_message.log.message == log_message assert airbyte_message.log.stack_trace is None @pytest.mark.parametrize( ("destination_sync_mode", "write_mode"), [ (DestinationSyncMode.append, "FAIL"), (DestinationSyncMode.append_dedup, "KEEP"), (DestinationSyncMode.overwrite, "OVERWRITE"), ], ) def test_get_file_write_mode(destination_sync_mode: DestinationSyncMode, write_mode: str) -> None: assert util.get_file_write_mode(destination_sync_mode) == write_mode @pytest.mark.parametrize( ("document_key", "stream", "namespace", "expected"), [ ("testdoc_pdf.pdf", "unstructured", None, "unstructured_testdoc_pdf.pdf"), ("testdoc_pdf.pdf", "unstructured", "docs", "unstructured_docs_testdoc_pdf.pdf"), ( "https://airbyte179.sharepoint.com/Shared%20Documents/Test_folder/Test_foler_2_1/simple_pdf_file.pdf", "unstructured", "docs", "unstructured_docs_Shared-Documents_Test_folder_Test_foler_2_1_simple_pdf_file.pdf", ), ( "https://airbyte179.sharepoint.com/Shared%20Documents/Test_folder/Test_foler_2_1/simple_pdf_file.pdf", "unstructured", "", "unstructured_Shared-Documents_Test_folder_Test_foler_2_1_simple_pdf_file.pdf", ), ], ) def test_generate_name(document_key: str, stream: str | None, namespace: str | None, expected: str) -> None: assert util.generate_name(document_key, stream, namespace) == expected
Nested
python
crytic__slither
slither/detectors/operations/encode_packed.py
{ "start": 1752, "end": 3691 }
class ____(AbstractDetector): """ Detect usage of more than one dynamic type in abi.encodePacked() arguments which could to collision """ ARGUMENT = "encode-packed-collision" HELP = "ABI encodePacked Collision" IMPACT = DetectorClassification.HIGH CONFIDENCE = DetectorClassification.HIGH WIKI = ( "https://github.com/crytic/slither/wiki/Detector-Documentation#abi-encodePacked-collision" ) WIKI_TITLE = "ABI encodePacked Collision" WIKI_DESCRIPTION = """Detect collision due to dynamic type usages in `abi.encodePacked`""" WIKI_EXPLOIT_SCENARIO = """ ```solidity contract Sign { function get_hash_for_signature(string name, string doc) external returns(bytes32) { return keccak256(abi.encodePacked(name, doc)); } } ``` Bob calls `get_hash_for_signature` with (`bob`, `This is the content`). The hash returned is used as an ID. Eve creates a collision with the ID using (`bo`, `bThis is the content`) and compromises the system. """ WIKI_RECOMMENDATION = """Do not use more than one dynamic type in `abi.encodePacked()` (see the [Solidity documentation](https://solidity.readthedocs.io/en/v0.5.10/abi-spec.html?highlight=abi.encodePacked#non-standard-packed-modeDynamic)). Use `abi.encode()`, preferably.""" def _detect(self): """Detect usage of more than one dynamic type in abi.encodePacked(..) arguments which could lead to collision""" results = [] for c in self.compilation_unit.contracts: values = _detect_abi_encodePacked_collision(c) for func, node in values: info = [ func, " calls abi.encodePacked() with multiple dynamic arguments:\n\t- ", node, "\n", ] json = self.generate_result(info) results.append(json) return results
EncodePackedCollision