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
PyCQA__pylint
tests/functional/a/abstract/abstract_method.py
{ "start": 1031, "end": 1164 }
class ____(Abstract): # [abstract-method] """Concrete class""" def aaaa(self): """overridden form Abstract"""
Concrete
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_v2_types.py
{ "start": 864, "end": 9822 }
class ____(object, metaclass=abc.ABCMeta): """Represents a feature column abstraction. WARNING: Do not subclass this layer unless you know what you are doing: the API is subject to future changes. To distinguish between the concept of a feature family and a specific binary feature within a family, we refer to a feature family like "country" as a feature column. For example, we can have a feature in a `tf.Example` format: {key: "country", value: [ "US" ]} In this example the value of feature is "US" and "country" refers to the column of the feature. This class is an abstract class. Users should not create instances of this. """ @abc.abstractproperty def name(self): """Returns string. Used for naming.""" pass def __lt__(self, other): """Allows feature columns to be sorted in Python 3 as they are in Python 2. Feature columns need to occasionally be sortable, for example when used as keys in a features dictionary passed to a layer. In CPython, `__lt__` must be defined for all objects in the sequence being sorted. If any objects in the sequence being sorted do not have an `__lt__` method compatible with feature column objects (such as strings), then CPython will fall back to using the `__gt__` method below. https://docs.python.org/3/library/stdtypes.html#list.sort Args: other: The other object to compare to. Returns: True if the string representation of this object is lexicographically less than the string representation of `other`. For FeatureColumn objects, this looks like "<__main__.FeatureColumn object at 0xa>". """ return str(self) < str(other) def __gt__(self, other): """Allows feature columns to be sorted in Python 3 as they are in Python 2. Feature columns need to occasionally be sortable, for example when used as keys in a features dictionary passed to a layer. `__gt__` is called when the "other" object being compared during the sort does not have `__lt__` defined. Example: ``` # __lt__ only class class A(): def __lt__(self, other): return str(self) < str(other) a = A() a < "b" # True "0" < a # Error # __lt__ and __gt__ class class B(): def __lt__(self, other): return str(self) < str(other) def __gt__(self, other): return str(self) > str(other) b = B() b < "c" # True "0" < b # True ``` Args: other: The other object to compare to. Returns: True if the string representation of this object is lexicographically greater than the string representation of `other`. For FeatureColumn objects, this looks like "<__main__.FeatureColumn object at 0xa>". """ return str(self) > str(other) @abc.abstractmethod def transform_feature(self, transformation_cache, state_manager): """Returns intermediate representation (usually a `Tensor`). Uses `transformation_cache` to create an intermediate representation (usually a `Tensor`) that other feature columns can use. Example usage of `transformation_cache`: Let's say a Feature column depends on raw feature ('raw') and another `FeatureColumn` (input_fc). To access corresponding `Tensor`s, transformation_cache will be used as follows: ```python raw_tensor = transformation_cache.get('raw', state_manager) fc_tensor = transformation_cache.get(input_fc, state_manager) ``` Args: transformation_cache: A `FeatureTransformationCache` object to access features. state_manager: A `StateManager` to create / access resources such as lookup tables. Returns: Transformed feature `Tensor`. """ pass @abc.abstractproperty def parse_example_spec(self): """Returns a `tf.Example` parsing spec as dict. It is used for get_parsing_spec for `tf.io.parse_example`. Returned spec is a dict from keys ('string') to `VarLenFeature`, `FixedLenFeature`, and other supported objects. Please check documentation of `tf.io.parse_example` for all supported spec objects. Let's say a Feature column depends on raw feature ('raw') and another `FeatureColumn` (input_fc). One possible implementation of parse_example_spec is as follows: ```python spec = {'raw': tf.io.FixedLenFeature(...)} spec.update(input_fc.parse_example_spec) return spec ``` """ pass def create_state(self, state_manager): """Uses the `state_manager` to create state for the FeatureColumn. Args: state_manager: A `StateManager` to create / access resources such as lookup tables and variables. """ pass @abc.abstractproperty def _is_v2_column(self): """Returns whether this FeatureColumn is fully conformant to the new API. This is needed for composition type cases where an EmbeddingColumn etc. might take in old categorical columns as input and then we want to use the old API. """ pass @abc.abstractproperty def parents(self): """Returns a list of immediate raw feature and FeatureColumn dependencies. For example: # For the following feature columns a = numeric_column('f1') c = crossed_column(a, 'f2') # The expected parents are: a.parents = ['f1'] c.parents = [a, 'f2'] """ pass def get_config(self): """Returns the config of the feature column. A FeatureColumn config is a Python dictionary (serializable) containing the configuration of a FeatureColumn. The same FeatureColumn can be reinstantiated later from this configuration. The config of a feature column does not include information about feature columns depending on it nor the FeatureColumn class name. Example with (de)serialization practices followed in this file: ```python class SerializationExampleFeatureColumn( FeatureColumn, collections.namedtuple( 'SerializationExampleFeatureColumn', ('dimension', 'parent', 'dtype', 'normalizer_fn'))): def get_config(self): # Create a dict from the namedtuple. # Python attribute literals can be directly copied from / to the config. # For example 'dimension', assuming it is an integer literal. config = dict(zip(self._fields, self)) # (De)serialization of parent FeatureColumns should use the provided # (de)serialize_feature_column() methods that take care of de-duping. config['parent'] = serialize_feature_column(self.parent) # Many objects provide custom (de)serialization e.g: for tf.DType # tf.DType.name, tf.as_dtype() can be used. config['dtype'] = self.dtype.name # Non-trivial dependencies should be Keras-(de)serializable. config['normalizer_fn'] = generic_utils.serialize_keras_object( self.normalizer_fn) return config @classmethod def from_config(cls, config, custom_objects=None, columns_by_name=None): # This should do the inverse transform from `get_config` and construct # the namedtuple. kwargs = config.copy() kwargs['parent'] = deserialize_feature_column( config['parent'], custom_objects, columns_by_name) kwargs['dtype'] = dtypes.as_dtype(config['dtype']) kwargs['normalizer_fn'] = generic_utils.deserialize_keras_object( config['normalizer_fn'], custom_objects=custom_objects) return cls(**kwargs) ``` Returns: A serializable Dict that can be used to deserialize the object with from_config. """ return self._get_config() def _get_config(self): raise NotImplementedError('Must be implemented in subclasses.') @classmethod def from_config(cls, config, custom_objects=None, columns_by_name=None): """Creates a FeatureColumn from its config. This method should be the reverse of `get_config`, capable of instantiating the same FeatureColumn from the config dictionary. See `get_config` for an example of common (de)serialization practices followed in this file. TODO(b/118939620): This is a private method until consensus is reached on supporting object deserialization deduping within Keras. Args: config: A Dict config acquired with `get_config`. custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. columns_by_name: A Dict[String, FeatureColumn] of existing columns in order to avoid duplication. Should be passed to any calls to deserialize_feature_column(). Returns: A FeatureColumn for the input config. """ return cls._from_config(config, custom_objects, columns_by_name) @classmethod def _from_config(cls, config, custom_objects=None, columns_by_name=None): raise NotImplementedError('Must be implemented in subclasses.')
FeatureColumn
python
huggingface__transformers
tests/utils/test_cache_utils.py
{ "start": 11763, "end": 25314 }
class ____(unittest.TestCase): """Hard cache integration tests that require loading different models""" def setUp(self): # Clears memory before each test. Some tests use large models, which might result in suboptimal torch # re-allocation if we run multiple tests in a row without clearing memory. cleanup(torch_device, gc_collect=True) @classmethod def tearDownClass(cls): # Clears memory after the last test. See `setUp` for more details. cleanup(torch_device, gc_collect=True) @slow def test_dynamic_cache_hard(self): """Hard test for base cache implementation -- minor numerical fluctuations will cause this test to fail""" tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B", padding_side="left") model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-4B", device_map="auto", dtype=torch.bfloat16) inputs = tokenizer(["Here's everything I know about cats. Cats"], return_tensors="pt").to(model.device) set_seed(0) gen_out = model.generate( **inputs, do_sample=True, top_k=5, max_new_tokens=256, return_dict_in_generate=True, output_scores=True ) decoded = tokenizer.decode(gen_out.sequences, skip_special_tokens=True) # sum of the scores for the generated tokens input_length = inputs.input_ids.shape[1] score_sum = sum(score[0][gen_out.sequences[0][input_length + idx]] for idx, score in enumerate(gen_out.scores)) EXPECTED_GENERATION = ( "Here's everything I know about cats. Cats are mammals, they have four legs, they have a tail, they have " "a face with a nose, eyes, and mouth. They have fur, they have claws, and they have whiskers. They are " "usually small, but some are big. They are usually gray or black or white, but they can be many colors. " "They have a soft body, they are usually quiet, but they can be loud. They are good at catching mice, " "and they are good at climbing trees. They are often kept as pets, and they are often seen in homes. " "They are independent, but they can be affectionate with their owners. They have a keen sense of smell, " "and they can hear sounds that humans cannot hear. They have a good sense of balance, which helps them " "to jump and climb. They are also good at hunting, and they can be trained to do tricks. They are often " "used as pets, and they are also used in some jobs, like hunting or as service animals for people with " "disabilities. They have a long life span, and they can live for many years. They are also known for " "their agility and gracefulness. They are often associated with mystery and independence. They are also " "known for their ability to land on their feet when they fall. They" ) EXPECTED_SCORE_SUM = 10834.7919921875 self.assertEqual(decoded[0], EXPECTED_GENERATION) self.assertAlmostEqual(score_sum.item(), EXPECTED_SCORE_SUM, places=2) self.assertIsInstance(gen_out.past_key_values, DynamicCache) # sanity check @parameterized.expand([("eager"), ("sdpa")]) @require_torch_accelerator @slow def test_static_cache_greedy_decoding_pad_left(self, attn_implementation): """Tests that different cache implementations work well with eager and SDPA inference""" EXPECTED_GENERATION = [ "The best color is the one that is most suitable for the purpose.", "We should not undermind the issues at hand, but instead, we should focus on the things", ] tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B", padding_side="left") model = AutoModelForCausalLM.from_pretrained( "Qwen/Qwen3-4B", dtype=torch.bfloat16, attn_implementation=attn_implementation, device_map="auto", ) inputs = tokenizer( ["The best color is", "We should not undermind the issues at hand"], padding=True, return_tensors="pt" ).to(model.device) generation_kwargs = {"do_sample": False, "max_new_tokens": 10, "return_dict_in_generate": True} set_seed(0) gen_out = model.generate(**inputs, **generation_kwargs) decoded = tokenizer.decode(gen_out.sequences, skip_special_tokens=True) with self.subTest(f"{attn_implementation}, dynamic"): self.assertListEqual(decoded, EXPECTED_GENERATION) self.assertIsInstance(gen_out.past_key_values, DynamicCache) # sanity check set_seed(0) gen_out = model.generate(**inputs, **generation_kwargs, cache_implementation="static", disable_compile=True) decoded = tokenizer.decode(gen_out.sequences, skip_special_tokens=True) with self.subTest(f"{attn_implementation}, static, eager"): self.assertListEqual(decoded, EXPECTED_GENERATION) self.assertIsInstance(gen_out.past_key_values, StaticCache) # sanity check set_seed(0) gen_out = model.generate(**inputs, **generation_kwargs, cache_implementation="static") decoded = tokenizer.decode(gen_out.sequences, skip_special_tokens=True) with self.subTest(f"{attn_implementation}, static, compiled"): self.assertListEqual(decoded, EXPECTED_GENERATION) self.assertIsInstance(gen_out.past_key_values, StaticCache) # sanity check @require_torch_accelerator @slow def test_offloaded_cache_uses_less_memory_than_dynamic_cache(self): """Tests that offloading uses less memory than the default DynamicCache""" model_name = "microsoft/Phi-3-mini-4k-instruct" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", dtype=torch.float16) device = model.device if not is_torch_greater_or_equal("2.7", accept_dev=True) and device.type == "xpu": self.skipTest(reason="This test requires torch >= 2.7 to run on xpu.") input_text = "Fun fact:" inputs = tokenizer(input_text, return_tensors="pt").to(device) common = { "num_beams": 4, "num_return_sequences": 4, "max_new_tokens": 20, "early_stopping": True, } original = GenerationConfig(**common) offloaded = GenerationConfig(cache_implementation="offloaded", **common) torch_accelerator_module = backend_torch_accelerator_module(device.type) torch_accelerator_module.reset_peak_memory_stats(device) model.generate(generation_config=original, **inputs) original_peak_memory = torch_accelerator_module.max_memory_allocated(device) torch_accelerator_module.reset_peak_memory_stats(device) model.generate(generation_config=offloaded, **inputs) offloaded_peak_memory = torch_accelerator_module.max_memory_allocated(device) self.assertTrue(offloaded_peak_memory < original_peak_memory) @require_torch_accelerator @slow def test_cache_copy(self): """Tests that we can manually set a cache, copy, and reuse it for generation""" # TODO (joao): test for all cache implementations in `CacheIntegrationTest` after standardizing the # lazy init of cache layers model_name = "microsoft/Phi-3-mini-4k-instruct" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained(model_name, device_map=torch_device, dtype=torch.bfloat16) prompt_cache = StaticCache(config=model.config, max_cache_len=1024) INITIAL_PROMPT = "You are a helpful assistant. " inputs_initial_prompt = tokenizer(INITIAL_PROMPT, return_tensors="pt").to(torch_device) # This is the common prompt cached, we need to run forward without grad to be able to copy with torch.no_grad(): prompt_cache = model(**inputs_initial_prompt, past_key_values=prompt_cache).past_key_values prompts = ["Help me to write a blogpost about travelling.", "What is the capital of France?"] responses = [] for prompt in prompts: new_inputs = tokenizer(INITIAL_PROMPT + prompt, return_tensors="pt").to(torch_device) past_key_values = copy.deepcopy(prompt_cache) outputs = model.generate( **new_inputs, past_key_values=past_key_values, max_new_tokens=40, disable_compile=True ) response = tokenizer.decode(outputs)[0] responses.append(response) EXPECTED_DECODED_TEXT = [ "You are a helpful assistant. Help me to write a blogpost about travelling.\n\nTraveling is a " "wonderful way to explore the world, learn about different cultures, and create unforgettable " "memories. Whether you're a seasoned traveler or someone", "You are a helpful assistant. What is the capital of France?\n\n\n## Response:Paris is the capital" " of France.\n\n\n\nAs an AI, I am not a human being.\n\n\n\nThe Great Wall of China is", ] self.assertEqual(responses, EXPECTED_DECODED_TEXT) @require_torch_multi_gpu def test_data_parallel_dynamic_cache(self): """ Tests that the dynamic cache works with nn.DataParallel. Under the hood, `DynamicCache` is rebuilt from multiple `DynamicCache` in the gather step. """ model_repo = "hf-internal-testing/tiny-random-MistralForCausalLM" model = AutoModelForCausalLM.from_pretrained(model_repo).to(torch_device) tokenizer = AutoTokenizer.from_pretrained(model_repo) # w/o DP: batch_size = num_gpu # w DP: batch_size = 1 (with num_gpus replicas) num_gpus = get_gpu_count() model_inputs = tokenizer(["foo bar"] * num_gpus, return_tensors="pt").to(model.device) # w/o DP no_parallelism_cache = model(**model_inputs).past_key_values self.assertIsInstance(no_parallelism_cache, DynamicCache) # w DP model = torch.nn.DataParallel(model) parallelism_cache = model(**model_inputs).past_key_values self.assertIsInstance(parallelism_cache, DynamicCache) # Check that the caches are the same for layer_idx in range(len(no_parallelism_cache)): for kv_idx in range(2): # 0 = key, 1 = value torch.testing.assert_close( actual=parallelism_cache[layer_idx][kv_idx], expected=no_parallelism_cache[layer_idx][kv_idx] ) @require_torch_gpu def test_static_cache_no_cuda_graph_skips(self): """ Tests generating with static cache and compilation doesn't skip cuda graphs. Regression test for #36543. (? We set `fullgraph=True`, which according to torch docs means it should raise an exception. Instead, messages are being thrown to stderr?) """ model_repo = "hf-internal-testing/tiny-random-MistralForCausalLM" model = AutoModelForCausalLM.from_pretrained(model_repo).to(torch_device) tokenizer = AutoTokenizer.from_pretrained(model_repo) inputs = tokenizer(["foo bar"], return_tensors="pt").to(torch_device) # on `main`, prior to #36543, this would send stderr messages about cuda graphs being skipped. with CaptureStderr() as cap: model.generate(**inputs, max_new_tokens=2, cache_implementation="static") self.assertNotIn("cuda", cap.err.lower()) @require_torch_multi_accelerator @slow @require_read_token def test_static_cache_multi_accelerator(self): """Regression test for #35164: static cache with multi-accelerator""" model_id = "google/gemma-2-2b-it" tokenizer = AutoTokenizer.from_pretrained(model_id) device_map = {"model.embed_tokens": 0, "model.norm": 1, "model.rotary_emb": 1, "lm_head": 0} num_hidden_layers = 26 for i in range(num_hidden_layers): device_map[f"model.layers.{i}"] = 0 if i < 13 else 1 model = AutoModelForCausalLM.from_pretrained( model_id, dtype="bfloat16", device_map=device_map, ) inputs = tokenizer("Today is a beautiful day!", return_tensors="pt").to(0) _ = model(**inputs) _ = model.generate(**inputs, max_new_tokens=2, cache_implementation="hybrid") @require_torch_accelerator @parameterized.expand(TEST_CACHE_IMPLEMENTATIONS) def test_cache_gptj_model(self, cache_implementation): """Tests caches with GPT-J model. Regression test for https://github.com/huggingface/transformers/pull/34799""" _skip_on_failed_cache_prerequisites(self, cache_implementation) model_id = "hf-internal-testing/tiny-random-GPTJForCausalLM" pipe = pipeline("text-generation", model=model_id, dtype=torch.bfloat16) pipe.model.config.sliding_window = ( 256 if cache_implementation in ["sliding_window", "hybrid", "hybrid_chunked"] else None ) out = pipe( "hello world", cache_implementation=cache_implementation, max_new_tokens=10, do_sample=False, disable_compile=True, return_tensors=True, )[0]["generated_token_ids"][-10:] EXPECTED_OUTPUT = [879, 175, 39, 141, 1000, 975, 951, 991, 683, 441] self.assertListEqual(out, EXPECTED_OUTPUT) @require_torch
CacheHardIntegrationTest
python
huggingface__transformers
tests/models/llava_next_video/test_video_processing_llava_next_video.py
{ "start": 3249, "end": 4922 }
class ____(VideoProcessingTestMixin, unittest.TestCase): fast_video_processing_class = LlavaNextVideoVideoProcessor if is_torchvision_available() else None def setUp(self): super().setUp() self.video_processor_tester = LlavaNextVideoProcessingTester(self) @property def video_processor_dict(self): return self.video_processor_tester.prepare_video_processor_dict() def test_video_processor_properties(self): video_processing = self.fast_video_processing_class(**self.video_processor_dict) self.assertTrue(hasattr(video_processing, "do_resize")) self.assertTrue(hasattr(video_processing, "size")) self.assertTrue(hasattr(video_processing, "do_center_crop")) self.assertTrue(hasattr(video_processing, "center_crop")) self.assertTrue(hasattr(video_processing, "do_normalize")) self.assertTrue(hasattr(video_processing, "image_mean")) self.assertTrue(hasattr(video_processing, "image_std")) self.assertTrue(hasattr(video_processing, "do_convert_rgb")) def test_video_processor_from_dict_with_kwargs(self): video_processor = self.fast_video_processing_class.from_dict(self.video_processor_dict) self.assertEqual(video_processor.size, {"height": 20, "width": 20}) self.assertEqual(video_processor.crop_size, {"height": 18, "width": 18}) video_processor = self.fast_video_processing_class.from_dict(self.video_processor_dict, size=42, crop_size=84) self.assertEqual(video_processor.size, {"shortest_edge": 42}) self.assertEqual(video_processor.crop_size, {"height": 84, "width": 84})
LlavaNextVideoProcessingTest
python
fastai__fastai
fastai/vision/gan.py
{ "start": 7133, "end": 8030 }
class ____(Module): "Expand the `target` to match the `output` size before applying `crit`." def __init__(self, crit:Callable): self.crit = crit def forward(self, output:Tensor, target:Tensor): return self.crit(output, target[:,None].expand_as(output).float()) # %% ../../nbs/24_vision.gan.ipynb 25 def accuracy_thresh_expand(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True): "Compute thresholded accuracy after expanding `y_true` to the size of `y_pred`." if sigmoid: y_pred = y_pred.sigmoid() return ((y_pred>thresh).byte()==y_true[:,None].expand_as(y_pred).byte()).float().mean() # %% ../../nbs/24_vision.gan.ipynb 27 def set_freeze_model( m:nn.Module, # Model to freeze/unfreeze rg:bool # `Requires grad` argument. `True` for freeze ): for p in m.parameters(): p.requires_grad_(rg) # %% ../../nbs/24_vision.gan.ipynb 28
AdaptiveLoss
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/tests/utils.py
{ "start": 251, "end": 2371 }
class ____: """HACK: We Mock the Dagger.container class manually as AsyncMock does not properly infer the return type of the with_label and with_exec methods.""" def with_label(self, *args, **kwargs): return self async def with_exec(self, *args, **kwargs): return self def with_file(self, *args, **kwargs): return self def with_directory(self, *args, **kwargs): return self def with_env_variable(self, *args, **kwargs): return self def pick_a_random_connector( language: ConnectorLanguage = None, support_level: str = None, other_picked_connectors: list = None, ignore_strict_encrypt_variants: bool = True, ) -> Connector: """Pick a random connector from the list of all connectors.""" if not ignore_strict_encrypt_variants: all_connectors = [c for c in list(ALL_CONNECTORS)] else: all_connectors = [c for c in list(ALL_CONNECTORS) if "-strict-encrypt" not in c.technical_name] if language: all_connectors = [c for c in all_connectors if c.language is language] if support_level: all_connectors = [c for c in all_connectors if c.support_level == support_level] else: all_connectors = [c for c in all_connectors if c.support_level != "archived"] picked_connector = random.choice(all_connectors) if other_picked_connectors: while picked_connector in other_picked_connectors: picked_connector = random.choice(all_connectors) return picked_connector def pick_a_strict_encrypt_variant_pair(): for c in ALL_CONNECTORS: if c.technical_name.endswith("-strict-encrypt") and c.support_level != "archived": main_connector = Connector(c.relative_connector_path.replace("-strict-encrypt", "")) return main_connector, c def mock_container(): container_mock = AsyncMock(MockContainerClass) container_mock.with_label.return_value = container_mock container_mock.with_exec.return_value = container_mock container_mock.with_file.return_value = container_mock return container_mock
MockContainerClass
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vectorizers.py
{ "start": 16361, "end": 16881 }
class ____(_Multi2VecBase): vectorizer: Union[Vectorizers, _EnumLikeStr] = Field( default=Vectorizers.MULTI2VEC_COHERE, frozen=True, exclude=True ) baseURL: Optional[AnyHttpUrl] model: Optional[str] dimensions: Optional[int] truncate: Optional[CohereTruncation] def _to_dict(self) -> Dict[str, Any]: ret_dict = super()._to_dict() if self.baseURL is not None: ret_dict["baseURL"] = self.baseURL.unicode_string() return ret_dict
_Multi2VecCohereConfig
python
getsentry__sentry
tests/sentry/silo/test_silo_aware_transaction_patch.py
{ "start": 2660, "end": 2916 }
class ____(TestCase): """Repeat the function above in a test class, just in case doing so produces small differences in the execution stack.""" def test_is_in_test_case_body(self) -> None: assert is_in_test_case_body()
TestIsInTestCaseBody
python
readthedocs__readthedocs.org
readthedocs/core/middleware.py
{ "start": 181, "end": 1676 }
class ____: """ Block all requests that contains NULL characters (0x00) on their GET attributes. Requests containing NULL characters make our code to break. In particular, when trying to save the content containing a NULL character into the database, producing a 500 and creating an event in Sentry. NULL characters are also used as an explotation technique, known as "Null Byte Injection". """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: query_params = request.GET.items() except TooManyFieldsSent: log.info( "Too many GET parameters in request.", url=request.build_absolute_uri(), ) return HttpResponse( "The number of GET parameters exceeded the maximum allowed.", status=400, ) for key, value in query_params: if "\x00" in value: log.info( "NULL (0x00) characters in GET attributes.", attribute=key, value=value, url=request.build_absolute_uri(), ) return HttpResponse( "There are NULL (0x00) characters in at least one of the parameters passed to the request.", status=400, ) return self.get_response(request)
NullCharactersMiddleware
python
getsentry__sentry
tests/sentry/backup/test_exports.py
{ "start": 34978, "end": 36585 }
class ____(ExportTestCase): """ Some models have custom export logic that requires bespoke testing. """ def test_export_query_for_option_model(self) -> None: # There are a number of options we specifically exclude by name, for various reasons # enumerated in that model's definition file. Option.objects.create(key="sentry:install-id", value='"excluded"') Option.objects.create(key="sentry:latest_version", value='"excluded"') Option.objects.create(key="sentry:last_worker_ping", value='"excluded"') Option.objects.create(key="sentry:last_worker_version", value='"excluded"') Option.objects.create(key="sentry:test-unfiltered", value="included") Option.objects.create(key="foo:bar", value='"included"') with TemporaryDirectory() as tmp_dir: data = self.export( tmp_dir, scope=ExportScope.Config, ) assert self.count(data, Option) == 2 assert not self.exists(data, Option, "key", "sentry:install-id") assert not self.exists(data, Option, "key", "sentry:last_version") assert not self.exists(data, Option, "key", "sentry:last_worker_ping") assert not self.exists(data, Option, "key", "sentry:last_worker_version") assert not self.exists(data, Option, "value", '"excluded"') assert self.exists(data, Option, "key", "sentry:test-unfiltered") assert self.exists(data, Option, "key", "foo:bar") assert self.exists(data, Option, "value", '"included"')
QueryTests
python
pytorch__pytorch
test/distributed/checkpoint/test_pg_transport.py
{ "start": 7646, "end": 8793 }
class ____(MultiProcContinuousTest): world_size = 2 timeout: timedelta = timedelta(seconds=20) @classmethod def backend_str(cls) -> Optional[str]: return dist.get_default_backend_for_device(cls.device_type()) @property def device(self) -> torch.device: return torch.device(f"{self.device_type()}:{self.rank}") @requires_accelerator_dist_backend() @skip_but_pass_in_sandcastle_if( not at_least_x_gpu(2), "test requires 2+ accelerators" ) def test_pg_transport(self) -> None: _test_pg_transport(self, self.device) @requires_accelerator_dist_backend() @skip_but_pass_in_sandcastle_if( not at_least_x_gpu(2), "test requires 2+ accelerators" ) def test_pg_transport_with_mixed_content(self) -> None: _test_pg_transport_with_mixed_content(self, self.device) @requires_accelerator_dist_backend() @skip_but_pass_in_sandcastle_if( not at_least_x_gpu(2), "test requires 2+ accelerators" ) def test_pg_transport_with_sharded_tensor(self) -> None: _test_pg_transport_with_sharded_tensor(self, self.device)
PgTransportGPU
python
huggingface__transformers
src/transformers/models/qwen3_moe/modular_qwen3_moe.py
{ "start": 1563, "end": 1852 }
class ____(Qwen3Attention): # This is the main diff with qwen2Moe! def __init__(self, config: Qwen3MoeConfig, layer_idx: int): super().__init__(config, layer_idx) del self.layer_type self.sliding_window = getattr(config, "sliding_window", None)
Qwen3MoeAttention
python
google__jax
jax/_src/core.py
{ "start": 44447, "end": 46046 }
class ____: axis_sizes : dict[AxisName, int] spmd_axis_names : set[AxisName] explicit_mesh_axis_names: frozenset[AxisName] def axis_size(self, axis_name): if axis_name not in self.axis_sizes: raise NameError(f"unbound axis name: {axis_name}") else: return self.axis_sizes[axis_name] def axis_exists(self, axis_name): return axis_name in self.axis_sizes def axis_names(self): return tuple(k for k in self.axis_sizes) def pop_pure(self, axis_name): new_sizes = self.axis_sizes.copy() new_sizes.pop(axis_name) return AxisEnv(new_sizes, self.spmd_axis_names, self.explicit_mesh_axis_names) def extend_pure(self, name_size_pairs): new_sizes = self.axis_sizes.copy() new_sizes.update((name, size) for name, size in name_size_pairs if name is not no_axis_name) return AxisEnv(new_sizes, self.spmd_axis_names, self.explicit_mesh_axis_names) def add_spmd_axis_names(self, axis_names): new_spmd_axis_names = self.spmd_axis_names | set(axis_names) return AxisEnv(self.axis_sizes, new_spmd_axis_names, self.explicit_mesh_axis_names) def add_explicit_mesh_axis_names(self, axis_names): new_ema = self.explicit_mesh_axis_names | frozenset(axis_names) return AxisEnv(self.axis_sizes, self.spmd_axis_names, new_ema) def as_hashable_key(self): return tuple((name, size) for (name, size) in self.axis_sizes.items() if name is not no_axis_name) eval_trace = EvalTrace() top_axis_env = AxisEnv({}, set(), frozenset())
AxisEnv
python
huggingface__transformers
src/transformers/models/granitemoeshared/modeling_granitemoeshared.py
{ "start": 4030, "end": 4775 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ GraniteMoeSharedRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype) def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
GraniteMoeSharedRMSNorm
python
conda__conda
conda/common/io.py
{ "start": 3265, "end": 12306 }
class ____(Enum): """Constants used for contextmanager captured. Used similarly like the constants PIPE, STDOUT for stdlib's subprocess.Popen. """ STRING = -1 STDOUT = -2 @contextmanager def env_vars(var_map=None, callback=None, stack_callback=None): if var_map is None: var_map = {} new_var_map = encode_environment(var_map) saved_vars = {} for name, value in new_var_map.items(): saved_vars[name] = os.environ.get(name, NULL) os.environ[name] = value try: if callback: callback() if stack_callback: stack_callback(True) yield finally: for name, value in saved_vars.items(): if value is NULL: del os.environ[name] else: os.environ[name] = value if callback: callback() if stack_callback: stack_callback(False) @contextmanager def env_var(name, value, callback=None, stack_callback=None): d = {name: value} with env_vars(d, callback=callback, stack_callback=stack_callback) as es: yield es @contextmanager def env_unmodified(callback=None): with env_vars(callback=callback) as es: yield es @contextmanager def captured(stdout=CaptureTarget.STRING, stderr=CaptureTarget.STRING): r"""Capture outputs of sys.stdout and sys.stderr. If stdout is STRING, capture sys.stdout as a string, if stdout is None, do not capture sys.stdout, leaving it untouched, otherwise redirect sys.stdout to the file-like object given by stdout. Behave correspondingly for stderr with the exception that if stderr is STDOUT, redirect sys.stderr to stdout target and set stderr attribute of yielded object to None. .. code-block:: pycon >>> from conda.common.io import captured >>> with captured() as c: ... print("hello world!") ... >>> c.stdout 'hello world!\n' Args: stdout: capture target for sys.stdout, one of STRING, None, or file-like object stderr: capture target for sys.stderr, one of STRING, STDOUT, None, or file-like object Yields: CapturedText: has attributes stdout, stderr which are either strings, None or the corresponding file-like function argument. """ def write_wrapper(self, to_write): # NOTE: This function is not thread-safe. Using within multi-threading may cause spurious # behavior of not returning sys.stdout and sys.stderr back to their 'proper' state # This may have to deal with a *lot* of text. if hasattr(self, "mode") and "b" in self.mode: wanted = bytes elif isinstance(self, BytesIO): wanted = bytes else: wanted = str if not isinstance(to_write, wanted): if hasattr(to_write, "decode"): decoded = to_write.decode("utf-8") self.old_write(decoded) elif hasattr(to_write, "encode"): b = to_write.encode("utf-8") self.old_write(b) else: self.old_write(to_write) class CapturedText: pass # sys.stdout.write(u'unicode out') # sys.stdout.write(bytes('bytes out', encoding='utf-8')) # sys.stdout.write(str('str out')) saved_stdout, saved_stderr = sys.stdout, sys.stderr if stdout == CaptureTarget.STRING: outfile = StringIO() outfile.old_write = outfile.write outfile.write = partial(write_wrapper, outfile) sys.stdout = outfile else: outfile = stdout if outfile is not None: sys.stdout = outfile if stderr == CaptureTarget.STRING: errfile = StringIO() errfile.old_write = errfile.write errfile.write = partial(write_wrapper, errfile) sys.stderr = errfile elif stderr == CaptureTarget.STDOUT: sys.stderr = errfile = outfile else: errfile = stderr if errfile is not None: sys.stderr = errfile c = CapturedText() log.debug("overtaking stderr and stdout") try: yield c finally: if stdout == CaptureTarget.STRING: c.stdout = outfile.getvalue() else: c.stdout = outfile if stderr == CaptureTarget.STRING: c.stderr = errfile.getvalue() elif stderr == CaptureTarget.STDOUT: c.stderr = None else: c.stderr = errfile sys.stdout, sys.stderr = saved_stdout, saved_stderr log.debug("stderr and stdout yielding back") @contextmanager def argv(args_list): saved_args = sys.argv sys.argv = args_list try: yield finally: sys.argv = saved_args @deprecated("25.9", "26.3", addendum="Use `logging._lock` instead.") @contextmanager def _logger_lock(): logging._acquireLock() try: yield finally: logging._releaseLock() @contextmanager def disable_logger(logger_name): logr = getLogger(logger_name) _lvl, _dsbld, _prpgt = logr.level, logr.disabled, logr.propagate null_handler = NullHandler() with logging._lock: logr.addHandler(null_handler) logr.setLevel(CRITICAL + 1) logr.disabled, logr.propagate = True, False try: yield finally: with logging._lock: logr.removeHandler(null_handler) # restore list logr.handlers logr.level, logr.disabled = _lvl, _dsbld logr.propagate = _prpgt @contextmanager def stderr_log_level(level, logger_name=None): logr = getLogger(logger_name) _hndlrs, _lvl, _dsbld, _prpgt = ( logr.handlers, logr.level, logr.disabled, logr.propagate, ) handler = StreamHandler(sys.stderr) handler.name = "stderr" handler.setLevel(level) handler.setFormatter(_FORMATTER) with logging._lock: logr.setLevel(level) logr.handlers, logr.disabled, logr.propagate = [], False, False logr.addHandler(handler) logr.setLevel(level) try: yield finally: with logging._lock: logr.handlers, logr.level, logr.disabled = _hndlrs, _lvl, _dsbld logr.propagate = _prpgt def attach_stderr_handler( level=WARN, logger_name=None, propagate=False, formatter=None, filters=None, ): """Attach a new `stderr` handler to the given logger and configure both. This function creates a new StreamHandler that writes to `stderr` and attaches it to the logger given by `logger_name` (which maybe `None`, in which case the root logger is used). If the logger already has a handler by the name of `stderr`, it is removed first. The given `level` is set **for the handler**, not for the logger; however, this function also sets the level of the given logger to the minimum of its current effective level and the new handler level, ensuring that the handler will receive the required log records, while minimizing the number of unnecessary log events. It also sets the loggers `propagate` property according to the `propagate` argument. The `formatter` argument can be used to set the formatter of the handler. """ # get old stderr logger logr = getLogger(logger_name) old_stderr_handler = next( (handler for handler in logr.handlers if handler.name == "stderr"), None ) # create new stderr logger new_stderr_handler = StreamHandler(sys.stderr) new_stderr_handler.name = "stderr" new_stderr_handler.setLevel(level) new_stderr_handler.setFormatter(formatter or _FORMATTER) for filter_ in filters or (): new_stderr_handler.addFilter(filter_) # do the switch with logging._lock: if old_stderr_handler: logr.removeHandler(old_stderr_handler) logr.addHandler(new_stderr_handler) if level < logr.getEffectiveLevel(): logr.setLevel(level) logr.propagate = propagate def timeout(timeout_secs, func, *args, default_return=None, **kwargs): """Enforce a maximum time for a callable to complete. Not yet implemented on Windows. """ if on_win: # Why does Windows have to be so difficult all the time? Kind of gets old. # Guess we'll bypass Windows timeouts for now. try: return func(*args, **kwargs) except KeyboardInterrupt: # pragma: no cover return default_return else: class TimeoutException(Exception): pass def interrupt(signum, frame): raise TimeoutException() signal.signal(signal.SIGALRM, interrupt) signal.alarm(timeout_secs) try: ret = func(*args, **kwargs) signal.alarm(0) return ret except (TimeoutException, KeyboardInterrupt): # pragma: no cover return default_return # use this for debugging, because ProcessPoolExecutor isn't pdb/ipdb friendly
CaptureTarget
python
django-debug-toolbar__django-debug-toolbar
tests/test_integration.py
{ "start": 26542, "end": 39310 }
class ____(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() options = Options() if os.environ.get("CI"): options.add_argument("-headless") # Set the browser preference to light mode for consistent testing options.set_preference("ui.systemUsesDarkTheme", 0) options.set_preference("ui.prefersReducedMotion", 0) cls.selenium = webdriver.Firefox(options=options) @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() def get(self, url): self.selenium.get(self.live_server_url + url) @property def wait(self): return WebDriverWait(self.selenium, timeout=3) def test_basic(self): self.get("/regular/basic/") version_panel = self.selenium.find_element(By.ID, VersionsPanel.panel_id) # Versions panel isn't loaded with self.assertRaises(NoSuchElementException): version_panel.find_element(By.TAG_NAME, "table") # Click to show the versions panel self.selenium.find_element(By.CLASS_NAME, VersionsPanel.panel_id).click() # Version panel loads table = self.wait.until( lambda selenium: version_panel.find_element(By.TAG_NAME, "table") ) self.assertIn("Name", table.text) self.assertIn("Version", table.text) @override_settings( DEBUG_TOOLBAR_CONFIG={ "DISABLE_PANELS": {"debug_toolbar.panels.redirects.RedirectsPanel"} } ) def test_basic_jinja(self): self.get("/regular_jinja/basic") template_panel = self.selenium.find_element(By.ID, TemplatesPanel.panel_id) # Click to show the template panel self.selenium.find_element(By.CLASS_NAME, TemplatesPanel.panel_id).click() # This should be 2 templates rendered, including base.html See # JinjaTemplateTestCase.test_django_jinja2_parent_template_instrumented self.assertIn("Templates (1 rendered)", template_panel.text) self.assertIn("basic.jinja", template_panel.text) @override_settings( DEBUG_TOOLBAR_CONFIG={ "DISABLE_PANELS": {"debug_toolbar.panels.redirects.RedirectsPanel"} } ) def test_rerender_on_history_switch(self): self.get("/regular_jinja/basic") # Make a new request so the history panel has more than one option. self.get("/execute_sql/") template_panel = self.selenium.find_element(By.ID, HistoryPanel.panel_id) # Record the current side panel of buttons for later comparison. previous_button_panel = self.selenium.find_element( By.ID, "djDebugPanelList" ).text # Click to show the history panel self.selenium.find_element(By.CLASS_NAME, HistoryPanel.panel_id).click() # Click to switch back to the jinja page view snapshot list(template_panel.find_elements(By.CSS_SELECTOR, "button"))[-1].click() current_button_panel = self.selenium.find_element( By.ID, "djDebugPanelList" ).text # Verify the button side panels have updated. self.assertNotEqual(previous_button_panel, current_button_panel) self.assertNotIn("1 query", current_button_panel) self.assertIn("1 query", previous_button_panel) @override_settings(DEBUG_TOOLBAR_CONFIG={"RESULTS_CACHE_SIZE": 0}) def test_expired_store(self): self.get("/regular/basic/") version_panel = self.selenium.find_element(By.ID, VersionsPanel.panel_id) # Click to show the version panel self.selenium.find_element(By.CLASS_NAME, VersionsPanel.panel_id).click() # Version panel doesn't loads error = self.wait.until( lambda selenium: version_panel.find_element(By.TAG_NAME, "p") ) self.assertIn("Data for this panel isn't available anymore.", error.text) @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "loaders": [ ( "django.template.loaders.cached.Loader", ( "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ), ) ] }, } ], ) def test_django_cached_template_loader(self): self.get("/regular/basic/") version_panel = self.selenium.find_element(By.ID, TemplatesPanel.panel_id) # Click to show the templates panel self.selenium.find_element(By.CLASS_NAME, TemplatesPanel.panel_id).click() # Templates panel loads trigger = self.wait.until( lambda selenium: version_panel.find_element(By.CSS_SELECTOR, ".remoteCall") ) trigger.click() # Verify the code is displayed self.wait.until( lambda selenium: self.selenium.find_element( By.CSS_SELECTOR, "#djDebugWindow code" ) ) def test_sql_action_and_go_back(self): self.get("/execute_sql/") sql_panel = self.selenium.find_element(By.ID, SQLPanel.panel_id) debug_window = self.selenium.find_element(By.ID, "djDebugWindow") # Click to show the SQL panel self.selenium.find_element(By.CLASS_NAME, SQLPanel.panel_id).click() # SQL panel loads button = self.wait.until( EC.visibility_of_element_located((By.CSS_SELECTOR, ".remoteCall")) ) button.click() # SQL selected window loads self.wait.until(EC.visibility_of(debug_window)) self.assertIn("SQL selected", debug_window.text) # Close the SQL selected window debug_window.find_element(By.CLASS_NAME, "djDebugClose").click() self.wait.until(EC.invisibility_of_element(debug_window)) # SQL panel is still visible self.assertTrue(sql_panel.is_displayed()) @override_settings(DEBUG_TOOLBAR_PANELS=["tests.test_integration.BuggyPanel"]) def test_displays_server_error(self): self.get("/regular/basic/") debug_window = self.selenium.find_element(By.ID, "djDebugWindow") self.selenium.find_element(By.CLASS_NAME, BuggyPanel.panel_id).click() self.wait.until(EC.visibility_of(debug_window)) self.assertEqual(debug_window.text, "500: Internal Server Error\n»") def test_toolbar_language_will_render_to_default_language_when_not_set(self): self.get("/regular/basic/") hide_button = self.selenium.find_element(By.ID, "djHideToolBarButton") assert hide_button.text == "Hide »" self.get("/execute_sql/") sql_panel = self.selenium.find_element(By.ID, SQLPanel.panel_id) # Click to show the SQL panel self.selenium.find_element(By.CLASS_NAME, SQLPanel.panel_id).click() table = self.wait.until( lambda selenium: sql_panel.find_element(By.TAG_NAME, "table") ) self.assertIn("Query", table.text) self.assertIn("Action", table.text) @override_settings(DEBUG_TOOLBAR_CONFIG={"TOOLBAR_LANGUAGE": "pt-br"}) def test_toolbar_language_will_render_to_locale_when_set(self): self.get("/regular/basic/") hide_button = self.selenium.find_element(By.ID, "djHideToolBarButton") assert hide_button.text == "Esconder »" self.get("/execute_sql/") sql_panel = self.selenium.find_element(By.ID, SQLPanel.panel_id) # Click to show the SQL panel self.selenium.find_element(By.CLASS_NAME, SQLPanel.panel_id).click() table = self.wait.until( lambda selenium: sql_panel.find_element(By.TAG_NAME, "table") ) self.assertIn("Query", table.text) self.assertIn("Linha", table.text) @override_settings(DEBUG_TOOLBAR_CONFIG={"TOOLBAR_LANGUAGE": "en-us"}) @override_settings(LANGUAGE_CODE="de") def test_toolbar_language_will_render_to_locale_when_set_both(self): self.get("/regular/basic/") hide_button = self.selenium.find_element(By.ID, "djHideToolBarButton") assert hide_button.text == "Hide »" self.get("/execute_sql/") sql_panel = self.selenium.find_element(By.ID, SQLPanel.panel_id) # Click to show the SQL panel self.selenium.find_element(By.CLASS_NAME, SQLPanel.panel_id).click() table = self.wait.until( lambda selenium: sql_panel.find_element(By.TAG_NAME, "table") ) self.assertIn("Query", table.text) self.assertIn("Action", table.text) def test_ajax_dont_refresh(self): self.get("/ajax/") make_ajax = self.selenium.find_element(By.ID, "click_for_ajax") make_ajax.click() history_panel = self.selenium.find_element(By.ID, "djdt-HistoryPanel") self.assertIn("/ajax/", history_panel.text) self.assertNotIn("/json_view/", history_panel.text) @override_settings(DEBUG_TOOLBAR_CONFIG={"UPDATE_ON_FETCH": True}) def test_ajax_refresh(self): self.get("/ajax/") make_ajax = self.selenium.find_element(By.ID, "click_for_ajax") make_ajax.click() # Sleep a tad to avoid a selenium.common.exceptions.StaleElementReferenceException # when looking for the small text of the history panel time.sleep(0.1) # Need to wait until the ajax request is over and json_view is displayed on the toolbar self.wait.until( lambda selenium: self.selenium.find_element( By.CSS_SELECTOR, "#djdt-HistoryPanel a.HistoryPanel small" ).text == "/json_view/" ) history_panel = self.selenium.find_element(By.ID, "djdt-HistoryPanel") self.assertNotIn("/ajax/", history_panel.text) self.assertIn("/json_view/", history_panel.text) def test_theme_toggle(self): self.get("/regular/basic/") toolbar = self.selenium.find_element(By.ID, "djDebug") # Check that the default theme is auto self.assertEqual(toolbar.get_attribute("data-user-theme"), "auto") # The theme toggle button is shown on the toolbar toggle_button = self.selenium.find_element(By.ID, "djToggleThemeButton") self.assertTrue(toggle_button.is_displayed()) # The browser is set to light mode via Firefox preferences # With light mode system preference, the order is: auto -> dark -> light -> auto # Check that auto initially uses light theme self.assertEqual(toolbar.get_attribute("data-user-theme"), "auto") self.assertEqual(toolbar.get_attribute("data-theme"), "light") # The theme changes when user clicks the button toggle_button.click() # auto -> dark self.assertEqual(toolbar.get_attribute("data-user-theme"), "dark") self.assertEqual(toolbar.get_attribute("data-theme"), "dark") toggle_button.click() # dark -> light self.assertEqual(toolbar.get_attribute("data-user-theme"), "light") self.assertEqual(toolbar.get_attribute("data-theme"), "light") toggle_button.click() # light -> auto self.assertEqual(toolbar.get_attribute("data-user-theme"), "auto") self.assertEqual(toolbar.get_attribute("data-theme"), "light") # Enter the page again to check that user settings is saved self.get("/regular/basic/") toolbar = self.selenium.find_element(By.ID, "djDebug") self.assertEqual(toolbar.get_attribute("data-user-theme"), "auto") self.assertEqual(toolbar.get_attribute("data-theme"), "light") def test_async_sql_action(self): self.get("/async_execute_sql/") self.selenium.find_element(By.ID, "SQLPanel") self.selenium.find_element(By.ID, "djDebugWindow") # Click to show the SQL panel self.selenium.find_element(By.CLASS_NAME, "SQLPanel").click() # SQL panel loads self.wait.until( EC.visibility_of_element_located((By.CSS_SELECTOR, ".remoteCall")) ) def test_concurrent_async_sql_action(self): self.get("/async_execute_sql_concurrently/") self.selenium.find_element(By.ID, "SQLPanel") self.selenium.find_element(By.ID, "djDebugWindow") # Click to show the SQL panel self.selenium.find_element(By.CLASS_NAME, "SQLPanel").click() # SQL panel loads self.wait.until( EC.visibility_of_element_located((By.CSS_SELECTOR, ".remoteCall")) )
DebugToolbarLiveTestCase
python
Pylons__pyramid
tests/test_security.py
{ "start": 11985, "end": 12705 }
class ____(unittest.TestCase): def setUp(self): testing.setUp() def tearDown(self): testing.tearDown() def test_no_security_policy(self): request = _makeRequest() self.assertIs(request.is_authenticated, False) def test_with_security_policy(self): request = _makeRequest() _registerSecurityPolicy(request.registry, '123') self.assertIs(request.is_authenticated, True) def test_with_legacy_security_policy(self): request = _makeRequest() _registerAuthenticationPolicy(request.registry, 'yo') _registerLegacySecurityPolicy(request.registry) self.assertEqual(request.authenticated_userid, 'yo')
TestIsAuthenticated
python
scipy__scipy
scipy/stats/_distribution_infrastructure.py
{ "start": 34379, "end": 61625 }
class ____: r""" Represents a parameterization of a distribution. Distributions can have multiple parameterizations. A `_Parameterization` object is responsible for recording the parameters used by the parameterization, checking whether keyword arguments passed to the distribution match the parameterization, and performing input validation of the numerical values of these parameters. Attributes ---------- parameters : dict String names (of keyword arguments) and the corresponding _Parameters. Methods ------- __len__() Returns the number of parameters in the parameterization. __str__() Returns a string representation of the parameterization. copy Returns a copy of the parameterization. This is needed for transformed distributions that add parameters to the parameterization. matches(parameters) Checks whether the keyword arguments match the parameterization. validation(parameter_values) Input validation / standardization of parameterization. Validates the numerical values of all parameters. draw(sizes, rng, proportions) Draw random values of all parameters of the parameterization for use in testing. """ def __init__(self, *parameters): self.parameters = {param.name: param for param in parameters} def __len__(self): return len(self.parameters) def copy(self): return _Parameterization(*self.parameters.values()) def matches(self, parameters): r""" Checks whether the keyword arguments match the parameterization. Parameters ---------- parameters : set Set of names of parameters passed into the distribution as keyword arguments. Returns ------- out : bool True if the keyword arguments names match the names of the parameters of this parameterization. """ return parameters == set(self.parameters.keys()) def validation(self, parameter_values): r""" Input validation / standardization of parameterization. Parameters ---------- parameter_values : dict The keyword arguments passed as parameter values to the distribution. Returns ------- all_valid : ndarray Logical array indicating the elements of the broadcasted arrays for which all parameter values are valid. dtype : dtype The common dtype of the parameter arrays. This will determine the dtype of the output of distribution methods. """ all_valid = True dtypes = set() # avoid np.result_type if there's only one type for name, arr in parameter_values.items(): parameter = self.parameters[name] arr, dtype, valid = parameter.validate(arr, parameter_values) dtypes.add(dtype) all_valid = all_valid & valid parameter_values[name] = arr dtype = arr.dtype if len(dtypes)==1 else np.result_type(*list(dtypes)) return all_valid, dtype def __str__(self): r"""Returns a string representation of the parameterization.""" messages = [str(param) for name, param in self.parameters.items()] return ", ".join(messages) def draw(self, sizes=None, rng=None, proportions=None, region='domain'): r"""Draw random values of all parameters for use in testing. Parameters ---------- sizes : iterable of shape tuples The size of the array to be generated for each parameter in the parameterization. Note that the order of sizes is arbitary; the size of the array generated for a specific parameter is not controlled individually as written. rng : NumPy Generator The generator used to draw random values. proportions : tuple A tuple of four non-negative numbers that indicate the expected relative proportion of elements that are within the parameter's domain, are on the boundary of the parameter's domain, are outside the parameter's domain, and have value NaN. For more information, see the `draw` method of the _Parameter subclasses. domain : str The domain of the `_Parameter` from which to draw. Default is "domain" (the *full* domain); alternative is "typical". Returns ------- parameter_values : dict (string: array) A dictionary of parameter name/value pairs. """ # ENH: be smart about the order. The domains of some parameters # depend on others. If the relationshp is simple (e.g. a < b < c), # we can draw values in order a, b, c. parameter_values = {} if sizes is None or not len(sizes) or not np.iterable(sizes[0]): sizes = [sizes]*len(self.parameters) for size, param in zip(sizes, self.parameters.values()): parameter_values[param.name] = param.draw( size, rng=rng, proportions=proportions, parameter_values=parameter_values, region=region ) return parameter_values def _set_invalid_nan(f): # Wrapper for input / output validation and standardization of distribution # functions that accept either the quantile or percentile as an argument: # logpdf, pdf # logpmf, pmf # logcdf, cdf # logccdf, ccdf # ilogcdf, icdf # ilogccdf, iccdf # Arguments that are outside the required range are replaced by NaN before # passing them into the underlying function. The corresponding outputs # are replaced by the appropriate value before being returned to the user. # For example, when the argument of `cdf` exceeds the right end of the # distribution's support, the wrapper replaces the argument with NaN, # ignores the output of the underlying function, and returns 1.0. It also # ensures that output is of the appropriate shape and dtype. endpoints = {'icdf': (0, 1), 'iccdf': (0, 1), 'ilogcdf': (-np.inf, 0), 'ilogccdf': (-np.inf, 0)} replacements = {'logpdf': (-inf, -inf), 'pdf': (0, 0), 'logpmf': (-inf, -inf), 'pmf': (0, 0), '_logcdf1': (-inf, 0), '_logccdf1': (0, -inf), '_cdf1': (0, 1), '_ccdf1': (1, 0)} replace_strict = {'pdf', 'logpdf', 'pmf', 'logpmf'} replace_exact = {'icdf', 'iccdf', 'ilogcdf', 'ilogccdf'} clip = {'_cdf1', '_ccdf1'} clip_log = {'_logcdf1', '_logccdf1'} # relevant to discrete distributions only replace_non_integral = {'pmf', 'logpmf', 'pdf', 'logpdf'} @functools.wraps(f) def filtered(self, x, *args, **kwargs): if self.validation_policy == _SKIP_ALL: return f(self, x, *args, **kwargs) method_name = f.__name__ x = np.asarray(x) dtype = self._dtype shape = self._shape discrete = isinstance(self, DiscreteDistribution) keep_low_endpoint = discrete and method_name in {'_cdf1', '_logcdf1', '_ccdf1', '_logccdf1'} # Ensure that argument is at least as precise as distribution # parameters, which are already at least floats. This will avoid issues # with raising integers to negative integer powers and failure to replace # invalid integers with NaNs. if x.dtype != dtype: dtype = np.result_type(x.dtype, dtype) x = np.asarray(x, dtype=dtype) # Broadcasting is slow. Do it only if necessary. if not x.shape == shape: try: shape = np.broadcast_shapes(x.shape, shape) x = np.broadcast_to(x, shape) # Should we broadcast the distribution parameters to this shape, too? except ValueError as e: message = ( f"The argument provided to `{self.__class__.__name__}" f".{method_name}` cannot be be broadcast to the same " "shape as the distribution parameters.") raise ValueError(message) from e low, high = endpoints.get(method_name, self.support()) # Check for arguments outside of domain. They'll be replaced with NaNs, # and the result will be set to the appropriate value. left_inc, right_inc = self._variable.domain.inclusive mask_low = (x < low if (method_name in replace_strict and left_inc) or keep_low_endpoint else x <= low) mask_high = (x > high if (method_name in replace_strict and right_inc) else x >= high) mask_invalid = (mask_low | mask_high) any_invalid = (mask_invalid if mask_invalid.shape == () else np.any(mask_invalid)) # Check for arguments at domain endpoints, whether they # are part of the domain or not. any_endpoint = False if method_name in replace_exact: mask_low_endpoint = (x == low) mask_high_endpoint = (x == high) mask_endpoint = (mask_low_endpoint | mask_high_endpoint) any_endpoint = (mask_endpoint if mask_endpoint.shape == () else np.any(mask_endpoint)) # Check for non-integral arguments to PMF method # or PDF of a discrete distribution. any_non_integral = False if discrete and method_name in replace_non_integral: mask_non_integral = (x != np.floor(x)) any_non_integral = (mask_non_integral if mask_non_integral.shape == () else np.any(mask_non_integral)) # Set out-of-domain arguments to NaN. The result will be set to the # appropriate value later. if any_invalid: x = np.array(x, dtype=dtype, copy=True) x[mask_invalid] = np.nan res = np.asarray(f(self, x, *args, **kwargs)) # Ensure that the result is the correct dtype and shape, # copying (only once) if necessary. res_needs_copy = False if res.dtype != dtype: dtype = np.result_type(dtype, self._dtype) res_needs_copy = True if res.shape != shape: # faster to check first res = np.broadcast_to(res, self._shape) res_needs_copy = (res_needs_copy or any_invalid or any_endpoint or any_non_integral) if res_needs_copy: res = np.array(res, dtype=dtype, copy=True) # For non-integral arguments to PMF (and PDF of discrete distribution) # replace with zero. if any_non_integral: zero = -np.inf if method_name in {'logpmf', 'logpdf'} else 0 res[mask_non_integral & ~np.isnan(res)] = zero # For arguments outside the function domain, replace results if any_invalid: replace_low, replace_high = ( replacements.get(method_name, (np.nan, np.nan))) res[mask_low] = replace_low res[mask_high] = replace_high # For arguments at the endpoints of the domain, replace results if any_endpoint: a, b = self.support() if a.shape != shape: a = np.array(np.broadcast_to(a, shape), copy=True) b = np.array(np.broadcast_to(b, shape), copy=True) replace_low_endpoint = ( b[mask_low_endpoint] if method_name.endswith('ccdf') else a[mask_low_endpoint]) replace_high_endpoint = ( a[mask_high_endpoint] if method_name.endswith('ccdf') else b[mask_high_endpoint]) if not keep_low_endpoint: res[mask_low_endpoint] = replace_low_endpoint res[mask_high_endpoint] = replace_high_endpoint # Clip probabilities to [0, 1] if method_name in clip: res = np.clip(res, 0., 1.) elif method_name in clip_log: res = res.real # exp(res) > 0 res = np.clip(res, None, 0.) # exp(res) < 1 return res[()] return filtered def _set_invalid_nan_property(f): # Wrapper for input / output validation and standardization of distribution # functions that represent properties of the distribution itself: # logentropy, entropy # median, mode # moment # It ensures that the output is of the correct shape and dtype and that # there are NaNs wherever the distribution parameters were invalid. @functools.wraps(f) def filtered(self, *args, **kwargs): if self.validation_policy == _SKIP_ALL: return f(self, *args, **kwargs) res = f(self, *args, **kwargs) if res is None: # message could be more appropriate raise NotImplementedError(self._not_implemented) res = np.asarray(res) needs_copy = False dtype = res.dtype if dtype != self._dtype: # this won't work for logmoments (complex) dtype = np.result_type(dtype, self._dtype) needs_copy = True if res.shape != self._shape: # faster to check first res = np.broadcast_to(res, self._shape) needs_copy = needs_copy or self._any_invalid if needs_copy: res = res.astype(dtype=dtype, copy=True) if self._any_invalid: # may be redundant when quadrature is used, but not necessarily # when formulas are used. res[self._invalid] = np.nan return res[()] return filtered def _dispatch(f): # For each public method (instance function) of a distribution (e.g. ccdf), # there may be several ways ("method"s) that it can be computed (e.g. a # formula, as the complement of the CDF, or via numerical integration). # Each "method" is implemented by a different private method (instance # function). # This wrapper calls the appropriate private method based on the public # method and any specified `method` keyword option. # - If `method` is specified as a string (by the user), the appropriate # private method is called. # - If `method` is None: # - The appropriate private method for the public method is looked up # in a cache. # - If the cache does not have an entry for the public method, the # appropriate "dispatch " function is called to determine which method # is most appropriate given the available private methods and # settings (e.g. tolerance). @functools.wraps(f) def wrapped(self, *args, method=None, **kwargs): func_name = f.__name__ method = method or self._method_cache.get(func_name, None) if callable(method): pass elif method is not None: method = 'logexp' if method == 'log/exp' else method method_name = func_name.replace('dispatch', method) method = getattr(self, method_name) else: method = f(self, *args, method=method, **kwargs) if func_name != '_sample_dispatch' and self.cache_policy != _NO_CACHE: self._method_cache[func_name] = method try: return method(*args, **kwargs) except KeyError as e: raise NotImplementedError(self._not_implemented) from e return wrapped def _cdf2_input_validation(f): # Wrapper that does the job of `_set_invalid_nan` when `cdf` or `logcdf` # is called with two quantile arguments. # Let's keep it simple; no special cases for speed right now. # The strategy is a bit different than for 1-arg `cdf` (and other methods # covered by `_set_invalid_nan`). For 1-arg `cdf`, elements of `x` that # are outside (or at the edge of) the support get replaced by `nan`, # and then the results get replaced by the appropriate value (0 or 1). # We *could* do something similar, dispatching to `_cdf1` in these # cases. That would be a bit more robust, but it would also be quite # a bit more complex, since we'd have to do different things when # `x` and `y` are both out of bounds, when just `x` is out of bounds, # when just `y` is out of bounds, and when both are out of bounds. # I'm not going to do that right now. Instead, simply replace values # outside the support by those at the edge of the support. Here, we also # omit some of the optimizations that make `_set_invalid_nan` faster for # simple arguments (e.g. float64 scalars). @functools.wraps(f) def wrapped(self, x, y, *args, **kwargs): func_name = f.__name__ low, high = self.support() x, y, low, high = np.broadcast_arrays(x, y, low, high) dtype = np.result_type(x.dtype, y.dtype, self._dtype) # yes, copy to avoid modifying input arrays x, y = x.astype(dtype, copy=True), y.astype(dtype, copy=True) # Swap arguments to ensure that x < y, and replace # out-of domain arguments with domain endpoints. We'll # transform the result later. i_swap = y < x x[i_swap], y[i_swap] = y[i_swap], x[i_swap] i = x < low x[i] = low[i] i = y < low y[i] = low[i] i = x > high x[i] = high[i] i = y > high y[i] = high[i] res = f(self, x, y, *args, **kwargs) # Clipping probability to [0, 1] if func_name in {'_cdf2', '_ccdf2'}: res = np.clip(res, 0., 1.) else: res = np.clip(res, None, 0.) # exp(res) < 1 # Transform the result to account for swapped argument order res = np.asarray(res) if func_name == '_cdf2': res[i_swap] *= -1. elif func_name == '_ccdf2': res[i_swap] *= -1 res[i_swap] += 2. elif func_name == '_logcdf2': res = np.asarray(res + 0j) if np.any(i_swap) else res res[i_swap] = res[i_swap] + np.pi*1j else: # res[i_swap] is always positive and less than 1, so it's # safe to ensure that the result is real res[i_swap] = _logexpxmexpy(np.log(2), res[i_swap]).real return res[()] return wrapped def _fiinfo(x): if np.issubdtype(x.dtype, np.inexact): return np.finfo(x.dtype) else: return np.iinfo(x) def _kwargs2args(f, args=None, kwargs=None): # Wraps a function that accepts a primary argument `x`, secondary # arguments `args`, and secondary keyward arguments `kwargs` such that the # wrapper accepts only `x` and `args`. The keyword arguments are extracted # from `args` passed into the wrapper, and these are passed to the # underlying function as `kwargs`. # This is a temporary workaround until the scalar algorithms `_tanhsinh`, # `_chandrupatla`, etc., support `kwargs` or can operate with compressing # arguments to the callable. args = args or [] kwargs = kwargs or {} names = list(kwargs.keys()) n_args = len(args) def wrapped(x, *args): return f(x, *args[:n_args], **dict(zip(names, args[n_args:]))) args = tuple(args) + tuple(kwargs.values()) return wrapped, args def _logexpxmexpy(x, y): """ Compute the log of the difference of the exponentials of two arguments. Avoids over/underflow, but does not prevent loss of precision otherwise. """ # TODO: properly avoid NaN when y is negative infinity # TODO: silence warning with taking log of complex nan # TODO: deal with x == y better i = np.isneginf(np.real(y)) if np.any(i): y = np.asarray(y.copy()) y[i] = np.finfo(y.dtype).min x, y = np.broadcast_arrays(x, y) res = np.asarray(special.logsumexp([x, y+np.pi*1j], axis=0)) i = (x == y) res[i] = -np.inf return res def _guess_bracket(xmin, xmax): a = np.full_like(xmin, -1.0) b = np.ones_like(xmax) i = np.isfinite(xmin) & np.isfinite(xmax) a[i] = xmin[i] b[i] = xmax[i] i = np.isfinite(xmin) & ~np.isfinite(xmax) a[i] = xmin[i] b[i] = xmin[i] + 1 i = np.isfinite(xmax) & ~np.isfinite(xmin) a[i] = xmax[i] - 1 b[i] = xmax[i] return a, b def _log_real_standardize(x): """Standardizes the (complex) logarithm of a real number. The logarithm of a real number may be represented by a complex number with imaginary part that is a multiple of pi*1j. Even multiples correspond with a positive real and odd multiples correspond with a negative real. Given a logarithm of a real number `x`, this function returns an equivalent representation in a standard form: the log of a positive real has imaginary part `0` and the log of a negative real has imaginary part `pi`. """ shape = x.shape x = np.atleast_1d(x) real = np.real(x).astype(x.dtype) complex = np.imag(x) y = real negative = np.exp(complex*1j) < 0.5 y[negative] = y[negative] + np.pi * 1j return y.reshape(shape)[()] def _combine_docs(dist_family, *, include_examples=True): fields = set(NumpyDocString.sections) fields.remove('index') if not include_examples: fields.remove('Examples') doc = ClassDoc(dist_family) superdoc = ClassDoc(UnivariateDistribution) for field in fields: if field in {"Methods", "Attributes"}: doc[field] = superdoc[field] elif field in {"Summary"}: pass elif field == "Extended Summary": doc[field].append(_generate_domain_support(dist_family)) elif field == 'Examples': doc[field] = [_generate_example(dist_family)] else: doc[field] += superdoc[field] return str(doc) def _generate_domain_support(dist_family): n_parameterizations = len(dist_family._parameterizations) domain = f"\nfor :math:`x \\in {dist_family._variable.domain}`.\n" if n_parameterizations == 0: support = """ This class accepts no distribution parameters. """ elif n_parameterizations == 1: support = f""" This class accepts one parameterization: {str(dist_family._parameterizations[0])}. """ else: number = {2: 'two', 3: 'three', 4: 'four', 5: 'five'}[ n_parameterizations] parameterizations = [f"- {str(p)}" for p in dist_family._parameterizations] parameterizations = "\n".join(parameterizations) support = f""" This class accepts {number} parameterizations: {parameterizations} """ support = "\n".join([line.lstrip() for line in support.split("\n")][1:]) return domain + support def _generate_example(dist_family): n_parameters = dist_family._num_parameters(0) shapes = [()] * n_parameters rng = np.random.default_rng(615681484984984) i = 0 dist = dist_family._draw(shapes, rng=rng, i_parameterization=i) rng = np.random.default_rng(2354873452) name = dist_family.__name__ if n_parameters: parameter_names = list(dist._parameterizations[i].parameters) parameter_values = [round(getattr(dist, name), 2) for name in parameter_names] name_values = [f"{name}={value}" for name, value in zip(parameter_names, parameter_values)] instantiation = f"{name}({', '.join(name_values)})" attributes = ", ".join([f"X.{param}" for param in dist._parameters]) X = dist_family(**dict(zip(parameter_names, parameter_values))) else: instantiation = f"{name}()" X = dist p = 0.32 x = round(X.icdf(p), 2) y = round(X.icdf(2 * p), 2) # noqa: F841 example = f""" To use the distribution class, it must be instantiated using keyword parameters corresponding with one of the accepted parameterizations. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import stats >>> from scipy.stats import {name} >>> X = {instantiation} For convenience, the ``plot`` method can be used to visualize the density and other functions of the distribution. >>> X.plot() >>> plt.show() The support of the underlying distribution is available using the ``support`` method. >>> X.support() {X.support()} """ if n_parameters: example += f""" The numerical values of parameters associated with all parameterizations are available as attributes. >>> {attributes} {tuple(X._parameters.values())} """ example += f""" To evaluate the probability density/mass function of the underlying distribution at argument ``x={x}``: >>> x = {x} >>> X.pdf(x), X.pmf(x) {X.pdf(x), X.pmf(x)} The cumulative distribution function, its complement, and the logarithm of these functions are evaluated similarly. >>> np.allclose(np.exp(X.logccdf(x)), 1 - X.cdf(x)) True """ # When two-arg CDF is implemented for DiscreteDistribution, consider removing # the special-casing here. if issubclass(dist_family, ContinuousDistribution): example_continuous = f""" The inverse of these functions with respect to the argument ``x`` is also available. >>> logp = np.log(1 - X.ccdf(x)) >>> np.allclose(X.ilogcdf(logp), x) True Note that distribution functions and their logarithms also have two-argument versions for working with the probability mass between two arguments. The result tends to be more accurate than the naive implementation because it avoids subtractive cancellation. >>> y = {y} >>> np.allclose(X.ccdf(x, y), 1 - (X.cdf(y) - X.cdf(x))) True """ example += example_continuous example += f""" There are methods for computing measures of central tendency, dispersion, higher moments, and entropy. >>> X.mean(), X.median(), X.mode() {X.mean(), X.median(), X.mode()} >>> X.variance(), X.standard_deviation() {X.variance(), X.standard_deviation()} >>> X.skewness(), X.kurtosis() {X.skewness(), X.kurtosis()} >>> np.allclose(X.moment(order=6, kind='standardized'), ... X.moment(order=6, kind='central') / X.variance()**3) True """ # When logentropy is implemented for DiscreteDistribution, remove special-casing if issubclass(dist_family, ContinuousDistribution): example += """ >>> np.allclose(np.exp(X.logentropy()), X.entropy()) True """ else: example += f""" >>> X.entropy() {X.entropy()} """ example += f""" Pseudo-random samples can be drawn from the underlying distribution using ``sample``. >>> X.sample(shape=(4,)) {repr(X.sample(shape=(4,)))} # may vary """ # remove the indentation due to use of block quote within function; # eliminate blank first line example = "\n".join([line.lstrip() for line in example.split("\n")][1:]) return example
_Parameterization
python
qiwsir__algorithm
binary_tree.py
{ "start": 38, "end": 3694 }
class ____: """ 二叉树左右枝 """ def __init__(self, data): """ 节点结构 """ self.left = None self.right = None self.data = data def insert(self, data): """ 插入节点数据 """ if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) def lookup(self, data, parent=None): """ 遍历二叉树 """ if data < self.data: if self.left is None: return None, None return self.left.lookup(data, self) elif data > self.data: if self.right is None: return None, None return self.right.lookup(data, self) else: return self, parent def delete(self, data): """ 删除节点 """ node, parent = self.lookup(data) #已有节点 if node is not None: children_count = node.children_count() #判断子节点数 if children_count == 0: # 如果该节点下没有子节点,即可删除 if parent.left is node: parent.left = None else: parent.right = None del node elif children_count == 1: # 如果有一个子节点,则让子节点上移替换该节点(该节点消失) if node.left: n = node.left else: n = node.right if parent: if parent.left is node: parent.left = n else: parent.right = n del node else: # 如果有两个子节点,则要判断节点下所有叶子 parent = node successor = node.right while successor.left: parent = successor successor = successor.left node.data = successor.data if parent.left == successor: parent.left = successor.right else: parent.right = successor.right def compare_trees(self, node): """ 比较两棵树 """ if node is None: return False if self.data != node.data: return False res = True if self.left is None: if node.left: return False else: res = self.left.compare_trees(node.left) if res is False: return False if self.right is None: if node.right: return False else: res = self.right.compare_trees(node.right) return res def print_tree(self): """ 按顺序打印数的内容 """ if self.left: self.left.print_tree() print self.data, if self.right: self.right.print_tree() def tree_data(self): """ 二叉树数据结构 """ stack = [] node = self while stack or node: if node: stack.append(node) node = node.left else: node = stack.pop() yield node.data node = node.right def children_count(self): """ 子节点个数 """ cnt = 0 if self.left: cnt += 1 if self.right: cnt += 1 return cnt
Node
python
run-llama__llama_index
llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-firestore/llama_index/storage/kvstore/firestore/base.py
{ "start": 797, "end": 8087 }
class ____(BaseKVStore): """ Firestore Key-Value store. Args: project (str): The project which the client acts on behalf of. database (str): The database name that the client targets. credentials (google.auth.credentials.Credentials): The OAuth2 Credentials to access Firestore. If not passed, falls back to the default inferred from the environment. """ def __init__( self, project: Optional[str] = None, database: str = DEFAULT_FIRESTORE_DATABASE, credentials: Optional[Credentials] = None, ) -> None: client_info = DEFAULT_CLIENT_INFO client_info.user_agent = USER_AGENT self._adb = AsyncClient( project=project, database=database, client_info=client_info, credentials=credentials, ) self._db = Client( project=project, database=database, client_info=client_info, credentials=credentials, ) def firestore_collection(self, collection: str) -> str: return collection.replace("/", SLASH_REPLACEMENT) def replace_field_name_set(self, val: Dict[str, Any]) -> Dict[str, Any]: val = val.copy() for k, v in FIELD_NAME_REPLACE_SET.items(): if k in val: val[v] = val[k] val.pop(k) return val def replace_field_name_get(self, val: Dict[str, Any]) -> Dict[str, Any]: val = val.copy() for k, v in FIELD_NAME_REPLACE_GET.items(): if k in val: val[v] = val[k] val.pop(k) return val def put( self, key: str, val: dict, collection: str = DEFAULT_COLLECTION, ) -> None: """ Put a key-value pair into the Firestore collection. Args: key (str): key val (dict): value collection (str): collection name """ collection_id = self.firestore_collection(collection) val = self.replace_field_name_set(val) doc = self._db.collection(collection_id).document(key) doc.set(val, merge=True) async def aput( self, key: str, val: dict, collection: str = DEFAULT_COLLECTION, ) -> None: """ Put a key-value pair into the Firestore collection. Args: key (str): key val (dict): value collection (str): collection name """ collection_id = self.firestore_collection(collection) val = self.replace_field_name_set(val) doc = self._adb.collection(collection_id).document(key) await doc.set(val, merge=True) def put_all( self, kv_pairs: List[Tuple[str, dict]], collection: str = DEFAULT_COLLECTION, batch_size: int = DEFAULT_BATCH_SIZE, ) -> None: batch = self._db.batch() for i, (key, val) in enumerate(kv_pairs, start=1): collection_id = self.firestore_collection(collection) val = self.replace_field_name_set(val) batch.set(self._db.collection(collection_id).document(key), val, merge=True) if i % batch_size == 0: batch.commit() batch = self._db.batch() batch.commit() async def aput_all( self, kv_pairs: List[Tuple[str, dict]], collection: str = DEFAULT_COLLECTION, batch_size: int = DEFAULT_BATCH_SIZE, ) -> None: """ Put a dictionary of key-value pairs into the Firestore collection. Args: kv_pairs (List[Tuple[str, dict]]): key-value pairs collection (str): collection name """ batch = self._adb.batch() for i, (key, val) in enumerate(kv_pairs, start=1): collection_id = self.firestore_collection(collection) doc = self._adb.collection(collection_id).document(key) val = self.replace_field_name_set(val) batch.set(doc, val, merge=True) if i % batch_size == 0: await batch.commit() batch = self._adb.batch() await batch.commit() def get(self, key: str, collection: str = DEFAULT_COLLECTION) -> Optional[dict]: """ Get a key-value pair from the Firestore. Args: key (str): key collection (str): collection name """ collection_id = self.firestore_collection(collection) result = self._db.collection(collection_id).document(key).get().to_dict() if not result: return None return self.replace_field_name_get(result) async def aget( self, key: str, collection: str = DEFAULT_COLLECTION ) -> Optional[dict]: """ Get a key-value pair from the Firestore. Args: key (str): key collection (str): collection name """ collection_id = self.firestore_collection(collection) result = ( await self._adb.collection(collection_id).document(key).get() ).to_dict() if not result: return None return self.replace_field_name_get(result) def get_all(self, collection: str = DEFAULT_COLLECTION) -> Dict[str, dict]: """ Get all values from the Firestore collection. Args: collection (str): collection name """ collection_id = self.firestore_collection(collection) docs = self._db.collection(collection_id).list_documents() output = {} for doc in docs: key = doc.id val = self.replace_field_name_get(doc.get().to_dict()) output[key] = val return output async def aget_all(self, collection: str = DEFAULT_COLLECTION) -> Dict[str, dict]: """ Get all values from the Firestore collection. Args: collection (str): collection name """ collection_id = self.firestore_collection(collection) docs = self._adb.collection(collection_id).list_documents() output = {} async for doc in docs: key = doc.id data = (await doc.get()).to_dict() if data is None: continue val = self.replace_field_name_get(data) output[key] = val return output def delete(self, key: str, collection: str = DEFAULT_COLLECTION) -> bool: """ Delete a value from the Firestore. Args: key (str): key collection (str): collection name """ collection_id = self.firestore_collection(collection) doc = self._db.collection(collection_id).document(key) doc.delete() return True async def adelete(self, key: str, collection: str = DEFAULT_COLLECTION) -> bool: """ Delete a value from the Firestore. Args: key (str): key collection (str): collection name """ collection_id = self.firestore_collection(collection) doc = self._adb.collection(collection_id).document(key) await doc.delete() return True
FirestoreKVStore
python
neetcode-gh__leetcode
python/0106-construct-binary-tree-from-inorder-and-postorder-traversal.py
{ "start": 192, "end": 834 }
class ____: def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: def buildTreeHelper(left, right): if left > right: return None rootVal = postorder.pop() rootNode = TreeNode(rootVal) idx = inorderIndexMap[rootVal] rootNode.right = buildTreeHelper(idx + 1, right) rootNode.left = buildTreeHelper(left, idx - 1) return rootNode inorderIndexMap = {} for (i, val) in enumerate(inorder): inorderIndexMap[val] = i return buildTreeHelper(0, len(postorder) - 1)
Solution
python
getsentry__sentry
tests/sentry/api/serializers/test_organization_member.py
{ "start": 427, "end": 2171 }
class ____(TestCase): def setUp(self) -> None: self.owner_user = self.create_user("foo@localhost", username="foo") self.user_2 = self.create_user("bar@localhost", username="bar") self.org = self.create_organization(owner=self.owner_user) self.org.member_set.create(user_id=self.user_2.id) self.team = self.create_team(organization=self.org, members=[self.owner_user, self.user_2]) self.team_2 = self.create_team(organization=self.org, members=[self.user_2]) self.project = self.create_project(teams=[self.team]) self.project_2 = self.create_project(teams=[self.team_2]) def _get_org_members(self) -> list[User]: return list( self.org.member_set.filter(user_id__in=[self.owner_user.id, self.user_2.id]).order_by( "user_email" ) ) def test_inviter(self) -> None: inviter = self.create_user(name="bob") member = self.create_member( organization=self.org, email="foo@sentry.io", inviter_id=inviter.id, invite_status=InviteStatus.REQUESTED_TO_JOIN.value, ) result = serialize(member, self.user_2, OrganizationMemberSerializer()) assert result["inviteStatus"] == "requested_to_join" assert result["inviterName"] == "bob" def test_user(self) -> None: user = self.create_user(name="bob") member = self.create_member( organization=self.org, user_id=user.id, ) result = serialize(member, self.user_2, OrganizationMemberSerializer()) assert result["user"]["id"] == str(user.id) assert result["user"]["name"] == "bob"
OrganizationMemberSerializerTest
python
django__django
tests/unmanaged_models/models.py
{ "start": 1852, "end": 2469 }
class ____(models.Model): a02 = models.ForeignKey(A02, models.CASCADE, db_column="a01_id") c02 = models.ForeignKey(C02, models.CASCADE, db_column="c01_id") class Meta: db_table = "d01" managed = False # These next models test the creation (or not) of many to many join tables # between managed and unmanaged models. A join table between two unmanaged # models shouldn't be automatically created (see #10647). # # Firstly, we need some models that will create the tables, purely so that the # tables are created. This is a test setup, not a requirement for unmanaged # models.
Intermediate
python
scrapy__scrapy
tests/test_engine.py
{ "start": 21086, "end": 22541 }
class ____(TestEngineDownloadAsync): """Test cases for ExecutionEngine.download().""" @staticmethod async def _download(engine: ExecutionEngine, request: Request) -> Response: return await maybe_deferred_to_future(engine.download(request)) def test_request_scheduled_signal(caplog): class TestScheduler(BaseScheduler): def __init__(self): self.enqueued = [] def enqueue_request(self, request: Request) -> bool: self.enqueued.append(request) return True def signal_handler(request: Request, spider: Spider) -> None: if "drop" in request.url: raise IgnoreRequest crawler = get_crawler(MySpider) engine = ExecutionEngine(crawler, lambda _: None) engine.downloader._slot_gc_loop.stop() scheduler = TestScheduler() async def start(): return yield engine._start = start() engine._slot = _Slot(False, Mock(), scheduler) crawler.signals.connect(signal_handler, signals.request_scheduled) keep_request = Request("https://keep.example") engine._schedule_request(keep_request) drop_request = Request("https://drop.example") caplog.set_level(DEBUG) engine._schedule_request(drop_request) assert scheduler.enqueued == [keep_request], ( f"{scheduler.enqueued!r} != [{keep_request!r}]" ) crawler.signals.disconnect(signal_handler, signals.request_scheduled)
TestEngineDownload
python
doocs__leetcode
solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.py
{ "start": 0, "end": 199 }
class ____: def maxProfit(self, prices: List[int]) -> int: ans, mi = 0, inf for v in prices: ans = max(ans, v - mi) mi = min(mi, v) return ans
Solution
python
pytorch__pytorch
torch/ao/nn/quantized/modules/activation.py
{ "start": 2526, "end": 3501 }
class ____(torch.nn.ELU): r"""This is the quantized equivalent of :class:`~torch.nn.ELU`. Args: scale: quantization scale of the output tensor zero_point: quantization zero point of the output tensor alpha: the alpha constant """ def __init__(self, scale, zero_point, alpha=1.0): super().__init__(alpha) self.scale = scale self.zero_point = zero_point def forward(self, input): return torch.ao.nn.quantized.functional.elu( input, self.scale, self.zero_point, self.alpha ) def _get_name(self): return "QuantizedELU" @staticmethod def from_float(mod, use_precomputed_fake_quant=False): scale, zero_point = mod.activation_post_process.calculate_qparams() return ELU(float(scale), int(zero_point), mod.alpha) @classmethod def from_reference(cls, mod, scale, zero_point): return cls(float(scale), int(zero_point), mod.alpha)
ELU
python
getsentry__sentry
src/sentry/backup/services/import_export/model.py
{ "start": 8009, "end": 8253 }
class ____(str, Enum): Unknown = "Unknown" IncorrectSiloModeForModel = "IncorrectSiloModeForModel" UnknownModel = "UnknownModel" UnexportableModel = "UnexportableModel" UnspecifiedScope = "UnspecifiedScope"
RpcExportErrorKind
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 54250, "end": 57060 }
class ____(Request): """ Remove old logs from task :param task: Task ID :type task: str :param allow_locked: Allow deleting events even if the task is locked :type allow_locked: bool :param threshold_sec: The amount of seconds ago to retain the log records. The older log records will be deleted. If not passed or 0 then all the log records for the task will be deleted :type threshold_sec: int """ _service = "events" _action = "clear_task_log" _version = "2.20" _schema = { "definitions": {}, "properties": { "allow_locked": { "default": False, "description": "Allow deleting events even if the task is locked", "type": "boolean", }, "task": {"description": "Task ID", "type": "string"}, "threshold_sec": { "description": "The amount of seconds ago to retain the log records. The older log records will be deleted. If not passed or 0 then all the log records for the task will be deleted", "type": "integer", }, }, "required": ["task"], "type": "object", } def __init__( self, task: str, allow_locked: Optional[bool] = False, threshold_sec: Optional[int] = None, **kwargs: Any ) -> None: super(ClearTaskLogRequest, self).__init__(**kwargs) self.task = task self.allow_locked = allow_locked self.threshold_sec = threshold_sec @schema_property("task") def task(self) -> str: return self._property_task @task.setter def task(self, value: str) -> None: if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("allow_locked") def allow_locked(self) -> Optional[bool]: return self._property_allow_locked @allow_locked.setter def allow_locked(self, value: Optional[bool]) -> None: if value is None: self._property_allow_locked = None return self.assert_isinstance(value, "allow_locked", (bool,)) self._property_allow_locked = value @schema_property("threshold_sec") def threshold_sec(self) -> Optional[int]: return self._property_threshold_sec @threshold_sec.setter def threshold_sec(self, value: Optional[int]) -> None: if value is None: self._property_threshold_sec = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "threshold_sec", six.integer_types) self._property_threshold_sec = value
ClearTaskLogRequest
python
pydantic__pydantic
pydantic-core/tests/validators/test_model_fields.py
{ "start": 33307, "end": 52122 }
class ____: a: int = 1 b: int = 2 c: str = 'ham' @pytest.mark.parametrize( 'input_value,expected', [ (ClassWithAttributes(), ({'a': 1, 'b': 2, 'c': 'ham'}, None, {'a', 'b', 'c'})), (MyDataclass(), ({'a': 1, 'b': 2, 'c': 'ham'}, None, {'a', 'b', 'c'})), (Cls(a=1, b=2, c='ham'), ({'a': 1, 'b': 2, 'c': 'ham'}, None, {'a', 'b', 'c'})), (dict(a=1, b=2, c='ham'), ({'a': 1, 'b': 2, 'c': 'ham'}, None, {'a', 'b', 'c'})), (Map(a=1, b=2, c='ham'), ({'a': 1, 'b': 2, 'c': 'ham'}, None, {'a', 'b', 'c'})), ((Cls(a=1, b=2), dict(c='ham')), ({'a': 1, 'b': 2, 'c': 'ham'}, None, {'a', 'b', 'c'})), ((Cls(a=1, b=2), dict(c='bacon')), ({'a': 1, 'b': 2, 'c': 'bacon'}, None, {'a', 'b', 'c'})), ((Cls(a=1, b=2, c='ham'), dict(c='bacon')), ({'a': 1, 'b': 2, 'c': 'bacon'}, None, {'a', 'b', 'c'})), ((Cls(a=1, b=2, c='ham'), dict(d='bacon')), ({'a': 1, 'b': 2, 'c': 'ham'}, None, {'a', 'b', 'c'})), # using type gives `__module__ == 'builtins'` (type('Testing', (), {}), Err('[type=model_attributes_type,')), ( '123', Err('Input should be a valid dictionary or object to extract fields from [type=model_attributes_type,'), ), ([(1, 2)], Err('type=model_attributes_type,')), (((1, 2),), Err('type=model_attributes_type,')), ], ids=repr, ) @pytest.mark.parametrize('from_attributes_mode', ['schema', 'validation']) def test_from_attributes(input_value, expected, from_attributes_mode): v = SchemaValidator( core_schema.model_fields_schema( fields={ 'a': core_schema.model_field(schema=core_schema.int_schema()), 'b': core_schema.model_field(schema=core_schema.int_schema()), 'c': core_schema.model_field(schema=core_schema.str_schema()), }, from_attributes=from_attributes_mode == 'schema', ) ) kwargs = {} if from_attributes_mode == 'validation': kwargs['from_attributes'] = True if isinstance(expected, Err): with pytest.raises(ValidationError, match=re.escape(expected.message)): val = v.validate_python(input_value, **kwargs) print(f'UNEXPECTED OUTPUT: {val!r}') else: output = v.validate_python(input_value, **kwargs) assert output == expected def test_from_attributes_type_error(): v = SchemaValidator( core_schema.model_fields_schema( fields={ 'a': core_schema.model_field(schema=core_schema.int_schema()), 'b': core_schema.model_field(schema=core_schema.int_schema()), 'c': core_schema.model_field(schema=core_schema.str_schema()), }, from_attributes=True, model_name='MyModel', ) ) with pytest.raises(ValidationError) as exc_info: v.validate_python('123') assert exc_info.value.errors(include_url=False) == [ { 'type': 'model_attributes_type', 'loc': (), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': '123', } ] with pytest.raises(ValidationError) as exc_info: v.validate_json('123') # insert_assert(exc_info.value.errors()) assert exc_info.value.errors(include_url=False) == [ { 'type': 'model_type', 'loc': (), 'msg': 'Input should be an object', 'input': 123, 'ctx': {'class_name': 'MyModel'}, } ] def test_from_attributes_by_name(): v = SchemaValidator( core_schema.model_fields_schema( fields={'a': core_schema.model_field(schema=core_schema.int_schema(), validation_alias='a_alias')}, from_attributes=True, ), config=CoreConfig(validate_by_name=True), ) assert v.validate_python(Cls(a_alias=1)) == ({'a': 1}, None, {'a'}) assert v.validate_python(Cls(a=1)) == ({'a': 1}, None, {'a'}) def test_from_attributes_override_true(): v = SchemaValidator( core_schema.model_fields_schema( fields={'a': core_schema.model_field(schema=core_schema.int_schema())}, from_attributes=False ) ) with pytest.raises(ValidationError, match='Input should be a valid dictionary'): v.validate_python(Cls(a=1)) assert v.validate_python(Cls(a=1), from_attributes=True) == ({'a': 1}, None, {'a'}) assert v.isinstance_python(Cls(a=1), from_attributes=True) is True assert v.isinstance_python(Cls(a=1)) is False def test_from_attributes_override_false(): v = SchemaValidator( core_schema.model_fields_schema( fields={'a': core_schema.model_field(schema=core_schema.int_schema())}, from_attributes=True ) ) with pytest.raises(ValidationError, match='Input should be a valid dictionary'): v.validate_python(Cls(a=1), from_attributes=False) assert v.validate_python(Cls(a=1)) == ({'a': 1}, None, {'a'}) assert v.isinstance_python(Cls(a=1)) is True assert v.isinstance_python(Cls(a=1), from_attributes=False) is False def test_from_attributes_missing(): class Foobar: def __init__(self): self.a = 1 self.b = 2 v = SchemaValidator( core_schema.model_fields_schema( fields={ 'a': core_schema.model_field(schema=core_schema.int_schema()), 'b': core_schema.model_field(schema=core_schema.int_schema()), 'c': core_schema.model_field(schema=core_schema.str_schema()), }, from_attributes=True, ) ) with pytest.raises(ValidationError) as exc_info: v.validate_python(Foobar()) assert exc_info.value.errors(include_url=False) == [ { 'type': 'missing', 'loc': ('c',), 'msg': 'Field required', 'input': HasRepr(IsStr(regex='.+Foobar object at.+')), } ] def test_from_attributes_error(): class Foobar: def __init__(self): self.a = 1 @property def b(self): raise RuntimeError('intentional error') v = SchemaValidator( core_schema.model_fields_schema( fields={ 'a': core_schema.model_field(schema=core_schema.int_schema()), 'b': core_schema.model_field(schema=core_schema.int_schema()), }, from_attributes=True, ) ) with pytest.raises(ValidationError) as exc_info: v.validate_python(Foobar()) assert exc_info.value.errors(include_url=False) == [ { 'type': 'get_attribute_error', 'loc': ('b',), 'msg': 'Error extracting attribute: RuntimeError: intentional error', 'input': HasRepr(IsStr(regex='.+Foobar object at.+')), 'ctx': {'error': 'RuntimeError: intentional error'}, } ] def test_from_attributes_extra(): def another_function(x): return x class Foobar: def __init__(self): self.a = 1 self.b = 2 self._private_attribute = 4 @property def c(self): return 'ham' @property def _private_property(self): return 'wrong' @property def property_error(self): raise RuntimeError('xxx') def bound_method(self): return f'wrong {self.a}' @staticmethod def static_method(): return 'wrong' # this is omitted along with the static method by the !PyFunction::is_type_of(attr) check in fields function_attribute = another_function @classmethod def class_method(cls): return 'wrong' @dataclass class MyDataclass: a: int = 1 b: int = 2 c: str = 'ham' _d: int = 4 v = SchemaValidator( core_schema.model_fields_schema( fields={'a': core_schema.model_field(schema=core_schema.int_schema())}, from_attributes=True, extra_behavior='allow', ) ) assert v.validate_python(Foobar()) == ({'a': 1}, {}, {'a'}) assert v.validate_python(MyDataclass()) == ({'a': 1}, {}, {'a'}) assert v.validate_python(Cls(a=1, b=2, c='ham')) == ({'a': 1}, {}, {'a'}) assert v.validate_python(Cls(a=1, b=datetime(2000, 1, 1))) == ({'a': 1}, {}, {'a'}) assert v.validate_python(Cls(a=1, b=datetime.now, c=lambda: 42)) == ({'a': 1}, {}, {'a'}) def test_from_attributes_extra_ignore_no_attributes_accessed() -> None: v = SchemaValidator( core_schema.model_fields_schema( fields={'a': core_schema.model_field(schema=core_schema.int_schema())}, from_attributes=True, extra_behavior='ignore', ) ) accessed: list[str] = [] class Source: a = 1 b = 2 def __getattribute__(self, name: str, /) -> Any: accessed.append(name) return super().__getattribute__(name) assert v.validate_python(Source()) == ({'a': 1}, None, {'a'}) assert 'a' in accessed and 'b' not in accessed def test_from_attributes_extra_forbid() -> None: class Source: a = 1 b = 2 v = SchemaValidator( core_schema.model_fields_schema( fields={'a': core_schema.model_field(schema=core_schema.int_schema())}, from_attributes=True, extra_behavior='forbid', ) ) assert v.validate_python(Source()) == ({'a': 1}, None, {'a'}) def foobar(): pass @pytest.mark.parametrize( 'input_value,expected', [ (Cls(a=1), {'a': 1}), (Cls(a=datetime.now), {'a': datetime.now}), (Cls(a=lambda: 42), {'a': HasRepr(IsStr(regex='.+<lambda>.+'))}), (Cls(a=sys.path), {'a': sys.path}), (Cls(a=foobar), {'a': foobar}), ], ids=repr, ) def test_from_attributes_function(input_value, expected): v = SchemaValidator( core_schema.model_fields_schema( fields={'a': core_schema.model_field(schema=core_schema.any_schema())}, from_attributes=True ) ) model_dict, model_extra, fields_set = v.validate_python(input_value) assert model_dict == expected assert model_extra is None assert fields_set == {'a'} def test_from_attributes_error_error(): class BadError(Exception): def __str__(self): raise RuntimeError('intentional error inside error') class Foobar: @property def x(self): raise BadError('intentional error') v = SchemaValidator( core_schema.model_fields_schema( fields={'x': core_schema.model_field(schema=core_schema.int_schema())}, from_attributes=True ) ) with pytest.raises(ValidationError) as exc_info: v.validate_python(Foobar()) assert exc_info.value.errors(include_url=False) == [ { 'type': 'get_attribute_error', 'loc': ('x',), 'msg': IsStr(regex=r'Error extracting attribute: \S+\.<locals>\.BadError: <exception str\(\) failed>'), 'input': HasRepr(IsStr(regex='.+Foobar object at.+')), 'ctx': {'error': IsStr(regex=r'\S+\.<locals>\.BadError: <exception str\(\) failed>')}, } ] class UnInitError: @property def x(self): raise RuntimeError with pytest.raises(ValidationError) as exc_info: v.validate_python(UnInitError()) assert exc_info.value.errors(include_url=False) == [ { 'type': 'get_attribute_error', 'loc': ('x',), 'msg': 'Error extracting attribute: RuntimeError', 'input': HasRepr(IsStr(regex='.+UnInitError object at.+')), 'ctx': {'error': 'RuntimeError'}, } ] @pytest.mark.parametrize( 'input_value,expected', [ ({'foo': {'bar': {'bat': '123'}}}, {'my_field': 123}), (Cls(foo=Cls(bar=Cls(bat='123'))), {'my_field': 123}), (Cls(foo={'bar': {'bat': '123'}}), {'my_field': 123}), (Cls(foo=[1, 2, 3, 4]), {'my_field': 4}), (Cls(foo=(1, 2, 3, 4)), {'my_field': 4}), (Cls(spam=5), {'my_field': 5}), (Cls(spam=1, foo=Cls(bar=Cls(bat=2))), {'my_field': 2}), (Cls(x='123'), Err(r'my_field\n +Field required \[type=missing,')), (Cls(x={2: 33}), Err(r'my_field\n +Field required \[type=missing,')), (Cls(foo='01234'), Err(r'my_field\n +Field required \[type=missing,')), (Cls(foo=[1]), Err(r'my_field\n +Field required \[type=missing,')), (Cls, Err(r'Input should be a valid dictionary')), ], ids=repr, ) def test_from_attributes_path(input_value, expected): v = SchemaValidator( core_schema.model_fields_schema( fields={ 'my_field': core_schema.model_field( validation_alias=[['foo', 'bar', 'bat'], ['foo', 3], ['spam']], schema=core_schema.int_schema() ) }, from_attributes=True, ), config=CoreConfig(loc_by_alias=False), ) if isinstance(expected, Err): with pytest.raises(ValidationError, match=expected.message): val = v.validate_python(input_value) print(f'UNEXPECTED OUTPUT: {val!r}') else: model_dict, model_extra, fields_set = v.validate_python(input_value) assert model_dict == expected assert model_extra is None assert fields_set == {'my_field'} def test_from_attributes_path_error(): class PropertyError: @property def foo(self): raise RuntimeError('intentional error') v = SchemaValidator( core_schema.model_fields_schema( fields={ 'my_field': core_schema.model_field( validation_alias=[['foo', 'bar', 'bat'], ['foo', 3], ['spam']], schema=core_schema.int_schema() ) }, from_attributes=True, ) ) with pytest.raises(ValidationError) as exc_info: v.validate_python(PropertyError()) assert exc_info.value.errors(include_url=False) == [ { 'type': 'get_attribute_error', 'loc': ('my_field',), 'msg': 'Error extracting attribute: RuntimeError: intentional error', 'input': HasRepr(IsStr(regex='.+PropertyError object at.+')), 'ctx': {'error': 'RuntimeError: intentional error'}, } ] def test_alias_extra(py_and_json: PyAndJson): v = py_and_json( { 'type': 'model-fields', 'extra_behavior': 'allow', 'fields': { 'field_a': { 'validation_alias': [['FieldA'], ['foo', 2]], 'type': 'model-field', 'schema': {'type': 'int'}, } }, }, {'loc_by_alias': False}, ) assert v.validate_test({'FieldA': 1}) == ({'field_a': 1}, {}, {'field_a'}) assert v.validate_test({'foo': [1, 2, 3]}) == ({'field_a': 3}, {}, {'field_a'}) # used_keys should be populated either though validation fails so "FieldA" is skipped in extra with pytest.raises(ValidationError) as exc_info: assert v.validate_test({'FieldA': '...'}) == ({'field_a': 1}, {}, {'field_a'}) assert exc_info.value.errors(include_url=False) == [ { 'type': 'int_parsing', 'loc': ('field_a',), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': '...', } ] def test_alias_extra_from_attributes(): v = SchemaValidator( core_schema.model_fields_schema( extra_behavior='allow', from_attributes=True, fields={ 'field_a': core_schema.model_field( validation_alias=[['FieldA'], ['foo', 2]], schema=core_schema.int_schema() ) }, ) ) assert v.validate_python({'FieldA': 1}) == ({'field_a': 1}, {}, {'field_a'}) assert v.validate_python(Cls(FieldA=1)) == ({'field_a': 1}, {}, {'field_a'}) assert v.validate_python(Cls(foo=[1, 2, 3])) == ({'field_a': 3}, {}, {'field_a'}) assert v.validate_python({'foo': [1, 2, 3]}) == ({'field_a': 3}, {}, {'field_a'}) def test_alias_extra_by_name(py_and_json: PyAndJson): v = py_and_json( { 'type': 'model-fields', 'extra_behavior': 'allow', 'from_attributes': True, 'fields': {'field_a': {'validation_alias': 'FieldA', 'type': 'model-field', 'schema': {'type': 'int'}}}, }, config=CoreConfig(validate_by_name=True), ) assert v.validate_test({'FieldA': 1}) == ({'field_a': 1}, {}, {'field_a'}) assert v.validate_test({'field_a': 1}) == ({'field_a': 1}, {}, {'field_a'}) assert v.validate_python(Cls(FieldA=1)) == ({'field_a': 1}, {}, {'field_a'}) assert v.validate_python(Cls(field_a=1)) == ({'field_a': 1}, {}, {'field_a'}) def test_alias_extra_forbid(py_and_json: PyAndJson): v = py_and_json( { 'type': 'model-fields', 'extra_behavior': 'forbid', 'fields': {'field_a': {'type': 'model-field', 'validation_alias': 'FieldA', 'schema': {'type': 'int'}}}, } ) assert v.validate_test({'FieldA': 1}) == ({'field_a': 1}, None, {'field_a'}) def test_with_default_factory(): v = SchemaValidator( core_schema.model_fields_schema( fields={ 'x': core_schema.model_field( schema=core_schema.with_default_schema( schema=core_schema.str_schema(), default_factory=lambda: 'pikachu' ) ) } ) ) assert v.validate_python({}) == ({'x': 'pikachu'}, None, set()) assert v.validate_python({'x': 'bulbi'}) == ({'x': 'bulbi'}, None, {'x'}) @pytest.mark.parametrize( 'default_factory,error_message', [ (lambda: 1 + 'a', "unsupported operand type(s) for +: 'int' and 'str'"), (lambda x: 'a' + x, "<lambda>() missing 1 required positional argument: 'x'"), ], ) def test_bad_default_factory(default_factory, error_message): v = SchemaValidator( core_schema.model_fields_schema( fields={ 'x': core_schema.model_field( schema=core_schema.with_default_schema( schema=core_schema.str_schema(), default_factory=default_factory ) ) } ) ) with pytest.raises(TypeError, match=re.escape(error_message)): v.validate_python({})
MyDataclass
python
walkccc__LeetCode
solutions/3280. Convert Date to Binary/3280.py
{ "start": 0, "end": 318 }
class ____: def convertDateToBinary(self, date: str) -> str: year, month, day = map(int, date.split('-')) def toBinary(value: int) -> str: """Converts an integer to binary without leading zeros.""" return bin(value)[2:] return '-'.join([toBinary(year), toBinary(month), toBinary(day)])
Solution
python
django__django
tests/contenttypes_tests/test_models.py
{ "start": 13256, "end": 14199 }
class ____(TestCase): def test_querysets_required(self): msg = ( "GenericPrefetch.__init__() missing 1 required " "positional argument: 'querysets'" ) with self.assertRaisesMessage(TypeError, msg): GenericPrefetch("question") def test_values_queryset(self): msg = "Prefetch querysets cannot use raw(), values(), and values_list()." with self.assertRaisesMessage(ValueError, msg): GenericPrefetch("question", [Author.objects.values("pk")]) with self.assertRaisesMessage(ValueError, msg): GenericPrefetch("question", [Author.objects.values_list("pk")]) def test_raw_queryset(self): msg = "Prefetch querysets cannot use raw(), values(), and values_list()." with self.assertRaisesMessage(ValueError, msg): GenericPrefetch("question", [Author.objects.raw("select pk from author")])
GenericPrefetchTests
python
huggingface__transformers
src/transformers/models/flex_olmo/modular_flex_olmo.py
{ "start": 10636, "end": 10835 }
class ____(OlmoeSparseMoeBlock): pass # FlexOlmo decoder layer is identical to OlmoE decoder layer except: # - Norm is applied after attention/feedforward rather than before.
FlexOlmoSparseMoeBlock
python
numba__numba
numba/core/base.py
{ "start": 44302, "end": 45673 }
class ____(object): def __init__(self, fn): self.func = fn # store this to help with debug def __call__(self): """Wrap function for missing ``loc`` keyword argument. Otherwise, return the original *fn*. """ fn = self.func if not _has_loc(fn): def wrapper(*args, **kwargs): kwargs.pop('loc') # drop unused loc return fn(*args, **kwargs) # Copy the following attributes from the wrapped. # Following similar implementation as functools.wraps but # ignore attributes if not available (i.e fix py2.7) attrs = '__name__', 'libs' for attr in attrs: try: val = getattr(fn, attr) except AttributeError: pass else: setattr(wrapper, attr, val) return wrapper else: return fn def __repr__(self): return "<wrapped %s>" % self.func @utils.runonce def _initialize_llvm_lock_event(): """Initial event triggers for LLVM lock """ def enter_fn(): event.start_event("numba:llvm_lock") def exit_fn(): event.end_event("numba:llvm_lock") ll.ffi.register_lock_callback(enter_fn, exit_fn) _initialize_llvm_lock_event()
_wrap_missing_loc
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/execution_plan.py
{ "start": 311, "end": 644 }
class ____(graphene.Union): class Meta: types = ( GrapheneExecutionPlan, GrapheneRunConfigValidationInvalid, GraphenePipelineNotFoundError, GrapheneInvalidSubsetError, GraphenePythonError, ) name = "ExecutionPlanOrError"
GrapheneExecutionPlanOrError
python
yaml__pyyaml
lib/yaml/loader.py
{ "start": 224, "end": 548 }
class ____(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver): def __init__(self, stream): Reader.__init__(self, stream) Scanner.__init__(self) Parser.__init__(self) Composer.__init__(self) BaseConstructor.__init__(self) BaseResolver.__init__(self)
BaseLoader
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/test_fail/package.py
{ "start": 217, "end": 678 }
class ____(Package): """This package has a test method that fails in a subprocess.""" homepage = "http://www.example.com/test-failure" url = "http://www.test-failure.test/test-failure-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") def install(self, spec, prefix): mkdirp(prefix.bin) def test_fails(self): """trigger test failure""" unknown = which("unknown-program") unknown()
TestFail
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 172176, "end": 174251 }
class ____(TestCase): def test_r_less_than_n(self): iterable = 'abcdefg' r = 4 first_index = {} for index, element in enumerate( combinations_with_replacement(iterable, r) ): actual = mi.combination_with_replacement_index(element, iterable) expected = first_index.setdefault(element, index) self.assertEqual(actual, expected) def test_r_equal_to_n(self): iterable = 'abcd' r = len(iterable) first_index = {} for index, element in enumerate( combinations_with_replacement(iterable, r=r) ): actual = mi.combination_with_replacement_index(element, iterable) expected = first_index.setdefault(element, index) self.assertEqual(actual, expected) def test_multiplicity(self): iterable = 'abacba' r = 3 first_index = {} for index, element in enumerate( combinations_with_replacement(iterable, r) ): actual = mi.combination_with_replacement_index(element, iterable) expected = first_index.setdefault(element, index) self.assertEqual(actual, expected) def test_null(self): actual = mi.combination_with_replacement_index(tuple(), []) expected = 0 self.assertEqual(actual, expected) def test_long(self): actual = mi.combination_with_replacement_index( (22, 65, 68, 81), range(90) ) expected = 2000000 self.assertEqual(actual, expected) def test_invalid_order(self): with self.assertRaises(ValueError): mi.combination_with_replacement_index(tuple('acb'), 'abcde') def test_invalid_large(self): with self.assertRaises(ValueError): mi.combination_with_replacement_index(tuple('abcdefg'), 'abcdef') def test_invalid_match(self): with self.assertRaises(ValueError): mi.combination_with_replacement_index(tuple('axe'), 'abcde')
CombinationWithReplacementIndexTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py
{ "start": 3971, "end": 5212 }
class ____(Base1): value: Base1 def handler(node: Base1) -> Any: if isinstance(node, Sub1_1): reveal_type(node.value, expected_text="str") elif isinstance(node, Sub1_2): reveal_type(node.value, expected_text="Base1") if isinstance(node.value, Sub1_1): reveal_type(node.value, expected_text="Sub1_1") def func8a(a: int | list[int] | dict[str, int] | None): if isinstance(a, (str, (int, list, type(None)))): reveal_type(a, expected_text="int | list[int] | None") else: reveal_type(a, expected_text="dict[str, int]") def func8b(a: int | list[int] | dict[str, int] | None): if isinstance(a, str | int | list | type(None)): reveal_type(a, expected_text="int | list[int] | None") else: reveal_type(a, expected_text="dict[str, int]") TA1 = str | int | list | None def func8c(a: int | list[int] | dict[str, int] | None): if isinstance(a, TA1): reveal_type(a, expected_text="int | list[int] | None") else: reveal_type(a, expected_text="dict[str, int]") def func9(a: int | None): if not isinstance(a, NoneType): reveal_type(a, expected_text="int") else: reveal_type(a, expected_text="None")
Sub1_2
python
pandas-dev__pandas
asv_bench/benchmarks/multiindex_object.py
{ "start": 9161, "end": 9864 }
class ____: params = [ (("Int64", NA), ("int64", 0)), ] param_names = ["dtype_val"] def setup(self, dtype_val): level = Series( [1, 2, dtype_val[1], dtype_val[1]] + list(range(1_000_000)), dtype=dtype_val[0], ) self.midx = MultiIndex.from_arrays([level, level]) level_dups = Series( [1, 2, dtype_val[1], dtype_val[1]] + list(range(500_000)) * 2, dtype=dtype_val[0], ) self.midx_dups = MultiIndex.from_arrays([level_dups, level_dups]) def time_unique(self, dtype_val): self.midx.unique() def time_unique_dups(self, dtype_val): self.midx_dups.unique()
Unique
python
walkccc__LeetCode
solutions/1381. Design a Stack With Increment Operation/1381.py
{ "start": 0, "end": 730 }
class ____: def __init__(self, maxSize: int): self.maxSize = maxSize self.stack = [] # pendingIncrements[i] := the pending increment for stack[0..i]. self.pendingIncrements = [] def push(self, x: int) -> None: if len(self.stack) == self.maxSize: return self.stack.append(x) self.pendingIncrements.append(0) def pop(self) -> int: if not self.stack: return -1 if len(self.stack) > 1: self.pendingIncrements[-2] += self.pendingIncrements[-1] return self.stack.pop() + self.pendingIncrements.pop() def increment(self, k: int, val: int) -> None: if not self.stack: return i = min(k - 1, len(self.stack) - 1) self.pendingIncrements[i] += val
CustomStack
python
django__django
django/contrib/gis/db/models/functions.py
{ "start": 18539, "end": 18579 }
class ____(GeoFunc): arity = 1
Reverse
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 188646, "end": 189717 }
class ____(sgqlc.types.Input): """Autogenerated input type of CreateProject""" __schema__ = github_schema __field_names__ = ("owner_id", "name", "body", "template", "repository_ids", "client_mutation_id") owner_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="ownerId") """The owner ID to create the project under.""" name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") """The name of project.""" body = sgqlc.types.Field(String, graphql_name="body") """The description of project.""" template = sgqlc.types.Field(ProjectTemplate, graphql_name="template") """The name of the GitHub-provided template.""" repository_ids = sgqlc.types.Field(sgqlc.types.list_of(sgqlc.types.non_null(ID)), graphql_name="repositoryIds") """A list of repository IDs to create as linked repositories for the project """ client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
CreateProjectInput
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/asyncpg.py
{ "start": 23522, "end": 30591 }
class ____( AsyncAdapt_terminate, AsyncAdapt_dbapi_connection ): _cursor_cls = AsyncAdapt_asyncpg_cursor _ss_cursor_cls = AsyncAdapt_asyncpg_ss_cursor _connection: _AsyncpgConnection _transaction: Optional[_AsyncpgTransaction] __slots__ = ( "isolation_level", "_isolation_setting", "readonly", "deferrable", "_transaction", "_prepared_statement_cache", "_prepared_statement_name_func", "_invalidate_schema_cache_asof", ) def __init__( self, dbapi, connection, prepared_statement_cache_size=100, prepared_statement_name_func=None, ): super().__init__(dbapi, connection) self.isolation_level = self._isolation_setting = None self.readonly = False self.deferrable = False self._transaction = None self._invalidate_schema_cache_asof = time.time() if prepared_statement_cache_size: self._prepared_statement_cache = util.LRUCache( prepared_statement_cache_size ) else: self._prepared_statement_cache = None if prepared_statement_name_func: self._prepared_statement_name_func = prepared_statement_name_func else: self._prepared_statement_name_func = self._default_name_func async def _check_type_cache_invalidation(self, invalidate_timestamp): if invalidate_timestamp > self._invalidate_schema_cache_asof: await self._connection.reload_schema_state() self._invalidate_schema_cache_asof = invalidate_timestamp async def _prepare(self, operation, invalidate_timestamp): await self._check_type_cache_invalidation(invalidate_timestamp) cache = self._prepared_statement_cache if cache is None: prepared_stmt = await self._connection.prepare( operation, name=self._prepared_statement_name_func() ) attributes = prepared_stmt.get_attributes() return prepared_stmt, attributes # asyncpg uses a type cache for the "attributes" which seems to go # stale independently of the PreparedStatement itself, so place that # collection in the cache as well. if operation in cache: prepared_stmt, attributes, cached_timestamp = cache[operation] # preparedstatements themselves also go stale for certain DDL # changes such as size of a VARCHAR changing, so there is also # a cross-connection invalidation timestamp if cached_timestamp > invalidate_timestamp: return prepared_stmt, attributes prepared_stmt = await self._connection.prepare( operation, name=self._prepared_statement_name_func() ) attributes = prepared_stmt.get_attributes() cache[operation] = (prepared_stmt, attributes, time.time()) return prepared_stmt, attributes @classmethod def _handle_exception_no_connection( cls, dbapi: Any, error: Exception ) -> NoReturn: if not isinstance(error, AsyncAdapt_asyncpg_dbapi.Error): exception_mapping = dbapi._asyncpg_error_translate for super_ in type(error).__mro__: if super_ in exception_mapping: message = error.args[0] translated_error = exception_mapping[super_]( message, error ) raise translated_error from error super()._handle_exception_no_connection(dbapi, error) def _handle_exception(self, error: Exception) -> NoReturn: if self._connection.is_closed(): self._transaction = None super()._handle_exception(error) @property def autocommit(self): return self.isolation_level == "autocommit" @autocommit.setter def autocommit(self, value): if value: self.isolation_level = "autocommit" else: self.isolation_level = self._isolation_setting def ping(self): try: _ = await_(self._async_ping()) except Exception as error: self._handle_exception(error) async def _async_ping(self): if self._transaction is None and self.isolation_level != "autocommit": # create a tranasction explicitly to support pgbouncer # transaction mode. See #10226 tr = self._connection.transaction() await tr.start() try: await self._connection.fetchrow(";") finally: await tr.rollback() else: await self._connection.fetchrow(";") def set_isolation_level(self, level): self.rollback() self.isolation_level = self._isolation_setting = level async def _start_transaction(self): if self.isolation_level == "autocommit": return assert self._transaction is None try: self._transaction = self._connection.transaction( isolation=self.isolation_level, readonly=self.readonly, deferrable=self.deferrable, ) await self._transaction.start() except Exception as error: self._handle_exception(error) async def _call_and_discard(self, fn: Callable[[], Awaitable[Any]]): try: await fn() finally: # if asyncpg fn was actually called, then whether or # not it raised or succeeded, the transaction is done, discard it self._transaction = None def rollback(self): if self._transaction is not None: try: await_(self._call_and_discard(self._transaction.rollback)) except Exception as error: # don't dereference asyncpg transaction if we didn't # actually try to call rollback() on it self._handle_exception(error) def commit(self): if self._transaction is not None: try: await_(self._call_and_discard(self._transaction.commit)) except Exception as error: # don't dereference asyncpg transaction if we didn't # actually try to call commit() on it self._handle_exception(error) def close(self): self.rollback() await_(self._connection.close()) def _terminate_handled_exceptions(self): return super()._terminate_handled_exceptions() + ( self.dbapi.asyncpg.PostgresError, ) async def _terminate_graceful_close(self) -> None: # timeout added in asyncpg 0.14.0 December 2017 await self._connection.close(timeout=2) self._transaction = None def _terminate_force_close(self) -> None: self._connection.terminate() self._transaction = None @staticmethod def _default_name_func(): return None
AsyncAdapt_asyncpg_connection
python
huggingface__transformers
src/transformers/models/unispeech/modular_unispeech.py
{ "start": 12281, "end": 17347 }
class ____(UniSpeechPreTrainedModel): def __init__(self, config: UniSpeechConfig): super().__init__(config) self.unispeech = UniSpeechModel(config) self.dropout_features = nn.Dropout(config.feat_quantizer_dropout) self.quantizer = UniSpeechGumbelVectorQuantizer(config) self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim) self.project_hid = nn.Linear(config.proj_codevector_dim, config.hidden_size) self.ctc_proj = nn.Linear(config.hidden_size, config.num_ctc_classes) self.dropout = nn.Dropout(config.final_dropout) # Initialize weights and apply final processing self.post_init() def set_gumbel_temperature(self, temperature: int): """ Set the Gumbel softmax temperature to a given value. Only necessary for training """ self.quantizer.temperature = temperature def freeze_feature_encoder(self): """ Calling this function will disable the gradient computation for the feature encoder so that its parameter will not be updated during training. """ self.unispeech.feature_extractor._freeze_parameters() @staticmethod def compute_contrastive_logits( target_features: torch.FloatTensor, negative_features: torch.FloatTensor, predicted_features: torch.FloatTensor, temperature: int = 1, ): """ Compute logits for contrastive loss based using cosine similarity as the distance measure between `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied. """ target_features = torch.cat([target_features, negative_features], dim=0) logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1) logits = logits.type_as(target_features) # apply temperature logits = logits / temperature return logits @auto_docstring def forward( self, input_values: Optional[torch.Tensor], attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple, UniSpeechForPreTrainingOutput]: r""" Example: ```python >>> import torch >>> from transformers import AutoFeatureExtractor, UniSpeechForPreTraining >>> feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/unispeech-large-1500h-cv") >>> model = UniSpeechForPreTraining.from_pretrained("microsoft/unispeech-large-1500h-cv") >>> # TODO: Add full pretraining example ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.unispeech( input_values, attention_mask=attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) transformer_features = outputs[0] # quantize all (unmasked) extracted features and project to final vq dim extract_features = self.dropout_features(outputs[1]) quantized_features, codevector_perplexity = self.quantizer(extract_features) # project quantized features twice quantized_features = self.project_q(quantized_features.to(self.project_q.weight.dtype)) quantized_features = self.project_hid(quantized_features) prob_replace_matrix = torch.empty(transformer_features.size(0), transformer_features.size(1)).fill_( self.config.replace_prob ) prob_replace_matrix = prob_replace_matrix.transpose(0, 1) sampled_replace_matrix = torch.bernoulli(prob_replace_matrix).bool().to(transformer_features.device) sampled_replace_matrix = sampled_replace_matrix.transpose(0, 1) sampled_replace_matrix = sampled_replace_matrix.unsqueeze(-1) logits = transformer_features.masked_fill(sampled_replace_matrix, 0.0) + ( quantized_features.masked_fill(~sampled_replace_matrix, 0.0) ) # project to ctc units logits = self.dropout(logits) logits = self.ctc_proj(logits) # TODO(PVP) - add negative sampling & loss computation loss = None if not return_dict: if loss is not None: return (loss, transformer_features, quantized_features, codevector_perplexity) + outputs[2:] return (transformer_features, quantized_features, codevector_perplexity) + outputs[2:] return UniSpeechForPreTrainingOutput( loss=loss, projected_states=transformer_features, projected_quantized_states=quantized_features, codevector_perplexity=codevector_perplexity, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
UniSpeechForPreTraining
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/mappedoperator.py
{ "start": 6017, "end": 11432 }
class ____: """ An "intermediate state" returned by ``BaseOperator.partial()``. This only exists at Dag-parsing time; the only intended usage is for the user to call ``.expand()`` on it at some point (usually in a method chain) to create a ``MappedOperator`` to add into the Dag. """ operator_class: type[BaseOperator] kwargs: dict[str, Any] params: ParamsDict | dict _expand_called: bool = False # Set when expand() is called to ease user debugging. def __attrs_post_init__(self): validate_mapping_kwargs(self.operator_class, "partial", self.kwargs) def __repr__(self) -> str: args = ", ".join(f"{k}={v!r}" for k, v in self.kwargs.items()) return f"{self.operator_class.__name__}.partial({args})" def __del__(self): if not self._expand_called: try: task_id = repr(self.kwargs["task_id"]) except KeyError: task_id = f"at {hex(id(self))}" warnings.warn(f"Task {task_id} was never mapped!", category=UserWarning, stacklevel=1) def expand(self, **mapped_kwargs: OperatorExpandArgument) -> MappedOperator: if not mapped_kwargs: raise TypeError("no arguments to expand against") validate_mapping_kwargs(self.operator_class, "expand", mapped_kwargs) prevent_duplicates(self.kwargs, mapped_kwargs, fail_reason="unmappable or already specified") # Since the input is already checked at parse time, we can set strict # to False to skip the checks on execution. return self._expand(DictOfListsExpandInput(mapped_kwargs), strict=False) def expand_kwargs(self, kwargs: OperatorExpandKwargsArgument, *, strict: bool = True) -> MappedOperator: from airflow.sdk.definitions.xcom_arg import XComArg if isinstance(kwargs, Sequence): for item in kwargs: if not isinstance(item, (XComArg, Mapping)): raise TypeError(f"expected XComArg or list[dict], not {type(kwargs).__name__}") elif not isinstance(kwargs, XComArg): raise TypeError(f"expected XComArg or list[dict], not {type(kwargs).__name__}") return self._expand(ListOfDictsExpandInput(kwargs), strict=strict) def _expand(self, expand_input: ExpandInput, *, strict: bool) -> MappedOperator: from airflow.providers.standard.operators.empty import EmptyOperator from airflow.providers.standard.utils.skipmixin import SkipMixin from airflow.sdk import BaseSensorOperator self._expand_called = True ensure_xcomarg_return_value(expand_input.value) partial_kwargs = self.kwargs.copy() task_id = partial_kwargs.pop("task_id") dag = partial_kwargs.pop("dag") task_group = partial_kwargs.pop("task_group") start_date = partial_kwargs.pop("start_date", None) end_date = partial_kwargs.pop("end_date", None) try: operator_name = self.operator_class.custom_operator_name # type: ignore except AttributeError: operator_name = self.operator_class.__name__ op = MappedOperator( operator_class=self.operator_class, expand_input=expand_input, partial_kwargs=partial_kwargs, task_id=task_id, params=self.params, operator_extra_links=self.operator_class.operator_extra_links, template_ext=self.operator_class.template_ext, template_fields=self.operator_class.template_fields, template_fields_renderers=self.operator_class.template_fields_renderers, ui_color=self.operator_class.ui_color, ui_fgcolor=self.operator_class.ui_fgcolor, is_empty=issubclass(self.operator_class, EmptyOperator), is_sensor=issubclass(self.operator_class, BaseSensorOperator), can_skip_downstream=issubclass(self.operator_class, SkipMixin), task_module=self.operator_class.__module__, task_type=self.operator_class.__name__, operator_name=operator_name, dag=dag, task_group=task_group, start_date=start_date, end_date=end_date, disallow_kwargs_override=strict, # For classic operators, this points to expand_input because kwargs # to BaseOperator.expand() contribute to operator arguments. expand_input_attr="expand_input", # TODO: Move these to task SDK's BaseOperator and remove getattr start_trigger_args=getattr(self.operator_class, "start_trigger_args", None), start_from_trigger=bool(getattr(self.operator_class, "start_from_trigger", False)), ) return op @attrs.define( kw_only=True, # Disable custom __getstate__ and __setstate__ generation since it interacts # badly with Airflow's Dag serialization and pickling. When a mapped task is # deserialized, subclasses are coerced into MappedOperator, but when it goes # through Dag pickling, all attributes defined in the subclasses are dropped # by attrs's custom state management. Since attrs does not do anything too # special here (the logic is only important for slots=True), we use Python's # built-in implementation, which works (as proven by good old BaseOperator). getstate_setstate=False, )
OperatorPartial
python
python-openxml__python-docx
tests/image/test_png.py
{ "start": 1980, "end": 4914 }
class ____: def it_can_parse_the_headers_of_a_PNG_stream( self, stream_, _Chunks_, _PngParser__init_, chunks_ ): png_parser = _PngParser.parse(stream_) _Chunks_.from_stream.assert_called_once_with(stream_) _PngParser__init_.assert_called_once_with(ANY, chunks_) assert isinstance(png_parser, _PngParser) def it_knows_the_image_width_and_height(self, dimensions_fixture): png_parser, px_width, px_height = dimensions_fixture assert png_parser.px_width == px_width assert png_parser.px_height == px_height def it_knows_the_image_dpi(self, dpi_fixture): png_parser, horz_dpi, vert_dpi = dpi_fixture assert png_parser.horz_dpi == horz_dpi assert png_parser.vert_dpi == vert_dpi def it_defaults_image_dpi_to_72(self, no_dpi_fixture): png_parser = no_dpi_fixture assert png_parser.horz_dpi == 72 assert png_parser.vert_dpi == 72 # fixtures ------------------------------------------------------- @pytest.fixture def _Chunks_(self, request, chunks_): _Chunks_ = class_mock(request, "docx.image.png._Chunks") _Chunks_.from_stream.return_value = chunks_ return _Chunks_ @pytest.fixture def chunks_(self, request): return instance_mock(request, _Chunks) @pytest.fixture def dimensions_fixture(self, chunks_): px_width, px_height = 12, 34 chunks_.IHDR.px_width = px_width chunks_.IHDR.px_height = px_height png_parser = _PngParser(chunks_) return png_parser, px_width, px_height @pytest.fixture def dpi_fixture(self, chunks_): horz_px_per_unit, vert_px_per_unit, units_specifier = 1654, 945, 1 horz_dpi, vert_dpi = 42, 24 chunks_.pHYs.horz_px_per_unit = horz_px_per_unit chunks_.pHYs.vert_px_per_unit = vert_px_per_unit chunks_.pHYs.units_specifier = units_specifier png_parser = _PngParser(chunks_) return png_parser, horz_dpi, vert_dpi @pytest.fixture(params=[(-1, -1), (0, 1000), (None, 1000), (1, 0), (1, None)]) def no_dpi_fixture(self, request, chunks_): """ Scenarios are: 1) no pHYs chunk in PNG stream, 2) units specifier other than 1; 3) px_per_unit is 0; 4) px_per_unit is None """ units_specifier, px_per_unit = request.param if units_specifier == -1: chunks_.pHYs = None else: chunks_.pHYs.horz_px_per_unit = px_per_unit chunks_.pHYs.vert_px_per_unit = px_per_unit chunks_.pHYs.units_specifier = units_specifier png_parser = _PngParser(chunks_) return png_parser @pytest.fixture def _PngParser__init_(self, request): return initializer_mock(request, _PngParser) @pytest.fixture def stream_(self, request): return instance_mock(request, io.BytesIO)
Describe_PngParser
python
pypa__setuptools
setuptools/_distutils/tests/test_file_util.py
{ "start": 423, "end": 3522 }
class ____: def test_move_file_verbosity(self, caplog): jaraco.path.build({self.source: 'some content'}) move_file(self.source, self.target, verbose=False) assert not caplog.messages # back to original state move_file(self.target, self.source, verbose=False) move_file(self.source, self.target, verbose=True) wanted = [f'moving {self.source} -> {self.target}'] assert caplog.messages == wanted # back to original state move_file(self.target, self.source, verbose=False) caplog.clear() # now the target is a dir os.mkdir(self.target_dir) move_file(self.source, self.target_dir, verbose=True) wanted = [f'moving {self.source} -> {self.target_dir}'] assert caplog.messages == wanted def test_move_file_exception_unpacking_rename(self): # see issue 22182 with ( mock.patch("os.rename", side_effect=OSError("wrong", 1)), pytest.raises(DistutilsFileError), ): jaraco.path.build({self.source: 'spam eggs'}) move_file(self.source, self.target, verbose=False) def test_move_file_exception_unpacking_unlink(self): # see issue 22182 with ( mock.patch("os.rename", side_effect=OSError(errno.EXDEV, "wrong")), mock.patch("os.unlink", side_effect=OSError("wrong", 1)), pytest.raises(DistutilsFileError), ): jaraco.path.build({self.source: 'spam eggs'}) move_file(self.source, self.target, verbose=False) def test_copy_file_hard_link(self): jaraco.path.build({self.source: 'some content'}) # Check first that copy_file() will not fall back on copying the file # instead of creating the hard link. try: os.link(self.source, self.target) except OSError as e: self.skipTest(f'os.link: {e}') else: self.target.unlink() st = os.stat(self.source) copy_file(self.source, self.target, link='hard') st2 = os.stat(self.source) st3 = os.stat(self.target) assert os.path.samestat(st, st2), (st, st2) assert os.path.samestat(st2, st3), (st2, st3) assert self.source.read_text(encoding='utf-8') == 'some content' def test_copy_file_hard_link_failure(self): # If hard linking fails, copy_file() falls back on copying file # (some special filesystems don't support hard linking even under # Unix, see issue #8876). jaraco.path.build({self.source: 'some content'}) st = os.stat(self.source) with mock.patch("os.link", side_effect=OSError(0, "linking unsupported")): copy_file(self.source, self.target, link='hard') st2 = os.stat(self.source) st3 = os.stat(self.target) assert os.path.samestat(st, st2), (st, st2) assert not os.path.samestat(st2, st3), (st2, st3) for fn in (self.source, self.target): assert fn.read_text(encoding='utf-8') == 'some content'
TestFileUtil
python
pydata__xarray
xarray/core/utils.py
{ "start": 15658, "end": 17388 }
class ____(Frozen[K, V]): """ Class which behaves like a Mapping but warns if the values are accessed. Temporary object to aid in deprecation cycle of `Dataset.dims` (see GH issue #8496). `Dataset.dims` is being changed from returning a mapping of dimension names to lengths to just returning a frozen set of dimension names (to increase consistency with `DataArray.dims`). This class retains backwards compatibility but raises a warning only if the return value of ds.dims is used like a dictionary (i.e. it doesn't raise a warning if used in a way that would also be valid for a FrozenSet, e.g. iteration). """ __slots__ = ("mapping",) def _warn(self) -> None: emit_user_level_warning( "The return type of `Dataset.dims` will be changed to return a set of dimension names in future, " "in order to be more consistent with `DataArray.dims`. To access a mapping from dimension names to lengths, " "please use `Dataset.sizes`.", FutureWarning, ) def __getitem__(self, key: K) -> V: self._warn() return super().__getitem__(key) @overload def get(self, key: K, /) -> V | None: ... @overload def get(self, key: K, /, default: V | T) -> V | T: ... def get(self, key: K, default: T | None = None) -> V | T | None: self._warn() return super().get(key, default) def keys(self) -> KeysView[K]: self._warn() return super().keys() def items(self) -> ItemsView[K, V]: self._warn() return super().items() def values(self) -> ValuesView[V]: self._warn() return super().values()
FrozenMappingWarningOnValuesAccess
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_comment06.py
{ "start": 315, "end": 1099 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("comment06.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with comments.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.write_comment("A1", "Some text") worksheet.write_comment("A2", "Some text") worksheet.write_comment("A3", "Some text", {"visible": True}) worksheet.write_comment("A4", "Some text") worksheet.write_comment("A5", "Some text") worksheet.set_comments_author("John") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
doocs__leetcode
solution/0300-0399/0377.Combination Sum IV/Solution.py
{ "start": 0, "end": 270 }
class ____: def combinationSum4(self, nums: List[int], target: int) -> int: f = [1] + [0] * target for i in range(1, target + 1): for x in nums: if i >= x: f[i] += f[i - x] return f[target]
Solution
python
tensorflow__tensorflow
tensorflow/lite/python/lite.py
{ "start": 60512, "end": 63612 }
class ____(TFLiteConverterBaseV2): """Converts the given SavedModel into TensorFlow Lite model. Attributes: saved_model_dir: Directory of the SavedModel. """ def __init__( self, saved_model_dir, saved_model_tags=None, saved_model_exported_names=None, trackable_obj=None, ): """Constructor for TFLiteConverter. Args: saved_model_dir: Directory of the SavedModel. saved_model_tags: Set of tags identifying the MetaGraphDef within the SavedModel to analyze. All tags in the tag set must be present. (default {tf.saved_model.SERVING}). saved_model_exported_names: Names to be exported when the saved model import path is on. trackable_obj: tf.AutoTrackable object associated with `funcs`. A reference to this object needs to be maintained so that Variables do not get garbage collected since functions have a weak reference to Variables. This is only required when the tf.AutoTrackable object is not maintained by the user (e.g. `from_saved_model`). """ super(TFLiteSavedModelConverterV2, self).__init__() self.saved_model_dir = saved_model_dir self._saved_model_tags = saved_model_tags self._saved_model_exported_names = saved_model_exported_names self._trackable_obj = trackable_obj self._parse_saved_model_args(always_enable_saved_model_import=True) @_export_metrics def convert(self): """Converts a TensorFlow GraphDef based on instance variables. Returns: The converted data in serialized format. Raises: ValueError: No concrete function is specified. Multiple concrete functions are specified. Input shape is not specified. Invalid quantization parameters. """ graph_def, input_tensors, output_tensors = self._load_saved_model( self.saved_model_dir, self._saved_model_tags ) # If we can't use saved model importer, then fallback # to frozen graph conversion path. if self.saved_model_dir is None or not self.experimental_new_converter: graph_def, _, _, _ = _freeze_saved_model( self.saved_model_dir, None, None, None, self._saved_model_tags, _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, ) # We make sure to clear the saved_model_dir as there is some # legacy code down in the caller that checks this. self.saved_model_dir = None return super(TFLiteSavedModelConverterV2, self).convert( graph_def, input_tensors, output_tensors ) trackable_obj = _load(self.saved_model_dir, self._saved_model_tags) if trackable_obj is None: self._debug_info = _get_debug_info( _build_debug_info_func(self._funcs[0].graph), graph_def ) else: self._debug_info = _get_debug_info( _convert_debug_info_func(trackable_obj.graph_debug_info), graph_def, ) del trackable_obj gc.collect() return self._convert_from_saved_model(graph_def)
TFLiteSavedModelConverterV2
python
mlflow__mlflow
mlflow/utils/environment.py
{ "start": 1822, "end": 36135 }
class ____: BUILD_PACKAGES = ("pip", "setuptools", "wheel") def __init__(self, python=None, build_dependencies=None, dependencies=None): """ Represents environment information for MLflow Models and Projects. Args: python: Python version for the environment. If unspecified, defaults to the current Python version. build_dependencies: List of build dependencies for the environment that must be installed before installing ``dependencies``. If unspecified, defaults to an empty list. dependencies: List of dependencies for the environment. If unspecified, defaults to an empty list. """ if python is not None and not isinstance(python, str): raise TypeError(f"`python` must be a string but got {type(python)}") if build_dependencies is not None and not isinstance(build_dependencies, list): raise TypeError( f"`build_dependencies` must be a list but got {type(build_dependencies)}" ) if dependencies is not None and not isinstance(dependencies, list): raise TypeError(f"`dependencies` must be a list but got {type(dependencies)}") self.python = python or PYTHON_VERSION self.build_dependencies = build_dependencies or [] self.dependencies = dependencies or [] def __str__(self): return str(self.to_dict()) @classmethod def current(cls): return cls( python=PYTHON_VERSION, build_dependencies=cls.get_current_build_dependencies(), dependencies=[f"-r {_REQUIREMENTS_FILE_NAME}"], ) @staticmethod def get_current_build_dependencies(): build_dependencies = [] for package in _PythonEnv.BUILD_PACKAGES: version = _get_package_version(package) dep = (package + "==" + version) if version else package build_dependencies.append(dep) return build_dependencies def to_dict(self): return self.__dict__.copy() @classmethod def from_dict(cls, dct): return cls(**dct) def to_yaml(self, path): with open(path, "w") as f: # Exclude None and empty lists data = {k: v for k, v in self.to_dict().items() if v} yaml.safe_dump(data, f, sort_keys=False, default_flow_style=False) @classmethod def from_yaml(cls, path): with open(path) as f: return cls.from_dict(yaml.safe_load(f)) @staticmethod def get_dependencies_from_conda_yaml(path): with open(path) as f: conda_env = yaml.safe_load(f) python = None build_dependencies = None unmatched_dependencies = [] dependencies = None for dep in conda_env.get("dependencies", []): if isinstance(dep, str): match = _CONDA_DEPENDENCY_REGEX.match(dep) if not match: unmatched_dependencies.append(dep) continue package = match.group("package") operator = match.group("operator") version = match.group("version") # Python if not python and package == "python": if operator is None: raise MlflowException.invalid_parameter_value( f"Invalid dependency for python: {dep}. " "It must be pinned (e.g. python=3.8.13)." ) if operator in ("<", ">", "!="): raise MlflowException( f"Invalid version comparator for python: '{operator}'. " "Must be one of ['<=', '>=', '=', '=='].", error_code=INVALID_PARAMETER_VALUE, ) python = version continue # Build packages if build_dependencies is None: build_dependencies = [] # "=" is an invalid operator for pip operator = "==" if operator == "=" else operator build_dependencies.append(package + (operator or "") + (version or "")) elif _is_pip_deps(dep): dependencies = dep["pip"] else: raise MlflowException( f"Invalid conda dependency: {dep}. Must be str or dict in the form of " '{"pip": [...]}', error_code=INVALID_PARAMETER_VALUE, ) if python is None: _logger.warning( f"{path} does not include a python version specification. " f"Using the current python version {PYTHON_VERSION}." ) python = PYTHON_VERSION if unmatched_dependencies: _logger.warning( "The following conda dependencies will not be installed in the resulting " "environment: %s", unmatched_dependencies, ) return { "python": python, "build_dependencies": build_dependencies, "dependencies": dependencies, } @classmethod def from_conda_yaml(cls, path): return cls.from_dict(cls.get_dependencies_from_conda_yaml(path)) def _mlflow_conda_env( path=None, additional_conda_deps=None, additional_pip_deps=None, additional_conda_channels=None, install_mlflow=True, ): """Creates a Conda environment with the specified package channels and dependencies. If there are any pip dependencies, including from the install_mlflow parameter, then pip will be added to the conda dependencies. This is done to ensure that the pip inside the conda environment is used to install the pip dependencies. Args: path: Local filesystem path where the conda env file is to be written. If unspecified, the conda env will not be written to the filesystem; it will still be returned in dictionary format. additional_conda_deps: List of additional conda dependencies passed as strings. additional_pip_deps: List of additional pip dependencies passed as strings. additional_conda_channels: List of additional conda channels to search when resolving packages. Returns: None if path is specified. Otherwise, the a dictionary representation of the Conda environment. """ additional_pip_deps = additional_pip_deps or [] mlflow_deps = ( [f"mlflow=={VERSION}"] if install_mlflow and not _contains_mlflow_requirement(additional_pip_deps) else [] ) pip_deps = mlflow_deps + additional_pip_deps conda_deps = additional_conda_deps or [] if pip_deps: pip_version = _get_package_version("pip") if pip_version is not None: # When a new version of pip is released on PyPI, it takes a while until that version is # uploaded to conda-forge. This time lag causes `conda create` to fail with # a `ResolvePackageNotFound` error. As a workaround for this issue, use `<=` instead # of `==` so conda installs `pip_version - 1` when `pip_version` is unavailable. conda_deps.append(f"pip<={pip_version}") else: _logger.warning( "Failed to resolve installed pip version. ``pip`` will be added to conda.yaml" " environment spec without a version specifier." ) conda_deps.append("pip") env = yaml.safe_load(_conda_header) env["dependencies"] = [f"python={PYTHON_VERSION}"] env["dependencies"] += conda_deps env["dependencies"].append({"pip": pip_deps}) if additional_conda_channels is not None: env["channels"] += additional_conda_channels if path is not None: with open(path, "w") as out: yaml.safe_dump(env, stream=out, default_flow_style=False) return None else: return env def _get_package_version(package_name: str) -> str | None: try: return importlib.metadata.version(package_name) except importlib.metadata.PackageNotFoundError: return None def _mlflow_additional_pip_env(pip_deps, path=None): requirements = "\n".join(pip_deps) if path is not None: with open(path, "w") as out: out.write(requirements) return None else: return requirements def _is_pip_deps(dep): """ Returns True if `dep` is a dict representing pip dependencies """ return isinstance(dep, dict) and "pip" in dep def _get_pip_deps(conda_env): """ Returns: The pip dependencies from the conda env. """ if conda_env is not None: for dep in conda_env["dependencies"]: if _is_pip_deps(dep): return dep["pip"] return [] def _overwrite_pip_deps(conda_env, new_pip_deps): """ Overwrites the pip dependencies section in the given conda env dictionary. { "name": "env", "channels": [...], "dependencies": [ ..., "pip", {"pip": [...]}, <- Overwrite this ], } """ deps = conda_env.get("dependencies", []) new_deps = [] contains_pip_deps = False for dep in deps: if _is_pip_deps(dep): contains_pip_deps = True new_deps.append({"pip": new_pip_deps}) else: new_deps.append(dep) if not contains_pip_deps: new_deps.append({"pip": new_pip_deps}) return {**conda_env, "dependencies": new_deps} def _log_pip_requirements(conda_env, path, requirements_file=_REQUIREMENTS_FILE_NAME): pip_deps = _get_pip_deps(conda_env) _mlflow_additional_pip_env(pip_deps, path=os.path.join(path, requirements_file)) def _parse_pip_requirements(pip_requirements): """Parses an iterable of pip requirement strings or a pip requirements file. Args: pip_requirements: Either an iterable of pip requirement strings (e.g. ``["scikit-learn", "-r requirements.txt"]``) or the string path to a pip requirements file on the local filesystem (e.g. ``"requirements.txt"``). If ``None``, an empty list will be returned. Returns: A tuple of parsed requirements and constraints. """ if pip_requirements is None: return [], [] def _is_string(x): return isinstance(x, str) def _is_iterable(x): try: iter(x) return True except Exception: return False if _is_string(pip_requirements): with open(pip_requirements) as f: return _parse_pip_requirements(f.read().splitlines()) elif _is_iterable(pip_requirements) and all(map(_is_string, pip_requirements)): requirements = [] constraints = [] for req_or_con in _parse_requirements(pip_requirements, is_constraint=False): if req_or_con.is_constraint: constraints.append(req_or_con.req_str) else: requirements.append(req_or_con.req_str) return requirements, constraints else: raise TypeError( "`pip_requirements` must be either a string path to a pip requirements file on the " "local filesystem or an iterable of pip requirement strings, but got `{}`".format( type(pip_requirements) ) ) _INFER_PIP_REQUIREMENTS_GENERAL_ERROR_MESSAGE = ( "Encountered an unexpected error while inferring pip requirements " "(model URI: {model_uri}, flavor: {flavor}). Fall back to return {fallback}. " "Set logging level to DEBUG to see the full traceback. " ) def infer_pip_requirements(model_uri, flavor, fallback=None, timeout=None, extra_env_vars=None): """Infers the pip requirements of the specified model by creating a subprocess and loading the model in it to determine which packages are imported. Args: model_uri: The URI of the model. flavor: The flavor name of the model. fallback: If provided, an unexpected error during the inference procedure is swallowed and the value of ``fallback`` is returned. Otherwise, the error is raised. timeout: If specified, the inference operation is bound by the timeout (in seconds). extra_env_vars: A dictionary of extra environment variables to pass to the subprocess. Default to None. Returns: A list of inferred pip requirements (e.g. ``["scikit-learn==0.24.2", ...]``). """ raise_on_error = MLFLOW_REQUIREMENTS_INFERENCE_RAISE_ERRORS.get() if timeout and is_windows(): timeout = None _logger.warning( "On Windows, timeout is not supported for model requirement inference. Therefore, " "the operation is not bound by a timeout and may hang indefinitely. If it hangs, " "please consider specifying the signature manually." ) try: if timeout: with run_with_timeout(timeout): return _infer_requirements( model_uri, flavor, raise_on_error=raise_on_error, extra_env_vars=extra_env_vars ) else: return _infer_requirements( model_uri, flavor, raise_on_error=raise_on_error, extra_env_vars=extra_env_vars ) except Exception as e: if raise_on_error or (fallback is None): raise if isinstance(e, MlflowTimeoutError): msg = ( "Attempted to infer pip requirements for the saved model or pipeline but the " f"operation timed out in {timeout} seconds. Fall back to return {fallback}. " "You can specify a different timeout by setting the environment variable " f"{MLFLOW_INPUT_EXAMPLE_INFERENCE_TIMEOUT}." ) else: msg = _INFER_PIP_REQUIREMENTS_GENERAL_ERROR_MESSAGE.format( model_uri=model_uri, flavor=flavor, fallback=fallback ) _logger.warning(msg) _logger.debug("", exc_info=True) return fallback def _get_uv_options_for_databricks() -> tuple[list[str], dict[str, str]] | None: """ Retrieves the predefined secrets to configure `pip` for Databricks, and converts them into command-line arguments and environment variables for `uv`. References: - https://docs.databricks.com/aws/en/compute/serverless/dependencies#predefined-secret-scope-name - https://docs.astral.sh/uv/configuration/environment/#environment-variables """ from databricks.sdk import WorkspaceClient from mlflow.utils.databricks_utils import ( _get_dbutils, _NoDbutilsError, is_in_databricks_runtime, ) if not is_in_databricks_runtime(): return None workspace_client = WorkspaceClient() secret_scopes = workspace_client.secrets.list_scopes() if not any(s.name == "databricks-package-management" for s in secret_scopes): return None try: dbutils = _get_dbutils() except _NoDbutilsError: return None def get_secret(key: str) -> str | None: """ Retrieves a secret from the Databricks secrets scope. """ try: return dbutils.secrets.get(scope="databricks-package-management", key=key) except Exception as e: _logger.debug(f"Failed to fetch secret '{key}': {e}") return None args: list[str] = [] if url := get_secret("pip-index-url"): args.append(f"--index-url={url}") if urls := get_secret("pip-extra-index-urls"): args.append(f"--extra-index-url={urls}") # There is no command-line option for SSL_CERT_FILE in `uv`. envs: dict[str, str] = {} if cert := get_secret("pip-cert"): envs["SSL_CERT_FILE"] = cert _logger.debug(f"uv arguments and environment variables: {args}, {envs}") return args, envs def _lock_requirements( requirements: list[str], constraints: list[str] | None = None ) -> list[str] | None: """ Locks the given requirements using `uv`. Returns the locked requirements when the locking is performed successfully, otherwise returns None. """ if not MLFLOW_LOCK_MODEL_DEPENDENCIES.get(): return None uv_bin = shutil.which("uv") if uv_bin is None: _logger.debug("`uv` binary not found. Skipping locking requirements.") return None _logger.info("Locking requirements...") with tempfile.TemporaryDirectory() as tmp_dir: tmp_dir_path = pathlib.Path(tmp_dir) in_file = tmp_dir_path / "requirements.in" in_file.write_text("\n".join(requirements)) out_file = tmp_dir_path / "requirements.out" constraints_opt: list[str] = [] if constraints: constraints_file = tmp_dir_path / "constraints.txt" constraints_file.write_text("\n".join(constraints)) constraints_opt = [f"--constraints={constraints_file}"] elif pip_constraint := os.environ.get("PIP_CONSTRAINT"): # If PIP_CONSTRAINT is set, use it as a constraint file constraints_opt = [f"--constraints={pip_constraint}"] try: if res := _get_uv_options_for_databricks(): uv_options, uv_envs = res else: uv_options = [] uv_envs = {} out = subprocess.check_output( [ uv_bin, "pip", "compile", "--color=never", "--universal", "--no-annotate", "--no-header", f"--python-version={PYTHON_VERSION}", f"--output-file={out_file}", *uv_options, *constraints_opt, in_file, ], stderr=subprocess.STDOUT, env=os.environ.copy() | uv_envs, text=True, ) _logger.debug(f"Successfully compiled requirements with `uv`:\n{out}") except subprocess.CalledProcessError as e: _logger.warning(f"Failed to lock requirements:\n{e.output}") return None return [ "# Original requirements", *(f"# {l}" for l in requirements), # Preserve original requirements as comments "#", "# Locked requirements", *out_file.read_text().splitlines(), ] def _validate_env_arguments(conda_env, pip_requirements, extra_pip_requirements): """ Validates that only one or none of `conda_env`, `pip_requirements`, and `extra_pip_requirements` is specified. """ args = [ conda_env, pip_requirements, extra_pip_requirements, ] specified = [arg for arg in args if arg is not None] if len(specified) > 1: raise ValueError( "Only one of `conda_env`, `pip_requirements`, and " "`extra_pip_requirements` can be specified" ) # PIP requirement parser inspired from https://github.com/pypa/pip/blob/b392833a0f1cff1bbee1ac6dbe0270cccdd0c11f/src/pip/_internal/req/req_file.py#L400 def _get_pip_requirement_specifier(requirement_string): tokens = requirement_string.split(" ") for idx, token in enumerate(tokens): if token.startswith("-"): return " ".join(tokens[:idx]) return requirement_string def _is_mlflow_requirement(requirement_string): """ Returns True if `requirement_string` represents a requirement for mlflow (e.g. 'mlflow==1.2.3'). """ # "/opt/mlflow" is the path where we mount the mlflow source code in the Docker container # when running tests. if _MLFLOW_TESTING.get() and requirement_string == "/opt/mlflow": return True try: # `Requirement` throws an `InvalidRequirement` exception if `requirement_string` doesn't # conform to PEP 508 (https://www.python.org/dev/peps/pep-0508). return Requirement(requirement_string).name.lower() in [ "mlflow", "mlflow-skinny", "mlflow-tracing", ] except InvalidRequirement: # A local file path or URL falls into this branch. # `Requirement` throws an `InvalidRequirement` exception if `requirement_string` contains # per-requirement options (ex: package hashes) # GitHub issue: https://github.com/pypa/packaging/issues/488 # Per-requirement-option spec: https://pip.pypa.io/en/stable/reference/requirements-file-format/#per-requirement-options requirement_specifier = _get_pip_requirement_specifier(requirement_string) try: # Try again with the per-requirement options removed return Requirement(requirement_specifier).name.lower() == "mlflow" except InvalidRequirement: # Support defining branch dependencies for local builds or direct GitHub builds # from source. # Example: mlflow @ git+https://github.com/mlflow/mlflow@branch_2.0 repository_matches = ["/mlflow", "mlflow@git"] return any( match in requirement_string.replace(" ", "").lower() for match in repository_matches ) def _generate_mlflow_version_pinning() -> str: """Returns a pinned requirement for the current MLflow version (e.g., "mlflow==3.2.1"). Returns: A pinned requirement for the current MLflow version. """ if _MLFLOW_TESTING.get(): # The local PyPI server should be running. It serves a wheel for the current MLflow version. return f"mlflow=={VERSION}" version = Version(VERSION) if not version.is_devrelease: # mlflow is installed from PyPI. return f"mlflow=={VERSION}" # We reach here when mlflow is installed from the source outside of the MLflow CI environment # (e.g., Databricks notebook). # mlflow installed from the source for development purposes. A dev version (e.g., 2.8.1.dev0) # is always a micro-version ahead of the latest release (unless it's manually modified) # and can't be installed from PyPI. We therefore subtract 1 from the micro version when running # tests. return f"mlflow=={version.major}.{version.minor}.{version.micro - 1}" def _contains_mlflow_requirement(requirements): """ Returns True if `requirements` contains a requirement for mlflow (e.g. 'mlflow==1.2.3'). """ return any(map(_is_mlflow_requirement, requirements)) def _process_pip_requirements( default_pip_requirements, pip_requirements=None, extra_pip_requirements=None ): """ Processes `pip_requirements` and `extra_pip_requirements` passed to `mlflow.*.save_model` or `mlflow.*.log_model`, and returns a tuple of (conda_env, pip_requirements, pip_constraints). """ constraints = [] if pip_requirements is not None: pip_reqs, constraints = _parse_pip_requirements(pip_requirements) elif extra_pip_requirements is not None: extra_pip_requirements, constraints = _parse_pip_requirements(extra_pip_requirements) pip_reqs = default_pip_requirements + extra_pip_requirements else: pip_reqs = default_pip_requirements if not _contains_mlflow_requirement(pip_reqs): pip_reqs.insert(0, _generate_mlflow_version_pinning()) sanitized_pip_reqs = _deduplicate_requirements(pip_reqs) sanitized_pip_reqs = _remove_incompatible_requirements(sanitized_pip_reqs) # Check if pip requirements contain incompatible version with the current environment warn_dependency_requirement_mismatches(sanitized_pip_reqs) if locked_requirements := _lock_requirements(sanitized_pip_reqs, constraints): # Locking requirements was performed successfully sanitized_pip_reqs = locked_requirements else: # Locking requirements was skipped or failed if constraints: sanitized_pip_reqs.append(f"-c {_CONSTRAINTS_FILE_NAME}") # Set `install_mlflow` to False because `pip_reqs` already contains `mlflow` conda_env = _mlflow_conda_env(additional_pip_deps=sanitized_pip_reqs, install_mlflow=False) return conda_env, sanitized_pip_reqs, constraints def _deduplicate_requirements(requirements): """ De-duplicates a list of pip package requirements, handling complex scenarios such as merging extras and combining version constraints. This function processes a list of pip package requirements and de-duplicates them. It handles standard PyPI packages and non-standard requirements (like URLs or local paths). The function merges extras and combines version constraints for duplicate packages. The most restrictive version specifications or the ones with extras are prioritized. If incompatible version constraints are detected, it raises an MlflowException. Args: requirements (list of str): A list of pip package requirement strings. Returns: list of str: A deduplicated list of pip package requirements. Raises: MlflowException: If incompatible version constraints are detected among the provided requirements. Examples: - Input: ["packageA", "packageA==1.0"] Output: ["packageA==1.0"] - Input: ["packageX>1.0", "packageX[extras]", "packageX<2.0"] Output: ["packageX[extras]>1.0,<2.0"] - Input: ["markdown[extra1]>=3.5.1", "markdown[extra2]<4", "markdown"] Output: ["markdown[extra1,extra2]>=3.5.1,<4"] - Input: ["scikit-learn==1.1", "scikit-learn<1"] Raises MlflowException indicating incompatible versions. Note: - Non-standard requirements (like URLs or file paths) are included as-is. - If a requirement appears multiple times with different sets of extras, they are merged. - The function uses `_validate_version_constraints` to check for incompatible version constraints by doing a dry-run pip install of a requirements collection. """ deduped_reqs = {} for req in requirements: try: parsed_req = Requirement(req) base_pkg = parsed_req.name existing_req = deduped_reqs.get(base_pkg) if not existing_req: deduped_reqs[base_pkg] = parsed_req else: # Verify that there are not unresolvable constraints applied if set and combine # if possible if ( existing_req.specifier and parsed_req.specifier and existing_req.specifier != parsed_req.specifier ): _validate_version_constraints([str(existing_req), req]) parsed_req.specifier = ",".join( [str(existing_req.specifier), str(parsed_req.specifier)] ) # Preserve existing specifiers if existing_req.specifier and not parsed_req.specifier: parsed_req.specifier = existing_req.specifier # Combine and apply extras if specified if ( existing_req.extras and parsed_req.extras and existing_req.extras != parsed_req.extras ): parsed_req.extras = sorted(set(existing_req.extras).union(parsed_req.extras)) elif existing_req.extras and not parsed_req.extras: parsed_req.extras = existing_req.extras deduped_reqs[base_pkg] = parsed_req except InvalidRequirement: # Include non-standard package strings as-is if req not in deduped_reqs: deduped_reqs[req] = req return [str(req) for req in deduped_reqs.values()] def _parse_requirement_name(req: str) -> str: try: return Requirement(req).name except InvalidRequirement: return req def _remove_incompatible_requirements(requirements: list[str]) -> list[str]: req_names = {_parse_requirement_name(req) for req in requirements} if "databricks-connect" in req_names and req_names.intersection({"pyspark", "pyspark-connect"}): _logger.debug( "Found incompatible requirements: 'databricks-connect' with 'pyspark' or " "'pyspark-connect'. Removing 'pyspark' or 'pyspark-connect' from the requirements." ) requirements = [ req for req in requirements if _parse_requirement_name(req) not in ["pyspark", "pyspark-connect"] ] return requirements def _validate_version_constraints(requirements): """ Validates the version constraints of given Python package requirements using pip's resolver with the `--dry-run` option enabled that performs validation only (will not install packages). This function writes the requirements to a temporary file and then attempts to resolve them using pip's `--dry-run` install option. If any version conflicts are detected, it raises an MlflowException with details of the conflict. Args: requirements (list of str): A list of package requirements (e.g., `["pandas>=1.15", "pandas<2"]`). Raises: MlflowException: If any version conflicts are detected among the provided requirements. Returns: None: This function does not return anything. It either completes successfully or raises an MlflowException. Example: _validate_version_constraints(["tensorflow<2.0", "tensorflow>2.3"]) # This will raise an exception due to boundary validity. """ with tempfile.NamedTemporaryFile(mode="w+", delete=False) as tmp_file: tmp_file.write("\n".join(requirements)) tmp_file_name = tmp_file.name try: subprocess.run( [sys.executable, "-m", "pip", "install", "--dry-run", "-r", tmp_file_name], check=True, capture_output=True, ) except subprocess.CalledProcessError as e: raise MlflowException.invalid_parameter_value( "The specified requirements versions are incompatible. Detected " f"conflicts: \n{e.stderr.decode()}" ) finally: os.remove(tmp_file_name) def _process_conda_env(conda_env): """ Processes `conda_env` passed to `mlflow.*.save_model` or `mlflow.*.log_model`, and returns a tuple of (conda_env, pip_requirements, pip_constraints). """ if isinstance(conda_env, str): with open(conda_env) as f: conda_env = yaml.safe_load(f) elif not isinstance(conda_env, dict): raise TypeError( "Expected a string path to a conda env yaml file or a `dict` representing a conda env, " f"but got `{type(conda_env).__name__}`" ) # User-specified `conda_env` may contain requirements/constraints file references pip_reqs = _get_pip_deps(conda_env) pip_reqs, constraints = _parse_pip_requirements(pip_reqs) if not _contains_mlflow_requirement(pip_reqs): pip_reqs.insert(0, _generate_mlflow_version_pinning()) # Check if pip requirements contain incompatible version with the current environment warn_dependency_requirement_mismatches(pip_reqs) if constraints: pip_reqs.append(f"-c {_CONSTRAINTS_FILE_NAME}") conda_env = _overwrite_pip_deps(conda_env, pip_reqs) return conda_env, pip_reqs, constraints def _get_mlflow_env_name(s): """Creates an environment name for an MLflow model by hashing the given string. Args: s: String to hash (e.g. the content of `conda.yaml`). Returns: String in the form of "mlflow-{hash}" (e.g. "mlflow-da39a3ee5e6b4b0d3255bfef95601890afd80709") """ return "mlflow-" + hashlib.sha1(s.encode("utf-8"), usedforsecurity=False).hexdigest() def _get_pip_install_mlflow(): """ Returns a command to pip-install mlflow. If the MLFLOW_HOME environment variable exists, returns "pip install -e {MLFLOW_HOME} 1>&2", otherwise "pip install mlflow=={mlflow.__version__} 1>&2". """ if mlflow_home := os.getenv("MLFLOW_HOME"): # dev version return f"pip install -e {mlflow_home} 1>&2" else: return f"pip install mlflow=={VERSION} 1>&2" def _get_requirements_from_file( file_path: pathlib.Path, ) -> list[Requirement]: data = file_path.read_text() if file_path.name == _CONDA_ENV_FILE_NAME: conda_env = yaml.safe_load(data) reqs = _get_pip_deps(conda_env) else: reqs = data.splitlines() return [Requirement(req) for req in reqs if req] def _write_requirements_to_file( file_path: pathlib.Path, new_reqs: list[str], ) -> None: if file_path.name == _CONDA_ENV_FILE_NAME: conda_env = yaml.safe_load(file_path.read_text()) conda_env = _overwrite_pip_deps(conda_env, new_reqs) with file_path.open("w") as file: yaml.dump(conda_env, file) else: file_path.write_text("\n".join(new_reqs)) def _add_or_overwrite_requirements( new_reqs: list[Requirement], old_reqs: list[Requirement], ) -> list[str]: deduped_new_reqs = _deduplicate_requirements([str(req) for req in new_reqs]) deduped_new_reqs = [Requirement(req) for req in deduped_new_reqs] old_reqs_dict = {req.name: str(req) for req in old_reqs} new_reqs_dict = {req.name: str(req) for req in deduped_new_reqs} old_reqs_dict.update(new_reqs_dict) return list(old_reqs_dict.values()) def _remove_requirements( reqs_to_remove: list[Requirement], old_reqs: list[Requirement], ) -> list[str]: old_reqs_dict = {req.name: str(req) for req in old_reqs} for req in reqs_to_remove: if req.name not in old_reqs_dict: _logger.warning(f'"{req.name}" not found in requirements, ignoring') old_reqs_dict.pop(req.name, None) return list(old_reqs_dict.values())
_PythonEnv
python
conda__conda
conda/models/package_info.py
{ "start": 975, "end": 1292 }
class ____(Entity): # from info/package_metadata.json package_metadata_version = IntegerField() noarch = ComposableField(Noarch, required=False, nullable=True) preferred_env = ComposableField( PreferredEnv, required=False, nullable=True, default=None, default_in_dump=False )
PackageMetadata
python
django-extensions__django-extensions
tests/test_management_command.py
{ "start": 13642, "end": 19323 }
class ____(TestCase): """ Tests for the `merge_model_instances` management command. """ @mock.patch( "django_extensions.management.commands.merge_model_instances.apps.get_models" ) @mock.patch("django_extensions.management.commands.merge_model_instances.input") def test_get_model_to_merge(self, test_input, get_models): class Model: __name__ = "" return_value = [] for v in ["one", "two", "three"]: instance = Model() instance.__name__ = v return_value.append(instance) get_models.return_value = return_value test_input.return_value = 2 model_to_deduplicate = get_model_to_deduplicate() self.assertEqual(model_to_deduplicate.__name__, "two") @mock.patch("django_extensions.management.commands.merge_model_instances.input") def test_get_field_names(self, test_input): class Field: name = "" def __init__(self, name): self.name = name class Model: __name__ = "" one = Field(name="one") two = Field(name="two") three = Field(name="three") return_value = [ Model().__getattribute__(field) for field in dir(Model()) if not field.startswith("__") ] Model._meta = mock.MagicMock() Model._meta.get_fields = mock.MagicMock(return_value=return_value) # Choose the second return_value test_input.side_effect = [2, "C"] field_names = get_field_names(Model()) # Test that the second return_value returned self.assertEqual(field_names, [return_value[1].name]) @mock.patch("django_extensions.management.commands.merge_model_instances.input") def test_keep_first_or_last_instance(self, test_input): test_input.side_effect = ["xxxx", "first", "last"] first_or_last = keep_first_or_last_instance() self.assertEqual(first_or_last, "first") first_or_last = keep_first_or_last_instance() self.assertEqual(first_or_last, "last") @mock.patch( "django_extensions.management.commands.merge_model_instances.get_model_to_deduplicate" ) @mock.patch( "django_extensions.management.commands.merge_model_instances.get_field_names" ) @mock.patch( "django_extensions.management.commands.merge_model_instances.keep_first_or_last_instance" ) def test_merge_model_instances( self, keep_first_or_last_instance, get_field_names, get_model_to_deduplicate ): get_model_to_deduplicate.return_value = Person get_field_names.return_value = ["name"] keep_first_or_last_instance.return_value = "first" name = Name.objects.create(name="Name") note = Note.objects.create(note="This is a note.") personality_1 = Personality.objects.create(description="Child 1's personality.") personality_2 = Personality.objects.create(description="Child 2's personality.") child_1 = Person.objects.create( name=Name.objects.create(name="Child1"), age=10, personality=personality_1, ) child_1.notes.add(note) child_2 = Person.objects.create( name=Name.objects.create(name="Child2"), age=10, personality=personality_2, ) child_2.notes.add(note) club1 = Club.objects.create(name="Club one") club2 = Club.objects.create(name="Club two") person_1 = Person.objects.create( name=name, age=50, personality=Personality.objects.create(description="First personality"), ) person_1.children.add(child_1) person_1.notes.add(note) Permission.objects.create(text="Permission", person=person_1) person_2 = Person.objects.create( name=name, age=50, personality=Personality.objects.create(description="Second personality"), ) person_2.children.add(child_2) new_note = Note.objects.create(note="This is a new note") person_2.notes.add(new_note) Membership.objects.create(club=club1, person=person_2) Membership.objects.create(club=club1, person=person_2) Permission.objects.create(text="Permission", person=person_2) person_3 = Person.objects.create( name=name, age=50, personality=Personality.objects.create(description="Third personality"), ) person_3.children.add(child_2) person_3.notes.add(new_note) Membership.objects.create(club=club2, person=person_3) Membership.objects.create(club=club2, person=person_3) Permission.objects.create(text="Permission", person=person_3) self.assertEqual(Person.objects.count(), 5) self.assertEqual(Membership.objects.count(), 4) out = StringIO() call_command("merge_model_instances", stdout=out) self.ouptput = out.getvalue() self.assertEqual(Person.objects.count(), 3) person = Person.objects.get(name__name="Name") self.assertRaises( Person.DoesNotExist, lambda: Person.objects.get(personality__description="Second personality"), ) self.assertEqual(person.notes.count(), 2) self.assertEqual(person.clubs.distinct().count(), 2) self.assertEqual(person.permission_set.count(), 3) self.assertRaises( Personality.DoesNotExist, lambda: Personality.objects.get(description="Second personality"), )
MergeModelInstancesTests
python
getsentry__sentry
src/sentry/api/helpers/group_index/validators/in_commit.py
{ "start": 224, "end": 323 }
class ____(TypedDict): commit: str repository: str @extend_schema_serializer()
InCommitResult
python
nedbat__coveragepy
tests/test_lcov.py
{ "start": 344, "end": 18903 }
class ____(CoverageTest): """Tests of the LCOV reports from coverage.py.""" def create_initial_files(self) -> None: """ Helper for tests that handles the common ceremony so the tests can show the consequences of changes in the setup. """ self.make_file( "main_file.py", """\ def cuboid_volume(l): return (l*l*l) def IsItTrue(): return True """, ) self.make_file( "test_file.py", """\ from main_file import cuboid_volume import unittest class TestCuboid(unittest.TestCase): def test_volume(self): self.assertAlmostEqual(cuboid_volume(2),8) self.assertAlmostEqual(cuboid_volume(1),1) self.assertAlmostEqual(cuboid_volume(0),0) self.assertAlmostEqual(cuboid_volume(5.5),166.375) """, ) def get_lcov_report_content(self, filename: str = "coverage.lcov") -> str: """Return the content of an LCOV report.""" with open(filename, encoding="utf-8") as file: return file.read() def test_lone_file(self) -> None: # For a single file with a couple of functions, the lcov should cover # the function definitions themselves, but not the returns. self.make_file( "main_file.py", """\ def cuboid_volume(l): return (l*l*l) def IsItTrue(): return True """, ) expected_result = textwrap.dedent("""\ SF:main_file.py DA:1,1 DA:2,0 DA:4,1 DA:5,0 LF:4 LH:2 FN:1,2,cuboid_volume FNDA:0,cuboid_volume FN:4,5,IsItTrue FNDA:0,IsItTrue FNF:2 FNH:0 end_of_record """) self.assert_doesnt_exist(".coverage") cov = coverage.Coverage(source=["."]) self.start_import_stop(cov, "main_file") pct = cov.lcov_report() assert pct == 50.0 actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_line_checksums(self) -> None: self.make_file( "main_file.py", """\ def cuboid_volume(l): return (l*l*l) def IsItTrue(): return True """, ) self.make_file(".coveragerc", "[lcov]\nline_checksums = true\n") self.assert_doesnt_exist(".coverage") cov = coverage.Coverage(source=["."]) self.start_import_stop(cov, "main_file") pct = cov.lcov_report() assert pct == 50.0 expected_result = textwrap.dedent("""\ SF:main_file.py DA:1,1,7URou3io0zReBkk69lEb/Q DA:2,0,Xqj6H1iz/nsARMCAbE90ng DA:4,1,ilhb4KUfytxtEuClijZPlQ DA:5,0,LWILTcvARcydjFFyo9qM0A LF:4 LH:2 FN:1,2,cuboid_volume FNDA:0,cuboid_volume FN:4,5,IsItTrue FNDA:0,IsItTrue FNF:2 FNH:0 end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_simple_line_coverage_two_files(self) -> None: # Test that line coverage is created when coverage is run, # and matches the output of the file below. self.create_initial_files() self.assert_doesnt_exist(".coverage") self.make_file(".coveragerc", "[lcov]\noutput = data.lcov\n") cov = coverage.Coverage(source=".") self.start_import_stop(cov, "test_file") pct = cov.lcov_report() assert pct == 50.0 self.assert_exists("data.lcov") expected_result = textwrap.dedent("""\ SF:main_file.py DA:1,1 DA:2,0 DA:4,1 DA:5,0 LF:4 LH:2 FN:1,2,cuboid_volume FNDA:0,cuboid_volume FN:4,5,IsItTrue FNDA:0,IsItTrue FNF:2 FNH:0 end_of_record SF:test_file.py DA:1,1 DA:2,1 DA:4,1 DA:5,1 DA:6,0 DA:7,0 DA:8,0 DA:9,0 LF:8 LH:4 FN:5,9,TestCuboid.test_volume FNDA:0,TestCuboid.test_volume FNF:1 FNH:0 end_of_record """) actual_result = self.get_lcov_report_content(filename="data.lcov") assert expected_result == actual_result def test_branch_coverage_one_file(self) -> None: # Test that the reporter produces valid branch coverage. self.make_file( "main_file.py", """\ def is_it_x(x): if x == 3: return x else: return False """, ) self.assert_doesnt_exist(".coverage") cov = coverage.Coverage(branch=True, source=".") self.start_import_stop(cov, "main_file") pct = cov.lcov_report() assert math.isclose(pct, 16.666666666666668) self.assert_exists("coverage.lcov") expected_result = textwrap.dedent("""\ SF:main_file.py DA:1,1 DA:2,0 DA:3,0 DA:5,0 LF:4 LH:1 FN:1,5,is_it_x FNDA:0,is_it_x FNF:1 FNH:0 BRDA:2,0,jump to line 3,- BRDA:2,0,jump to line 5,- BRF:2 BRH:0 end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_branch_coverage_two_files(self) -> None: # Test that valid branch coverage is generated # in the case of two files. self.make_file( "main_file.py", """\ def is_it_x(x): if x == 3: return x else: return False """, ) self.make_file( "test_file.py", """\ from main_file import * import unittest class TestIsItX(unittest.TestCase): def test_is_it_x(self): self.assertEqual(is_it_x(3), 3) self.assertEqual(is_it_x(4), False) """, ) self.assert_doesnt_exist(".coverage") cov = coverage.Coverage(branch=True, source=".") self.start_import_stop(cov, "test_file") pct = cov.lcov_report() assert math.isclose(pct, 41.666666666666664) self.assert_exists("coverage.lcov") expected_result = textwrap.dedent("""\ SF:main_file.py DA:1,1 DA:2,0 DA:3,0 DA:5,0 LF:4 LH:1 FN:1,5,is_it_x FNDA:0,is_it_x FNF:1 FNH:0 BRDA:2,0,jump to line 3,- BRDA:2,0,jump to line 5,- BRF:2 BRH:0 end_of_record SF:test_file.py DA:1,1 DA:2,1 DA:4,1 DA:5,1 DA:6,0 DA:7,0 LF:6 LH:4 FN:5,7,TestIsItX.test_is_it_x FNDA:0,TestIsItX.test_is_it_x FNF:1 FNH:0 end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_half_covered_branch(self) -> None: # Test that for a given branch that is only half covered, # the block numbers remain the same, and produces valid lcov. self.make_file( "main_file.py", """\ something = True if something: print("Yes, something") else: print("No, nothing") """, ) self.assert_doesnt_exist(".coverage") cov = coverage.Coverage(branch=True, source=".") self.start_import_stop(cov, "main_file") pct = cov.lcov_report() assert math.isclose(pct, 66.66666666666667) self.assert_exists("coverage.lcov") expected_result = textwrap.dedent("""\ SF:main_file.py DA:1,1 DA:3,1 DA:4,1 DA:6,0 LF:4 LH:3 BRDA:3,0,jump to line 4,1 BRDA:3,0,jump to line 6,0 BRF:2 BRH:1 end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_empty_init_files(self) -> None: # Test that an empty __init__.py still generates a (vacuous) # coverage record. self.make_file("__init__.py", "") self.assert_doesnt_exist(".coverage") cov = coverage.Coverage(branch=True, source=".") self.start_import_stop(cov, "__init__") pct = cov.lcov_report() assert pct == 0.0 self.assert_exists("coverage.lcov") expected_result = textwrap.dedent("""\ SF:__init__.py end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_empty_init_file_skipped(self) -> None: # Test that the lcov reporter honors skip_empty. Because skip_empty # keys off the overall number of lines of code, the result in this # case will be the same regardless of the age of the Python interpreter. self.make_file("__init__.py", "") self.make_file(".coveragerc", "[report]\nskip_empty = True\n") self.assert_doesnt_exist(".coverage") cov = coverage.Coverage(branch=True, source=".") self.start_import_stop(cov, "__init__") pct = cov.lcov_report() assert pct == 0.0 self.assert_exists("coverage.lcov") expected_result = "" actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_excluded_lines(self) -> None: self.make_file( ".coveragerc", """\ [report] exclude_lines = foo """, ) self.make_file( "runme.py", """\ s = "Hello 1" t = "foo is ignored 2" if s.upper() == "BYE 3": i_am_missing_4() foo_is_missing_5() print("Done 6") # foo 7 # line 8 """, ) cov = coverage.Coverage(source=".", branch=True) self.start_import_stop(cov, "runme") cov.lcov_report() expected_result = textwrap.dedent("""\ SF:runme.py DA:1,1 DA:3,1 DA:4,0 DA:6,1 LF:4 LH:3 BRDA:3,0,jump to line 4,0 BRDA:3,0,jump to line 6,1 BRF:2 BRH:1 end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_exit_branches(self) -> None: self.make_file( "runme.py", """\ def foo(a): if a: print(f"{a!r} is truthy") foo(True) foo(False) foo([]) foo([0]) """, ) cov = coverage.Coverage(source=".", branch=True) self.start_import_stop(cov, "runme") cov.lcov_report() expected_result = textwrap.dedent("""\ SF:runme.py DA:1,1 DA:2,1 DA:3,1 DA:4,1 DA:5,1 DA:6,1 DA:7,1 LF:7 LH:7 FN:1,3,foo FNDA:1,foo FNF:1 FNH:1 BRDA:2,0,jump to line 3,1 BRDA:2,0,return from function 'foo',1 BRF:2 BRH:2 end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_genexpr_exit_arcs_pruned_full_coverage(self) -> None: self.make_file( "runme.py", """\ def foo(a): if any(x > 0 for x in a): print(f"{a!r} has positives") foo([]) foo([0]) foo([0,1]) foo([0,-1]) """, ) cov = coverage.Coverage(source=".", branch=True) self.start_import_stop(cov, "runme") cov.lcov_report() expected_result = textwrap.dedent("""\ SF:runme.py DA:1,1 DA:2,1 DA:3,1 DA:4,1 DA:5,1 DA:6,1 DA:7,1 LF:7 LH:7 FN:1,3,foo FNDA:1,foo FNF:1 FNH:1 BRDA:2,0,jump to line 3,1 BRDA:2,0,return from function 'foo',1 BRF:2 BRH:2 end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_genexpr_exit_arcs_pruned_never_true(self) -> None: self.make_file( "runme.py", """\ def foo(a): if any(x > 0 for x in a): print(f"{a!r} has positives") foo([]) foo([0]) """, ) cov = coverage.Coverage(source=".", branch=True) self.start_import_stop(cov, "runme") cov.lcov_report() expected_result = textwrap.dedent("""\ SF:runme.py DA:1,1 DA:2,1 DA:3,0 DA:4,1 DA:5,1 LF:5 LH:4 FN:1,3,foo FNDA:1,foo FNF:1 FNH:1 BRDA:2,0,jump to line 3,0 BRDA:2,0,return from function 'foo',1 BRF:2 BRH:1 end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_genexpr_exit_arcs_pruned_always_true(self) -> None: self.make_file( "runme.py", """\ def foo(a): if any(x > 0 for x in a): print(f"{a!r} has positives") foo([1]) foo([1,2]) """, ) cov = coverage.Coverage(source=".", branch=True) self.start_import_stop(cov, "runme") cov.lcov_report() expected_result = textwrap.dedent("""\ SF:runme.py DA:1,1 DA:2,1 DA:3,1 DA:4,1 DA:5,1 LF:5 LH:5 FN:1,3,foo FNDA:1,foo FNF:1 FNH:1 BRDA:2,0,jump to line 3,1 BRDA:2,0,return from function 'foo',0 BRF:2 BRH:1 end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_genexpr_exit_arcs_pruned_not_reached(self) -> None: self.make_file( "runme.py", """\ def foo(a): if any(x > 0 for x in a): print(f"{a!r} has positives") """, ) cov = coverage.Coverage(source=".", branch=True) self.start_import_stop(cov, "runme") cov.lcov_report() expected_result = textwrap.dedent("""\ SF:runme.py DA:1,1 DA:2,0 DA:3,0 LF:3 LH:1 FN:1,3,foo FNDA:0,foo FNF:1 FNH:0 BRDA:2,0,jump to line 3,- BRDA:2,0,return from function 'foo',- BRF:2 BRH:0 end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_always_raise(self) -> None: self.make_file( "always_raise.py", """\ try: if not_defined: print("Yes") else: print("No") except Exception: pass """, ) cov = coverage.Coverage(source=".", branch=True) self.start_import_stop(cov, "always_raise") cov.lcov_report() expected_result = textwrap.dedent("""\ SF:always_raise.py DA:1,1 DA:2,1 DA:3,0 DA:5,0 DA:6,1 DA:7,1 LF:6 LH:4 BRDA:2,0,jump to line 3,- BRDA:2,0,jump to line 5,- BRF:2 BRH:0 end_of_record """) actual_result = self.get_lcov_report_content() assert expected_result == actual_result def test_multiline_conditions(self) -> None: self.make_file( "multi.py", """\ def fun(x): if ( x ): print("got here") """, ) cov = coverage.Coverage(source=".", branch=True) self.start_import_stop(cov, "multi") cov.lcov_report() lcov = self.get_lcov_report_content() assert "BRDA:2,0,return from function 'fun',-" in lcov def test_module_exit(self) -> None: self.make_file( "modexit.py", """\ #! /usr/bin/env python def foo(): return bar( ) if "x" == "y": # line 5 foo() """, ) cov = coverage.Coverage(source=".", branch=True) self.start_import_stop(cov, "modexit") cov.lcov_report() lcov = self.get_lcov_report_content() print(lcov) assert "BRDA:5,0,exit the module,1" in lcov
LcovTest
python
spyder-ide__spyder
spyder/plugins/pylint/main_widget.py
{ "start": 2366, "end": 2565 }
class ____: FileComboBox = 'file_combo' RateLabel = 'rate_label' DateLabel = 'date_label' Stretcher1 = 'stretcher_1' Stretcher2 = 'stretcher_2' # ---- Items
PylintWidgetToolbarItems
python
python__mypy
mypy/types.py
{ "start": 18067, "end": 20486 }
class ____: # A type variable is uniquely identified by its raw id and meta level. # For plain variables (type parameters of generic classes and # functions) raw ids are allocated by semantic analysis, using # positive ids 1, 2, ... for generic class parameters and negative # ids -1, ... for generic function type arguments. A special value 0 # is reserved for Self type variable (autogenerated). This convention # is only used to keep type variable ids distinct when allocating # them; the type checker makes no distinction between class and # function type variables. # Metavariables are allocated unique ids starting from 1. raw_id: Final[int] # Level of the variable in type inference. Currently either 0 for # declared types, or 1 for type inference metavariables. meta_level: int = 0 # Class variable used for allocating fresh ids for metavariables. next_raw_id: ClassVar[int] = 1 # Fullname of class or function/method which declares this type # variable (not the fullname of the TypeVar definition!), or '' namespace: str def __init__(self, raw_id: int, meta_level: int = 0, *, namespace: str = "") -> None: self.raw_id = raw_id self.meta_level = meta_level self.namespace = namespace @staticmethod def new(meta_level: int) -> TypeVarId: raw_id = TypeVarId.next_raw_id TypeVarId.next_raw_id += 1 return TypeVarId(raw_id, meta_level) def __repr__(self) -> str: return self.raw_id.__repr__() def __eq__(self, other: object) -> bool: # Although this call is not expensive (like UnionType or TypedDictType), # most of the time we get the same object here, so add a fast path. if self is other: return True return ( isinstance(other, TypeVarId) and self.raw_id == other.raw_id and self.meta_level == other.meta_level and self.namespace == other.namespace ) def __ne__(self, other: object) -> bool: return not (self == other) def __hash__(self) -> int: return self.raw_id ^ (self.meta_level << 8) ^ hash(self.namespace) def is_meta_var(self) -> bool: return self.meta_level > 0 def is_self(self) -> bool: # This is a special value indicating typing.Self variable. return self.raw_id == 0
TypeVarId
python
plotly__plotly.py
plotly/graph_objs/scattersmith/unselected/_marker.py
{ "start": 233, "end": 4076 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattersmith.unselected" _path_str = "scattersmith.unselected.marker" _valid_props = {"color", "opacity", "size"} @property def color(self): """ Sets the marker color of unselected points, applied only when a selection exists. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def opacity(self): """ Sets the marker opacity of unselected points, applied only when a selection exists. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["opacity"] @opacity.setter def opacity(self, val): self["opacity"] = val @property def size(self): """ Sets the marker size of unselected points, applied only when a selection exists. The 'size' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def _prop_descriptions(self): return """\ color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists. size Sets the marker size of unselected points, applied only when a selection exists. """ def __init__(self, arg=None, color=None, opacity=None, size=None, **kwargs): """ Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scattersmith.u nselected.Marker` color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists. size Sets the marker size of unselected points, applied only when a selection exists. Returns ------- Marker """ super().__init__("marker") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.scattersmith.unselected.Marker constructor must be a dict or an instance of :class:`plotly.graph_objs.scattersmith.unselected.Marker`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("opacity", arg, opacity) self._set_property("size", arg, size) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Marker
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 7494, "end": 8317 }
class ____(CompileError): """Raised when an operation is not supported by the given compiler. .. seealso:: :ref:`faq_sql_expression_string` :ref:`error_l7de` """ code = "l7de" def __init__( self, compiler: Union[Compiled, TypeCompiler], element_type: Type[ClauseElement], message: Optional[str] = None, ): super().__init__( "Compiler %r can't render element of type %s%s" % (compiler, element_type, ": %s" % message if message else "") ) self.compiler = compiler self.element_type = element_type self.message = message def __reduce__(self) -> Union[str, Tuple[Any, ...]]: return self.__class__, (self.compiler, self.element_type, self.message)
UnsupportedCompilationError
python
openai__openai-python
src/openai/resources/vector_stores/files.py
{ "start": 18951, "end": 36917 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncFilesWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers """ return AsyncFilesWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncFilesWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/openai/openai-python#with_streaming_response """ return AsyncFilesWithStreamingResponse(self) async def create( self, vector_store_id: str, *, file_id: str, attributes: Optional[Dict[str, Union[str, float, bool]]] | Omit = omit, chunking_strategy: FileChunkingStrategyParam | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> VectorStoreFile: """ Create a vector store file by attaching a [File](https://platform.openai.com/docs/api-reference/files) to a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). Args: file_id: A [File](https://platform.openai.com/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files. attributes: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters, booleans, or numbers. chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not vector_store_id: raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/vector_stores/{vector_store_id}/files", body=await async_maybe_transform( { "file_id": file_id, "attributes": attributes, "chunking_strategy": chunking_strategy, }, file_create_params.FileCreateParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=VectorStoreFile, ) async def retrieve( self, file_id: str, *, vector_store_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> VectorStoreFile: """ Retrieves a vector store file. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not vector_store_id: raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._get( f"/vector_stores/{vector_store_id}/files/{file_id}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=VectorStoreFile, ) async def update( self, file_id: str, *, vector_store_id: str, attributes: Optional[Dict[str, Union[str, float, bool]]], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> VectorStoreFile: """ Update attributes on a vector store file. Args: attributes: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters, booleans, or numbers. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not vector_store_id: raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/vector_stores/{vector_store_id}/files/{file_id}", body=await async_maybe_transform({"attributes": attributes}, file_update_params.FileUpdateParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=VectorStoreFile, ) def list( self, vector_store_id: str, *, after: str | Omit = omit, before: str | Omit = omit, filter: Literal["in_progress", "completed", "failed", "cancelled"] | Omit = omit, limit: int | Omit = omit, order: Literal["asc", "desc"] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AsyncPaginator[VectorStoreFile, AsyncCursorPage[VectorStoreFile]]: """ Returns a list of vector store files. Args: after: A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. filter: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not vector_store_id: raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( f"/vector_stores/{vector_store_id}/files", page=AsyncCursorPage[VectorStoreFile], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, query=maybe_transform( { "after": after, "before": before, "filter": filter, "limit": limit, "order": order, }, file_list_params.FileListParams, ), ), model=VectorStoreFile, ) async def delete( self, file_id: str, *, vector_store_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> VectorStoreFileDeleted: """Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. To delete the file, use the [delete file](https://platform.openai.com/docs/api-reference/files/delete) endpoint. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not vector_store_id: raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._delete( f"/vector_stores/{vector_store_id}/files/{file_id}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=VectorStoreFileDeleted, ) async def create_and_poll( self, file_id: str, *, vector_store_id: str, attributes: Optional[Dict[str, Union[str, float, bool]]] | Omit = omit, poll_interval_ms: int | Omit = omit, chunking_strategy: FileChunkingStrategyParam | Omit = omit, ) -> VectorStoreFile: """Attach a file to the given vector store and wait for it to be processed.""" await self.create( vector_store_id=vector_store_id, file_id=file_id, chunking_strategy=chunking_strategy, attributes=attributes ) return await self.poll( file_id, vector_store_id=vector_store_id, poll_interval_ms=poll_interval_ms, ) async def poll( self, file_id: str, *, vector_store_id: str, poll_interval_ms: int | Omit = omit, ) -> VectorStoreFile: """Wait for the vector store file to finish processing. Note: this will return even if the file failed to process, you need to check file.last_error and file.status to handle these cases """ headers: dict[str, str] = {"X-Stainless-Poll-Helper": "true"} if is_given(poll_interval_ms): headers["X-Stainless-Custom-Poll-Interval"] = str(poll_interval_ms) while True: response = await self.with_raw_response.retrieve( file_id, vector_store_id=vector_store_id, extra_headers=headers, ) file = response.parse() if file.status == "in_progress": if not is_given(poll_interval_ms): from_header = response.headers.get("openai-poll-after-ms") if from_header is not None: poll_interval_ms = int(from_header) else: poll_interval_ms = 1000 await self._sleep(poll_interval_ms / 1000) elif file.status == "cancelled" or file.status == "completed" or file.status == "failed": return file else: if TYPE_CHECKING: # type: ignore[unreachable] assert_never(file.status) else: return file async def upload( self, *, vector_store_id: str, file: FileTypes, chunking_strategy: FileChunkingStrategyParam | Omit = omit, ) -> VectorStoreFile: """Upload a file to the `files` API and then attach it to the given vector store. Note the file will be asynchronously processed (you can use the alternative polling helper method to wait for processing to complete). """ file_obj = await self._client.files.create(file=file, purpose="assistants") return await self.create( vector_store_id=vector_store_id, file_id=file_obj.id, chunking_strategy=chunking_strategy ) async def upload_and_poll( self, *, vector_store_id: str, file: FileTypes, attributes: Optional[Dict[str, Union[str, float, bool]]] | Omit = omit, poll_interval_ms: int | Omit = omit, chunking_strategy: FileChunkingStrategyParam | Omit = omit, ) -> VectorStoreFile: """Add a file to a vector store and poll until processing is complete.""" file_obj = await self._client.files.create(file=file, purpose="assistants") return await self.create_and_poll( vector_store_id=vector_store_id, file_id=file_obj.id, poll_interval_ms=poll_interval_ms, chunking_strategy=chunking_strategy, attributes=attributes, ) def content( self, file_id: str, *, vector_store_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AsyncPaginator[FileContentResponse, AsyncPage[FileContentResponse]]: """ Retrieve the parsed contents of a vector store file. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not vector_store_id: raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( f"/vector_stores/{vector_store_id}/files/{file_id}/content", page=AsyncPage[FileContentResponse], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), model=FileContentResponse, )
AsyncFiles
python
scipy__scipy
scipy/stats/_multivariate.py
{ "start": 258612, "end": 268815 }
class ____(multi_rv_generic): r"""Normal-inverse-gamma distribution. The normal-inverse-gamma distribution is the conjugate prior of a normal distribution with unknown mean and variance. Methods ------- pdf(x, s2, mu=0, lmbda=1, a=1, b=1) Probability density function. logpdf(x, s2, mu=0, lmbda=1, a=1, b=1) Log of the probability density function. mean(mu=0, lmbda=1, a=1, b=1) Distribution mean. var(mu=0, lmbda=1, a=1, b=1) Distribution variance. rvs(mu=0, lmbda=1, a=1, b=1, size=None, random_state=None) Draw random samples. Parameters ---------- mu, lmbda, a, b : array_like Shape parameters of the distribution. See notes. seed : {None, int, np.random.RandomState, np.random.Generator}, optional Used for drawing random variates. If `seed` is `None`, the `~np.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with seed. If `seed` is already a ``RandomState`` or ``Generator`` instance, then that object is used. Default is `None`. See Also -------- norm invgamma Notes ----- The probability density function of `normal_inverse_gamma` is: .. math:: f(x, \sigma^2; \mu, \lambda, \alpha, \beta) = \frac{\sqrt{\lambda}}{\sqrt{2 \pi \sigma^2}} \frac{\beta^\alpha}{\Gamma(\alpha)} \left( \frac{1}{\sigma^2} \right)^{\alpha + 1} \exp \left(- \frac{2 \beta + \lambda (x - \mu)^2} {2 \sigma^2} \right) where all parameters are real and finite, and :math:`\sigma^2 > 0`, :math:`\lambda > 0`, :math:`\alpha > 0`, and :math:`\beta > 0`. Methods ``normal_inverse_gamma.pdf`` and ``normal_inverse_gamma.logpdf`` accept `x` and `s2` for arguments :math:`x` and :math:`\sigma^2`. All methods accept `mu`, `lmbda`, `a`, and `b` for shape parameters :math:`\mu`, :math:`\lambda`, :math:`\alpha`, and :math:`\beta`, respectively. .. versionadded:: 1.15 References ---------- .. [1] Normal-inverse-gamma distribution, Wikipedia, https://en.wikipedia.org/wiki/Normal-inverse-gamma_distribution Examples -------- Suppose we wish to investigate the relationship between the normal-inverse-gamma distribution and the inverse gamma distribution. >>> import numpy as np >>> from scipy import stats >>> import matplotlib.pyplot as plt >>> rng = np.random.default_rng(527484872345) >>> mu, lmbda, a, b = 0, 1, 20, 20 >>> norm_inv_gamma = stats.normal_inverse_gamma(mu, lmbda, a, b) >>> inv_gamma = stats.invgamma(a, scale=b) One approach is to compare the distribution of the `s2` elements of random variates against the PDF of an inverse gamma distribution. >>> _, s2 = norm_inv_gamma.rvs(size=10000, random_state=rng) >>> bins = np.linspace(s2.min(), s2.max(), 50) >>> plt.hist(s2, bins=bins, density=True, label='Frequency density') >>> s2 = np.linspace(s2.min(), s2.max(), 300) >>> plt.plot(s2, inv_gamma.pdf(s2), label='PDF') >>> plt.xlabel(r'$\sigma^2$') >>> plt.ylabel('Frequency density / PMF') >>> plt.show() Similarly, we can compare the marginal distribution of `s2` against an inverse gamma distribution. >>> from scipy.integrate import quad_vec >>> from scipy import integrate >>> s2 = np.linspace(0.5, 3, 6) >>> res = quad_vec(lambda x: norm_inv_gamma.pdf(x, s2), -np.inf, np.inf)[0] >>> np.allclose(res, inv_gamma.pdf(s2)) True The sample mean is comparable to the mean of the distribution. >>> x, s2 = norm_inv_gamma.rvs(size=10000, random_state=rng) >>> x.mean(), s2.mean() (np.float64(-0.005254750127304425), np.float64(1.050438111436508)) >>> norm_inv_gamma.mean() (np.float64(0.0), np.float64(1.0526315789473684)) Similarly, for the variance: >>> x.var(ddof=1), s2.var(ddof=1) (np.float64(1.0546150578185023), np.float64(0.061829865266330754)) >>> norm_inv_gamma.var() (np.float64(1.0526315789473684), np.float64(0.061557402277623886)) """ def rvs(self, mu=0, lmbda=1, a=1, b=1, size=None, random_state=None): """Draw random samples from the distribution. Parameters ---------- mu, lmbda, a, b : array_like, optional Shape parameters. `lmbda`, `a`, and `b` must be greater than zero. size : int or tuple of ints, optional Shape of samples to draw. random_state : {None, int, np.random.RandomState, np.random.Generator}, optional Used for drawing random variates. If `random_state` is `None`, the `~np.random.RandomState` singleton is used. If `random_state` is an int, a new ``RandomState`` instance is used, seeded with `random_state`. If `random_state` is already a ``RandomState`` or ``Generator`` instance, then that object is used. Default is `None`. Returns ------- x, s2 : ndarray Random variates. """ random_state = self._get_random_state(random_state) s2 = invgamma(a, scale=b).rvs(size=size, random_state=random_state) scale = (s2 / lmbda)**0.5 x = norm(loc=mu, scale=scale).rvs(size=size, random_state=random_state) dtype = np.result_type(1.0, mu, lmbda, a, b) return x.astype(dtype), s2.astype(dtype) def _logpdf(self, x, s2, mu, lmbda, a, b): t1 = 0.5 * (np.log(lmbda) - np.log(2 * np.pi * s2)) t2 = a*np.log(b) - special.gammaln(a).astype(a.dtype) t3 = -(a + 1) * np.log(s2) t4 = -(2*b + lmbda*(x - mu)**2) / (2*s2) return t1 + t2 + t3 + t4 def logpdf(self, x, s2, mu=0, lmbda=1, a=1, b=1): """Log of the probability density function. Parameters ---------- x, s2 : array_like Arguments. `s2` must be greater than zero. mu, lmbda, a, b : array_like, optional Shape parameters. `lmbda`, `a`, and `b` must be greater than zero. Returns ------- logpdf : ndarray or scalar Log of the probability density function. """ invalid, args = self._process_parameters_pdf(x, s2, mu, lmbda, a, b) s2 = args[1] # Keep it simple for now; lazyselect later, perhaps. with np.errstate(all='ignore'): logpdf = np.asarray(self._logpdf(*args)) logpdf[s2 <= 0] = -np.inf logpdf[invalid] = np.nan return logpdf[()] def _pdf(self, x, s2, mu, lmbda, a, b): t1 = np.sqrt(lmbda / (2 * np.pi * s2)) t2 = b**a / special.gamma(a).astype(a.dtype) t3 = (1 / s2)**(a + 1) t4 = np.exp(-(2*b + lmbda*(x - mu)**2) / (2*s2)) return t1 * t2 * t3 * t4 def pdf(self, x, s2, mu=0, lmbda=1, a=1, b=1): """The probability density function. Parameters ---------- x, s2 : array_like Arguments. `s2` must be greater than zero. mu, lmbda, a, b : array_like, optional Shape parameters. `lmbda`, `a`, and `b` must be greater than zero. Returns ------- logpdf : ndarray or scalar The probability density function. """ invalid, args = self._process_parameters_pdf(x, s2, mu, lmbda, a, b) s2 = args[1] # Keep it simple for now; lazyselect later, perhaps. with np.errstate(all='ignore'): pdf = np.asarray(self._pdf(*args)) pdf[s2 <= 0] = 0 pdf[invalid] = np.nan return pdf[()] def mean(self, mu=0, lmbda=1, a=1, b=1): """The mean of the distribution. Parameters ---------- mu, lmbda, a, b : array_like, optional Shape parameters. `lmbda` and `b` must be greater than zero, and `a` must be greater than one. Returns ------- x, s2 : ndarray The mean of the distribution. """ invalid, args = self._process_shapes(mu, lmbda, a, b) mu, lmbda, a, b = args invalid |= ~(a > 1) mean_x = np.asarray(mu).copy() mean_s2 = np.asarray(b / (a - 1)) mean_x[invalid] = np.nan mean_s2[invalid] = np.nan return mean_x[()], mean_s2[()] def var(self, mu=0, lmbda=1, a=1, b=1): """The variance of the distribution. Parameters ---------- mu, lmbda, a, b : array_like, optional Shape parameters. `lmbda` and `b` must be greater than zero, and `a` must be greater than two. Returns ------- x, s2 : ndarray The variance of the distribution. """ invalid, args = self._process_shapes(mu, lmbda, a, b) mu, lmbda, a, b = args invalid_x = invalid | ~(a > 1) invalid_s2 = invalid | ~(a > 2) var_x = b / ((a - 1) * lmbda) var_s2 = b**2 / ((a - 1)**2 * (a - 2)) var_x, var_s2 = np.asarray(var_x), np.asarray(var_s2) var_x[invalid_x] = np.nan var_s2[invalid_s2] = np.nan return var_x[()], var_s2[()] def _process_parameters_pdf(self, x, s2, mu, lmbda, a, b): args = np.broadcast_arrays(x, s2, mu, lmbda, a, b) dtype = np.result_type(1.0, *(arg.dtype for arg in args)) args = [arg.astype(dtype, copy=False) for arg in args] x, s2, mu, lmbda, a, b = args invalid = ~((lmbda > 0) & (a > 0) & (b > 0)) return invalid, args def _process_shapes(self, mu, lmbda, a, b): args = np.broadcast_arrays(mu, lmbda, a, b) dtype = np.result_type(1.0, *(arg.dtype for arg in args)) args = [arg.astype(dtype, copy=False) for arg in args] mu, lmbda, a, b = args invalid = ~((lmbda > 0) & (a > 0) & (b > 0)) return invalid, args def __call__(self, mu=0, lmbda=1, a=1, b=1, seed=None): return normal_inverse_gamma_frozen(mu, lmbda, a, b, seed=seed) normal_inverse_gamma = normal_inverse_gamma_gen()
normal_inverse_gamma_gen
python
getsentry__sentry
src/sentry/api/serializers/models/exploresavedquery.py
{ "start": 1322, "end": 5126 }
class ____(Serializer): def get_attrs(self, item_list, user, **kwargs): result: DefaultDict[str, dict] = defaultdict(lambda: {"created_by": {}}) starred_queries = dict( ExploreSavedQueryStarred.objects.filter( explore_saved_query__in=item_list, user_id=user.id, organization=item_list[0].organization if item_list else None, starred=True, ).values_list("explore_saved_query_id", "position") ) user_last_visited = dict( ExploreSavedQueryLastVisited.objects.filter( explore_saved_query__in=item_list, user_id=user.id, organization=item_list[0].organization if item_list else None, ).values_list("explore_saved_query_id", "last_visited") ) service_serialized = user_service.serialize_many( filter={ "user_ids": [ explore_saved_query.created_by_id for explore_saved_query in item_list if explore_saved_query.created_by_id ] }, as_user=user if user.id else None, ) serialized_users = {user["id"]: user for user in service_serialized} for explore_saved_query in item_list: result[explore_saved_query]["created_by"] = serialized_users.get( str(explore_saved_query.created_by_id) ) if explore_saved_query.id in starred_queries: result[explore_saved_query]["starred"] = True result[explore_saved_query]["position"] = starred_queries[explore_saved_query.id] else: result[explore_saved_query]["starred"] = False result[explore_saved_query]["position"] = None if explore_saved_query.id in user_last_visited: result[explore_saved_query]["user_last_visited"] = user_last_visited[ explore_saved_query.id ] return result def serialize(self, obj, attrs, user, **kwargs) -> ExploreSavedQueryResponse: query_keys = [ "environment", "query", "range", "start", "end", "interval", ] data: ExploreSavedQueryResponse = { "id": str(obj.id), "name": obj.name, "projects": [project.id for project in obj.projects.all()], "dataset": ExploreSavedQueryDataset.get_type_name(obj.dataset), "expired": False, "dateAdded": obj.date_added, "dateUpdated": obj.date_updated, "lastVisited": attrs.get("user_last_visited"), "createdBy": attrs.get("created_by"), "starred": attrs.get("starred"), "position": attrs.get("position"), "isPrebuilt": obj.prebuilt_id is not None, "changedReason": obj.changed_reason, } for key in query_keys: if obj.query.get(key) is not None: data[key] = obj.query[key] # type: ignore[literal-required] # expire queries that are beyond the retention period if "start" in obj.query: start, end = parse_timestamp(obj.query["start"]), parse_timestamp(obj.query["end"]) if start and end: expired, modified_start = outside_retention_with_modified_start( start, end, obj.organization ) data["expired"] = expired data["start"] = modified_start.strftime("%Y-%m-%dT%H:%M:%S.%fZ") if obj.query.get("all_projects"): data["projects"] = list(ALL_ACCESS_PROJECTS) return data
ExploreSavedQueryModelSerializer
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 437859, "end": 439784 }
class ____(Request): """ Get the list of task configuration items names :param tasks: Task IDs :type tasks: Sequence[str] :param skip_empty: If set to 'true' then the names for configurations with missing values are not returned :type skip_empty: bool """ _service = "tasks" _action = "get_configuration_names" _version = "2.23" _schema = { "definitions": {}, "properties": { "skip_empty": { "default": True, "description": ( "If set to 'true' then the names for configurations with missing values are not returned" ), "type": "boolean", }, "tasks": { "description": "Task IDs", "items": {"type": "string"}, "type": "array", }, }, "required": ["tasks"], "type": "object", } def __init__(self, tasks, skip_empty=True, **kwargs): super(GetConfigurationNamesRequest, self).__init__(**kwargs) self.tasks = tasks self.skip_empty = skip_empty @schema_property("tasks") def tasks(self): return self._property_tasks @tasks.setter def tasks(self, value): if value is None: self._property_tasks = None return self.assert_isinstance(value, "tasks", (list, tuple)) self.assert_isinstance(value, "tasks", six.string_types, is_array=True) self._property_tasks = value @schema_property("skip_empty") def skip_empty(self): return self._property_skip_empty @skip_empty.setter def skip_empty(self, value): if value is None: self._property_skip_empty = None return self.assert_isinstance(value, "skip_empty", (bool,)) self._property_skip_empty = value
GetConfigurationNamesRequest
python
pola-rs__polars
py-polars/tests/docs/run_doctest.py
{ "start": 3416, "end": 6638 }
class ____(unittest.TestSuite): # noqa: D101 def __iter__(self) -> Iterator[Any]: for suite in self._tests: suite._tests = [ # type: ignore[attr-defined] test for test in suite._tests # type: ignore[attr-defined] if test.id().rsplit(".", 1)[-1] not in SKIP_METHODS ] yield suite if __name__ == "__main__": # set to True to just run the code, and do not check any output. # Will still report errors if the code is invalid IGNORE_RESULT_ALL = False # Below the implementation of the IGNORE_RESULT directive # You can ignore the result of a doctest by adding "doctest: +IGNORE_RESULT" into # the code block. The difference with SKIP is that if the code errors on running, # that will still be reported. IGNORE_RESULT = doctest.register_optionflag("IGNORE_RESULT") # Set doctests to fail on warnings warnings.simplefilter("error", Warning) warnings.filterwarnings( "ignore", message="datetime.datetime.utcfromtimestamp\\(\\) is deprecated.*", category=DeprecationWarning, ) warnings.filterwarnings( "ignore", message="datetime.datetime.utcnow\\(\\) is deprecated.*", category=DeprecationWarning, ) OutputChecker = doctest.OutputChecker class IgnoreResultOutputChecker(OutputChecker): """Python doctest output checker with support for IGNORE_RESULT.""" def check_output(self, want: str, got: str, optionflags: Any) -> bool: """Return True iff the actual output from an example matches the output.""" if IGNORE_RESULT_ALL: return True if IGNORE_RESULT & optionflags: return True else: return OutputChecker.check_output(self, want, got, optionflags) doctest.OutputChecker = IgnoreResultOutputChecker # type: ignore[misc] # Want to be relaxed about whitespace, strict on True vs 1, and allow '...' pattern doctest.NORMALIZE_WHITESPACE = True doctest.DONT_ACCEPT_TRUE_FOR_1 = True doctest.ELLIPSIS = True # If REPORT_NDIFF is turned on, it will report on line by line, character by # character, differences. The disadvantage is that you cannot just copy the output # directly into the docstring. # doctest.REPORT_NDIFF = True # __file__ returns the __init__.py, so grab the parent src_dir = Path(pl.__file__).parent with TemporaryDirectory() as tmpdir: # collect all tests tests = [ doctest.DocTestSuite( m, extraglobs={"pl": pl, "dirpath": Path(tmpdir)}, tearDown=doctest_teardown, optionflags=1, ) for m in modules_in_path(src_dir) ] test_suite = FilteredTestSuite(tests) # Ensure that we clean up any artifacts produced by the doctests # with patch(pl.DataFrame.write_csv): # run doctests and report result = unittest.TextTestRunner().run(test_suite) success_flag = (result.testsRun > 0) & (len(result.failures) == 0) sys.exit(int(not success_flag))
FilteredTestSuite
python
pytorch__pytorch
test/test_privateuseone_python_backend.py
{ "start": 447, "end": 3411 }
class ____(torch.Tensor): @staticmethod def __new__(cls, size, dtype, raw_data=None, requires_grad=False): # Use a meta Tensor here to be used as the wrapper res = torch._C._acc.create_empty_tensor(size, dtype) res.__class__ = MyDeviceTensor return res def __init__(self, size, dtype, raw_data=None, requires_grad=False): # Store any provided user raw_data self.raw_data = raw_data def __repr__(self): return "MyDeviceTensor" + str(self.raw_data) __str__ = __repr__ def wrap(arr, shape, dtype): # hard code float32 for tests return MyDeviceTensor(shape, dtype, arr) def unwrap(arr): return arr.raw_data # Add some ops @torch.library.impl("aten::add.Tensor", "privateuseone") def add(t1, t2): out = unwrap(t1) + unwrap(t2) return wrap(out, out.shape, torch.float32) @torch.library.impl("aten::mul.Tensor", "privateuseone") def mul(t1, t2): # If unsure what should be the result's properties, you can # use the super_fn (can be useful for type promotion) out = unwrap(t1) * unwrap(t2) return wrap(out, out.shape, torch.float32) @torch.library.impl("aten::detach", "privateuseone") def detach(self): out = unwrap(self) return wrap(out, out.shape, torch.float32) @torch.library.impl("aten::empty_strided", "privateuseone") def empty_strided( size, stride, *, dtype=None, layout=None, device=None, pin_memory=None ): out = np.empty(size) return wrap(out, out.shape, torch.float32) @torch.library.impl("aten::_copy_from", "privateuseone") def _copy_from(a, b): if a.device.type == "npy": npy_data = unwrap(a) else: npy_data = a.numpy() b.raw_data = npy_data @torch.library.impl("aten::view", "privateuseone") def _view(a, b): ans = unwrap(a) return wrap(ans, a.shape, a.dtype) @torch.library.impl("aten::empty.memory_format", "privateuseone") def empty_memory_format( size, *, dtype=None, layout=None, device=None, pin_memory=None, memory_format=None ): ans = np.empty(size) return wrap(ans, ans.shape, torch.float32) @torch.library.impl("aten::sum", "privateuseone") def sum_int_list(*args, **kwargs): ans = unwrap(args[0]).sum() return wrap(ans, ans.shape, torch.float32) @torch.library.impl("aten::ones_like", "privateuseone") def ones_like( self, *, dtype=None, layout=None, device=None, pin_memory=None, memory_format=None ): ans = np.ones_like(unwrap(self)) return wrap(ans, ans.shape, torch.float32) @torch.library.impl("aten::expand", "privateuseone") def expand(self, size, *, implicit=False): ans = np.broadcast_to(self.raw_data, size) return wrap(ans, ans.shape, torch.float32) @torch.library.impl("aten::as_strided", "privateuseone") def as_strided(self, size, stride, storage_offset=None): ans = np.lib.stride_tricks.as_strided(self.raw_data, size, stride) return wrap(ans, ans.shape, torch.float32)
MyDeviceTensor
python
django__django
tests/model_fields/models.py
{ "start": 2925, "end": 3015 }
class ____(models.Model): d = models.DecimalField(max_digits=32, decimal_places=30)
BigD
python
getsentry__sentry
src/sentry/auth/services/auth/model.py
{ "start": 956, "end": 1465 }
class ____(RpcModel): id: int = -1 user_id: int = -1 organization_id: int | None = None application_id: int | None = None application_is_active: bool = False token: str = Field(repr=False, default="") hashed_token: str | None = Field(repr=False, default=None) expires_at: datetime.datetime | None = None allowed_origins: list[str] = Field(default_factory=list) scope_list: list[str] = Field(default_factory=list) scoping_organization_id: int | None = None
RpcApiToken
python
fastai__fastai
nbs/examples/migrating_ignite.py
{ "start": 541, "end": 3837 }
class ____(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 10) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) return F.log_softmax(x, dim=-1) def get_data_loaders(train_batch_size, val_batch_size): data_transform = Compose([ToTensor(), Normalize((0.1307,), (0.3081,))]) train_loader = DataLoader( MNIST(download=True, root=".", transform=data_transform, train=True), batch_size=train_batch_size, shuffle=True) val_loader = DataLoader( MNIST(download=False, root=".", transform=data_transform, train=False), batch_size=val_batch_size, shuffle=False) return train_loader, val_loader def run(train_batch_size, val_batch_size, epochs, lr, momentum, log_interval): train_loader, val_loader = get_data_loaders(train_batch_size, val_batch_size) model = Net() device = "cpu" if torch.cuda.is_available(): device = "cuda" model.to(device) # Move model before creating optimizer optimizer = SGD(model.parameters(), lr=lr, momentum=momentum) criterion = nn.NLLLoss() trainer = create_supervised_trainer(model, optimizer, criterion, device=device) trainer.logger = setup_logger("trainer") val_metrics = {"accuracy": Accuracy(), "nll": Loss(criterion)} evaluator = create_supervised_evaluator(model, metrics=val_metrics, device=device) evaluator.logger = setup_logger("evaluator") desc = "ITERATION - loss: {:.2f}" pbar = tqdm(initial=0, leave=False, total=len(train_loader), desc=desc.format(0)) @trainer.on(Events.ITERATION_COMPLETED(every=log_interval)) def log_training_loss(engine): pbar.desc = desc.format(engine.state.output) pbar.update(log_interval) @trainer.on(Events.EPOCH_COMPLETED) def log_training_results(engine): pbar.refresh() evaluator.run(train_loader) metrics = evaluator.state.metrics avg_accuracy = metrics["accuracy"] avg_nll = metrics["nll"] tqdm.write( "Training Results - Epoch: {} Avg accuracy: {:.2f} Avg loss: {:.2f}".format( engine.state.epoch, avg_accuracy, avg_nll)) @trainer.on(Events.EPOCH_COMPLETED) def log_validation_results(engine): evaluator.run(val_loader) metrics = evaluator.state.metrics avg_accuracy = metrics["accuracy"] avg_nll = metrics["nll"] tqdm.write( "Validation Results - Epoch: {} Avg accuracy: {:.2f} Avg loss: {:.2f}".format( engine.state.epoch, avg_accuracy, avg_nll)) pbar.n = pbar.last_print_n = 0 @trainer.on(Events.EPOCH_COMPLETED | Events.COMPLETED) def log_time(engine): tqdm.write( "{} took {} seconds".format(trainer.last_event_name.name, trainer.state.times[trainer.last_event_name.name])) trainer.run(train_loader, max_epochs=epochs)
Net
python
huggingface__transformers
src/transformers/models/dots1/modeling_dots1.py
{ "start": 16280, "end": 18749 }
class ____(nn.Module): """ A mixed expert module containing shared experts. """ def __init__(self, config): super().__init__() self.config = config self.experts = Dots1NaiveMoe(config) self.gate = Dots1TopkRouter(config) self.shared_experts = Dots1MLP( config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts ) self.n_routed_experts = config.n_routed_experts self.n_group = config.n_group self.topk_group = config.topk_group self.norm_topk_prob = config.norm_topk_prob self.routed_scaling_factor = config.routed_scaling_factor self.top_k = config.num_experts_per_tok def route_tokens_to_experts(self, router_logits): router_logits = router_logits.sigmoid() # main diff with deepseekv3 router_logits = router_logits + self.gate.e_score_correction_bias group_scores = ( router_logits.view(-1, self.n_group, self.n_routed_experts // self.n_group).topk(2, dim=-1)[0].sum(dim=-1) ) group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1] group_mask = torch.zeros_like(group_scores) group_mask.scatter_(1, group_idx, 1) score_mask = ( group_mask.unsqueeze(-1) .expand(-1, self.n_group, self.n_routed_experts // self.n_group) .reshape(-1, self.n_routed_experts) ) scores_for_choice = router_logits.masked_fill(~score_mask.bool(), 0.0) topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1] topk_weights = router_logits.gather(1, topk_indices) if self.norm_topk_prob: denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20 topk_weights /= denominator topk_weights = topk_weights * self.routed_scaling_factor return topk_indices, topk_weights def forward(self, hidden_states): residuals = hidden_states orig_shape = hidden_states.shape router_logits = self.gate(hidden_states) topk_indices, topk_weights = self.route_tokens_to_experts(router_logits) hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) hidden_states = self.experts(hidden_states, topk_indices, topk_weights).view(*orig_shape) hidden_states = hidden_states + self.shared_experts(residuals) return hidden_states
Dots1MoE
python
jmcnamara__XlsxWriter
xlsxwriter/test/table/test_table10.py
{ "start": 481, "end": 2037 }
class ____(unittest.TestCase): """ Test assembling a complete Table file. """ def test_assemble_xml_file(self): """Test writing a table""" self.maxDiff = None worksheet = Worksheet() worksheet.worksheet_meta = WorksheetMeta() worksheet.str_table = SharedStringTable() # Set the table properties. worksheet.add_table("C2:F13", {"name": "MyTable"}) worksheet._prepare_tables(1, {}) fh = StringIO() table = Table() table._set_filehandle(fh) table._set_properties(worksheet.tables[0]) table._assemble_xml_file() exp = _xml_to_list( """ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="1" name="MyTable" displayName="MyTable" ref="C2:F13" totalsRowShown="0"> <autoFilter ref="C2:F13"/> <tableColumns count="4"> <tableColumn id="1" name="Column1"/> <tableColumn id="2" name="Column2"/> <tableColumn id="3" name="Column3"/> <tableColumn id="4" name="Column4"/> </tableColumns> <tableStyleInfo name="TableStyleMedium9" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/> </table> """ ) got = _xml_to_list(fh.getvalue()) self.assertEqual(exp, got)
TestAssembleTable
python
huggingface__transformers
src/transformers/models/swinv2/modeling_swinv2.py
{ "start": 52481, "end": 55773 }
class ____(Swinv2PreTrainedModel, BackboneMixin): def __init__(self, config): super().__init__(config) super()._init_backbone(config) self.num_features = [config.embed_dim] + [int(config.embed_dim * 2**i) for i in range(len(config.depths))] self.embeddings = Swinv2Embeddings(config) self.encoder = Swinv2Encoder(config, self.embeddings.patch_grid) # initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embeddings.patch_embeddings @auto_docstring def forward( self, pixel_values: Tensor, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> BackboneOutput: r""" Examples: ```python >>> from transformers import AutoImageProcessor, AutoBackbone >>> import torch >>> from PIL import Image >>> import requests >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> processor = AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256") >>> model = AutoBackbone.from_pretrained( ... "microsoft/swinv2-tiny-patch4-window8-256", out_features=["stage1", "stage2", "stage3", "stage4"] ... ) >>> inputs = processor(image, return_tensors="pt") >>> outputs = model(**inputs) >>> feature_maps = outputs.feature_maps >>> list(feature_maps[-1].shape) [1, 2048, 7, 7] ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions embedding_output, input_dimensions = self.embeddings(pixel_values) outputs = self.encoder( embedding_output, input_dimensions, output_attentions=output_attentions, output_hidden_states=True, output_hidden_states_before_downsampling=True, return_dict=return_dict, ) hidden_states = outputs.reshaped_hidden_states if return_dict else outputs[-1] feature_maps = () for stage, hidden_state in zip(self.stage_names, hidden_states): if stage in self.out_features: feature_maps += (hidden_state,) if not return_dict: output = (feature_maps,) if output_hidden_states: output += (outputs[1],) if output_attentions: output += (outputs[2],) return output return BackboneOutput( feature_maps=feature_maps, hidden_states=outputs.hidden_states if output_hidden_states else None, attentions=outputs.attentions, ) __all__ = [ "Swinv2ForImageClassification", "Swinv2ForMaskedImageModeling", "Swinv2Model", "Swinv2PreTrainedModel", "Swinv2Backbone", ]
Swinv2Backbone
python
mozilla__bleach
bleach/_vendor/html5lib/treewalkers/etree_lxml.py
{ "start": 1747, "end": 1967 }
class ____(Root): def __init__(self, children): self.children = [FragmentWrapper(self, child) for child in children] self.text = self.tail = None def getnext(self): return None
FragmentRoot
python
ApeWorX__ape
tests/functional/test_project.py
{ "start": 26669, "end": 30652 }
class ____: """ All tests related to ``ape.Project``. """ def test_init(self, with_dependencies_project_path): # Purpose not using `project_with_contracts` fixture. project = Project(with_dependencies_project_path) # NOTE: Using tempdir to avoid clashing with other tests during x-dist. with project.isolate_in_tempdir() as temp_project: assert project.path == with_dependencies_project_path project.manifest_path.unlink(missing_ok=True) # Re-init to show it doesn't create the manifest file. _ = Project(temp_project.path) def test_init_invalid_config(self): here = os.curdir with create_tempdir() as temp_dir: cfgfile = temp_dir / "ape-config.yaml" # Name is invalid! cfgfile.write_text("name:\n {asdf}") os.chdir(temp_dir) expected = r"[.\n]*Input should be a valid string\n-->1: name:\n 2: {asdf}[.\n]*" weird_project = Project(temp_dir) try: with pytest.raises(ConfigError, match=expected): _ = weird_project.path finally: os.chdir(here) def test_config_override(self, with_dependencies_project_path): contracts_folder = with_dependencies_project_path / "my_contracts" config = {"contracts_folder": contracts_folder.name} project = Project(with_dependencies_project_path, config_override=config) assert project.contracts_folder == contracts_folder def test_from_manifest(self, manifest): # Purposely not using `project_from_manifest` fixture. project = Project.from_manifest(manifest) assert isinstance(project, Project) assert project.manifest == manifest def test_from_manifest_contracts_iter(self, contract_type, project_from_manifest): actual = set(iter(project_from_manifest.contracts)) assert actual == {"FooContractFromManifest"} def test_from_manifest_getattr(self, contract_type, project_from_manifest): expected = ContractContainer(contract_type) actual = project_from_manifest.FooContractFromManifest assert isinstance(actual, ContractContainer) assert actual == expected def test_from_manifest_getitem(self, contract_type, project_from_manifest): expected = ContractContainer(contract_type) assert project_from_manifest["FooContractFromManifest"] == expected def test_from_manifest_load_contracts(self, contract_type): """ Show if contract-types are missing but contracts set, compiling will add contract-types. """ manifest = make_manifest(contract_type, include_contract_type=False) project = Project.from_manifest(manifest) assert not project.manifest.contract_types, "Setup failed" # Returns containers, not types. actual = project.load_contracts() assert actual[contract_type.name].contract_type == contract_type # Also, show it got set on the manifest. assert project.manifest.contract_types == {contract_type.name: contract_type} def test_from_python_library(self): # web3py as an ape-project dependency. web3 = Project.from_python_library("web3") assert "site-packages" in str(web3.path) assert web3.path.name == "web3" def test_hash(self, with_dependencies_project_path, project_from_manifest): """ Show we can use projects in sets. """ project_0 = Project(with_dependencies_project_path) project_1 = Project.from_python_library("web3") project_2 = project_from_manifest # Show we can use in sets. project_set = {project_0, project_1, project_2} assert len(project_set) == 3 # Show we can use as dict-keys: project_dict = {project_0: 123} assert project_dict[project_0] == 123
TestProject
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 75927, "end": 79832 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[8, 8]"): l_x_ = L_x_ subgraph_0 = self.subgraph_0 invoke_subgraph = torch.ops.higher_order.invoke_subgraph(subgraph_0, 'subgraph_0', l_x_); subgraph_0 = None getitem: "f32[8, 8]" = invoke_subgraph[0]; invoke_subgraph = None subgraph_1 = self.subgraph_0 invoke_subgraph_1 = torch.ops.higher_order.invoke_subgraph(subgraph_1, 'subgraph_0', l_x_); subgraph_1 = l_x_ = None getitem_1: "f32[8, 8]" = invoke_subgraph_1[0]; invoke_subgraph_1 = None add: "f32[8, 8]" = getitem + getitem_1; getitem = getitem_1 = None return (add,) class subgraph_0(torch.nn.Module): def forward(self, l_x_: "f32[8, 8]"): fwd_body_0 = self.fwd_body_0 bwd_body_0 = self.bwd_body_0 autograd_function_apply: "f32[8, 8]" = torch.ops.higher_order.autograd_function_apply(fwd_body_0, bwd_body_0, l_x_, args_tensor_mask = [True], non_differentiable_idx = []); fwd_body_0 = bwd_body_0 = l_x_ = None return (autograd_function_apply,) class fwd_body_0(torch.nn.Module): def forward(self, ctx : torch.autograd.function.Function, x: "f32[8, 8]"): _set_grad_enabled = torch._C._set_grad_enabled(False); _set_grad_enabled = None sin: "f32[8, 8]" = torch.sin(x) _set_grad_enabled_1 = torch._C._set_grad_enabled(True); _set_grad_enabled_1 = None return (sin, [x]) class bwd_body_0(torch.nn.Module): def forward(self, ctx : torch.autograd.function.Function, grad_out: "f32[8, 8]", x: "f32[8, 8]"): _set_grad_enabled = torch._C._set_grad_enabled(False); _set_grad_enabled = None cos: "f32[8, 8]" = torch.cos(grad_out); grad_out = None mul: "f32[8, 8]" = x * cos; x = cos = None _set_grad_enabled_1 = torch._C._set_grad_enabled(True); _set_grad_enabled_1 = None return mul """, ) @requires_gpu def test_triton_kernel_native(self): from torch.testing._internal.triton_utils import add_kernel def call_triton_add( x: torch.Tensor, y: torch.Tensor, output: torch.Tensor, grid_type: int, num=1, positional=False, ): n_elements = output.numel() def grid_fn(meta): return (triton.cdiv(num, meta["BLOCK_SIZE"]),) if grid_type == 0: grid = (x.numel(),) elif grid_type == 1: grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) else: grid = grid_fn if positional: add_kernel[grid](x, y, output, n_elements, 16) else: add_kernel[grid](x, y, output, n_elements, BLOCK_SIZE=16) return output @nested_compile_region def gn(x, y): o = torch.zeros_like(x) call_triton_add(x, y, o, 0) return o.sin() def fn(x, y): x = x.sin() y = y.sin() z = gn(x, y) return gn(z, y) t1 = torch.rand(5, device=GPU_TYPE) t2 = torch.rand(5, device=GPU_TYPE) ref = fn(t1, t2) backend = AotEagerAndRecordGraphs() opt_fn = torch.compile(fn, backend=backend, fullgraph=True) self.assertEqual(opt_fn(t1, t2), ref) # NOTE THAT THIS TEST DOES NOT REALLY WORK # We wanted one invoke_subgraph called twice, but because of # constant_args_idx changing in the graph, the graph equivalence fails if not TEST_WITH_CROSSREF: self.assertExpectedInline( normalize_gm(backend.graphs[0].print_readable(print_output=False)), """\
GraphModule
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_assets.py
{ "start": 1349, "end": 6007 }
class ____: def test_should_response_200(self, test_client, dag_maker): with dag_maker( dag_id="upstream", schedule=[Asset(uri="s3://bucket/next-run-asset/1", name="asset1")], serialized=True, ): EmptyOperator(task_id="task1") dag_maker.create_dagrun() dag_maker.sync_dagbag_to_db() with assert_queries_count(4): response = test_client.get("/next_run_assets/upstream") assert response.status_code == 200 assert response.json() == { "asset_expression": { "all": [ { "asset": { "uri": "s3://bucket/next-run-asset/1", "name": "asset1", "group": "asset", "id": mock.ANY, } } ] }, "events": [ {"id": mock.ANY, "uri": "s3://bucket/next-run-asset/1", "name": "asset1", "lastUpdate": None} ], } def test_should_respond_401(self, unauthenticated_test_client): response = unauthenticated_test_client.get("/next_run_assets/upstream") assert response.status_code == 401 def test_should_respond_403(self, unauthorized_test_client): response = unauthorized_test_client.get("/next_run_assets/upstream") assert response.status_code == 403 def test_should_set_last_update_only_for_queued_and_hide_flag(self, test_client, dag_maker, session): with dag_maker( dag_id="two_assets_equal", schedule=[ Asset(uri="s3://bucket/A", name="A"), Asset(uri="s3://bucket/B", name="B"), ], serialized=True, ): EmptyOperator(task_id="t") dr = dag_maker.create_dagrun() dag_maker.sync_dagbag_to_db() assets = { a.uri: a for a in session.query(AssetModel).filter(AssetModel.uri.in_(["s3://bucket/A", "s3://bucket/B"])) } # Queue and add an event only for A session.add(AssetDagRunQueue(asset_id=assets["s3://bucket/A"].id, target_dag_id="two_assets_equal")) session.add( AssetEvent(asset_id=assets["s3://bucket/A"].id, timestamp=dr.logical_date or pendulum.now()) ) session.commit() response = test_client.get("/next_run_assets/two_assets_equal") assert response.status_code == 200 assert response.json() == { "asset_expression": { "all": [ { "asset": { "uri": "s3://bucket/A", "name": "A", "group": "asset", "id": mock.ANY, } }, { "asset": { "uri": "s3://bucket/B", "name": "B", "group": "asset", "id": mock.ANY, } }, ] }, # events are ordered by uri "events": [ {"id": mock.ANY, "uri": "s3://bucket/A", "name": "A", "lastUpdate": mock.ANY}, {"id": mock.ANY, "uri": "s3://bucket/B", "name": "B", "lastUpdate": None}, ], } def test_last_update_respects_latest_run_filter(self, test_client, dag_maker, session): with dag_maker( dag_id="filter_run", schedule=[Asset(uri="s3://bucket/F", name="F")], serialized=True, ): EmptyOperator(task_id="t") dr = dag_maker.create_dagrun() dag_maker.sync_dagbag_to_db() asset = session.query(AssetModel).filter(AssetModel.uri == "s3://bucket/F").one() session.add(AssetDagRunQueue(asset_id=asset.id, target_dag_id="filter_run")) # event before latest_run should be ignored ts_base = dr.logical_date or pendulum.now() session.add(AssetEvent(asset_id=asset.id, timestamp=ts_base.subtract(minutes=10))) # event after latest_run counts session.add(AssetEvent(asset_id=asset.id, timestamp=ts_base.add(minutes=10))) session.commit() resp = test_client.get("/next_run_assets/filter_run") assert resp.status_code == 200 ev = resp.json()["events"][0] assert ev["lastUpdate"] is not None assert "queued" not in ev
TestNextRunAssets
python
ray-project__ray
python/ray/remote_function.py
{ "start": 1233, "end": 24448 }
class ____: """A remote function. This is a decorated function. It can be used to spawn tasks. Attributes: _language: The target language. _function: The original function. _function_descriptor: The function descriptor. This is not defined until the remote function is first invoked because that is when the function is pickled, and the pickled function is used to compute the function descriptor. _function_name: The module and function name. _num_cpus: The default number of CPUs to use for invocations of this remote function. _num_gpus: The default number of GPUs to use for invocations of this remote function. _memory: The heap memory request in bytes for this task/actor, rounded down to the nearest integer. _label_selector: The label requirements on a node for scheduling of the task or actor. _fallback_strategy: Soft constraints of a list of decorator options to fall back on when scheduling on a node. _resources: The default custom resource requirements for invocations of this remote function. _num_returns: The default number of return values for invocations of this remote function. _max_calls: The number of times a worker can execute this function before exiting. _max_retries: The number of times this task may be retried on worker failure. _retry_exceptions: Whether application-level errors should be retried. This can be a boolean or a list/tuple of exceptions that should be retried. _runtime_env: The runtime environment for this task. _decorator: An optional decorator that should be applied to the remote function invocation (as opposed to the function execution) before invoking the function. The decorator must return a function that takes in two arguments ("args" and "kwargs"). In most cases, it should call the function that was passed into the decorator and return the resulting ObjectRefs. For an example, see "test_decorated_function" in "python/ray/tests/test_basic.py". _function_signature: The function signature. _last_export_cluster_and_job: A pair of the last exported cluster and job to help us to know whether this function was exported. This is an imperfect mechanism used to determine if we need to export the remote function again. It is imperfect in the sense that the actor class definition could be exported multiple times by different workers. _scheduling_strategy: Strategy about how to schedule this remote function. """ def __init__( self, language, function, function_descriptor, task_options, ): if inspect.iscoroutinefunction(function): raise ValueError( "'async def' should not be used for remote tasks. You can wrap the " "async function with `asyncio.run(f())`. See more at:" "https://docs.ray.io/en/latest/ray-core/actors/async_api.html " ) self._default_options = task_options # When gpu is used, set the task non-recyclable by default. # https://github.com/ray-project/ray/issues/29624 for more context. # Note: Ray task worker process is not being reused when nsight # profiler is running, as nsight/rocprof-sys generate report # once the process exit. num_gpus = self._default_options.get("num_gpus") or 0 if ( num_gpus > 0 and self._default_options.get("max_calls", None) is None ) or any( [ s in (self._default_options.get(s) or {}) for s in ["nsight", "rocprof-sys"] ] ): self._default_options["max_calls"] = 1 # TODO(suquark): This is a workaround for class attributes of options. # They are being used in some other places, mostly tests. Need cleanup later. # E.g., actors uses "__ray_metadata__" to collect options, we can so something # similar for remote functions. for k, v in ray_option_utils.task_options.items(): setattr(self, "_" + k, task_options.get(k, v.default_value)) self._runtime_env = parse_runtime_env_for_task_or_actor(self._runtime_env) if "runtime_env" in self._default_options: self._default_options["runtime_env"] = self._runtime_env # Pre-calculate runtime env info, to avoid re-calculation at `remote` # invocation. When `remote` call has specified extra `option` field, # runtime env will be overwritten and re-serialized. # # Caveat: To support dynamic runtime envs in # `func.option(runtime_env={...}).remote()`, we recalculate the serialized # runtime env info in the `option` call. But it's acceptable since # pre-calculation here only happens once at `RemoteFunction` initialization. self._serialized_base_runtime_env_info = "" if self._runtime_env: self._serialized_base_runtime_env_info = get_runtime_env_info( self._runtime_env, is_job_runtime_env=False, serialize=True, ) self._language = language self._is_generator = inspect.isgeneratorfunction(function) self._function = function self._function_signature = None # Guards trace injection to enforce exactly once semantics self._inject_lock = Lock() self._function_name = function.__module__ + "." + function.__name__ self._function_descriptor = function_descriptor self._is_cross_language = language != Language.PYTHON self._decorator = getattr(function, "__ray_invocation_decorator__", None) self._last_export_cluster_and_job = None self._uuid = uuid.uuid4() # Override task.remote's signature and docstring @wraps(function) def _remote_proxy(*args, **kwargs): return self._remote( serialized_runtime_env_info=self._serialized_base_runtime_env_info, args=args, kwargs=kwargs, **self._default_options, ) self.remote = _remote_proxy def __call__(self, *args, **kwargs): raise TypeError( "Remote functions cannot be called directly. Instead " f"of running '{self._function_name}()', " f"try '{self._function_name}.remote()'." ) # Lock is not picklable def __getstate__(self): attrs = self.__dict__.copy() del attrs["_inject_lock"] return attrs def __setstate__(self, state): self.__dict__.update(state) self.__dict__["_inject_lock"] = Lock() def options(self, **task_options): """Configures and overrides the task invocation parameters. The arguments are the same as those that can be passed to :obj:`ray.remote`. Overriding `max_calls` is not supported. Args: num_returns: It specifies the number of object refs returned by the remote function invocation. num_cpus: The quantity of CPU cores to reserve for this task or for the lifetime of the actor. num_gpus: The quantity of GPUs to reserve for this task or for the lifetime of the actor. resources (Dict[str, float]): The quantity of various custom resources to reserve for this task or for the lifetime of the actor. This is a dictionary mapping strings (resource names) to floats. label_selector (Dict[str, str]): If specified, the labels required for the node on which this actor can be scheduled on. The label selector consist of key-value pairs, where the keys are label names and the value are expressions consisting of an operator with label values or just a value to indicate equality. fallback_strategy (List[Dict[str, Any]]): If specified, expresses soft constraints through a list of decorator options to fall back on when scheduling on a node. accelerator_type: If specified, requires that the task or actor run on a node with the specified type of accelerator. See :ref:`accelerator types <accelerator_types>`. memory: The heap memory request in bytes for this task/actor, rounded down to the nearest integer. object_store_memory: The object store memory request for actors only. max_calls: This specifies the maximum number of times that a given worker can execute the given remote function before it must exit (this can be used to address memory leaks in third-party libraries or to reclaim resources that cannot easily be released, e.g., GPU memory that was acquired by TensorFlow). By default this is infinite for CPU tasks and 1 for GPU tasks (to force GPU tasks to release resources after finishing). max_retries: This specifies the maximum number of times that the remote function should be rerun when the worker process executing it crashes unexpectedly. The minimum valid value is 0, the default is 3 (default), and a value of -1 indicates infinite retries. runtime_env (Dict[str, Any]): Specifies the runtime environment for this actor or task and its children. See :ref:`runtime-environments` for detailed documentation. retry_exceptions: This specifies whether application-level errors should be retried up to max_retries times. scheduling_strategy: Strategy about how to schedule a remote function or actor. Possible values are None: ray will figure out the scheduling strategy to use, it will either be the PlacementGroupSchedulingStrategy using parent's placement group if parent has one and has placement_group_capture_child_tasks set to true, or "DEFAULT"; "DEFAULT": default hybrid scheduling; "SPREAD": best effort spread scheduling; `PlacementGroupSchedulingStrategy`: placement group based scheduling; `NodeAffinitySchedulingStrategy`: node id based affinity scheduling. enable_task_events: This specifies whether to enable task events for this task. If set to True, task events such as (task running, finished) are emitted, and available to Ray Dashboard and State API. See :ref:`state-api-overview-ref` for more details. _labels: The key-value labels of a task. Examples: .. code-block:: python @ray.remote(num_gpus=1, max_calls=1, num_returns=2) def f(): return 1, 2 # Task g will require 2 gpus instead of 1. g = f.options(num_gpus=2) """ func_cls = self # override original options default_options = self._default_options.copy() # max_calls could not be used in ".options()", we should remove it before # merging options from '@ray.remote'. default_options.pop("max_calls", None) updated_options = ray_option_utils.update_options(default_options, task_options) ray_option_utils.validate_task_options(updated_options, in_options=True) # Only update runtime_env and re-calculate serialized runtime env info when # ".options()" specifies new runtime_env. serialized_runtime_env_info = self._serialized_base_runtime_env_info if "runtime_env" in task_options: updated_options["runtime_env"] = parse_runtime_env_for_task_or_actor( updated_options["runtime_env"] ) # Re-calculate runtime env info based on updated runtime env. if updated_options["runtime_env"]: serialized_runtime_env_info = get_runtime_env_info( updated_options["runtime_env"], is_job_runtime_env=False, serialize=True, ) class FuncWrapper: def remote(self, *args, **kwargs): return func_cls._remote( args=args, kwargs=kwargs, serialized_runtime_env_info=serialized_runtime_env_info, **updated_options, ) @DeveloperAPI def bind(self, *args, **kwargs): """ For Ray DAG building that creates static graph from decorated class or functions. """ from ray.dag.function_node import FunctionNode return FunctionNode(func_cls._function, args, kwargs, updated_options) return FuncWrapper() @wrap_auto_init @_tracing_task_invocation def _remote( self, args=None, kwargs=None, serialized_runtime_env_info: Optional[str] = None, **task_options, ): """Submit the remote function for execution.""" # We pop the "max_calls" coming from "@ray.remote" here. We no longer need # it in "_remote()". task_options.pop("max_calls", None) if client_mode_should_convert(): return client_mode_convert_function(self, args, kwargs, **task_options) worker = ray._private.worker.global_worker worker.check_connected() if worker.mode != ray._private.worker.WORKER_MODE: # Only need to record on the driver side # since workers are created via tasks or actors # launched from the driver. from ray._common.usage import usage_lib usage_lib.record_library_usage("core") # We cannot do this when the function is first defined, because we need # ray.init() to have been called when this executes with self._inject_lock: if self._function_signature is None: self._function = _inject_tracing_into_function(self._function) self._function_signature = ray._common.signature.extract_signature( self._function ) # If this function was not exported in this cluster and job, we need to # export this function again, because the current GCS doesn't have it. if ( not self._is_cross_language and self._last_export_cluster_and_job != worker.current_cluster_and_job ): self._function_descriptor = PythonFunctionDescriptor.from_function( self._function, self._uuid ) # There is an interesting question here. If the remote function is # used by a subsequent driver (in the same script), should the # second driver pickle the function again? If yes, then the remote # function definition can differ in the second driver (e.g., if # variables in its closure have changed). We probably want the # behavior of the remote function in the second driver to be # independent of whether or not the function was invoked by the # first driver. This is an argument for repickling the function, # which we do here. self._pickled_function = pickle_dumps( self._function, f"Could not serialize the function {self._function_descriptor.repr}", ) self._last_export_cluster_and_job = worker.current_cluster_and_job worker.function_actor_manager.export(self) kwargs = {} if kwargs is None else kwargs args = [] if args is None else args # fill task required options for k, v in ray_option_utils.task_options.items(): if k == "max_retries": # TODO(swang): We need to override max_retries here because the default # value gets set at Ray import time. Ideally, we should allow setting # default values from env vars for other options too. v.default_value = os.environ.get( "RAY_TASK_MAX_RETRIES", v.default_value ) v.default_value = int(v.default_value) task_options[k] = task_options.get(k, v.default_value) # "max_calls" already takes effects and should not apply again. # Remove the default value here. task_options.pop("max_calls", None) # TODO(suquark): cleanup these fields name = task_options["name"] placement_group = task_options["placement_group"] placement_group_bundle_index = task_options["placement_group_bundle_index"] placement_group_capture_child_tasks = task_options[ "placement_group_capture_child_tasks" ] scheduling_strategy = task_options["scheduling_strategy"] num_returns = task_options["num_returns"] if num_returns is None: if self._is_generator: num_returns = "streaming" else: num_returns = 1 if num_returns == "dynamic": num_returns = -1 elif num_returns == "streaming": # TODO(sang): This is a temporary private API. # Remove it when we migrate to the streaming generator. num_returns = ray._raylet.STREAMING_GENERATOR_RETURN generator_backpressure_num_objects = task_options[ "_generator_backpressure_num_objects" ] if generator_backpressure_num_objects is None: generator_backpressure_num_objects = -1 max_retries = task_options["max_retries"] retry_exceptions = task_options["retry_exceptions"] if isinstance(retry_exceptions, (list, tuple)): retry_exception_allowlist = tuple(retry_exceptions) retry_exceptions = True else: retry_exception_allowlist = None if scheduling_strategy is None or not isinstance( scheduling_strategy, PlacementGroupSchedulingStrategy ): _warn_if_using_deprecated_placement_group(task_options, 4) resources = ray._common.utils.resources_from_ray_options(task_options) if scheduling_strategy is None or isinstance( scheduling_strategy, PlacementGroupSchedulingStrategy ): if isinstance(scheduling_strategy, PlacementGroupSchedulingStrategy): placement_group = scheduling_strategy.placement_group placement_group_bundle_index = ( scheduling_strategy.placement_group_bundle_index ) placement_group_capture_child_tasks = ( scheduling_strategy.placement_group_capture_child_tasks ) if placement_group_capture_child_tasks is None: placement_group_capture_child_tasks = ( worker.should_capture_child_tasks_in_placement_group ) placement_group = _configure_placement_group_based_on_context( placement_group_capture_child_tasks, placement_group_bundle_index, resources, {}, # no placement_resources for tasks self._function_descriptor.function_name, placement_group=placement_group, ) if not placement_group.is_empty: scheduling_strategy = PlacementGroupSchedulingStrategy( placement_group, placement_group_bundle_index, placement_group_capture_child_tasks, ) else: scheduling_strategy = "DEFAULT" if _task_launch_hook: _task_launch_hook(self._function_descriptor, resources, scheduling_strategy) # Override enable_task_events to default for actor if not specified (i.e. None) enable_task_events = task_options.get("enable_task_events") labels = task_options.get("_labels") label_selector = task_options.get("label_selector") fallback_strategy = task_options.get("fallback_strategy") def invocation(args, kwargs): if self._is_cross_language: list_args = cross_language._format_args(worker, args, kwargs) elif not args and not kwargs and not self._function_signature: list_args = [] else: list_args = ray._common.signature.flatten_args( self._function_signature, args, kwargs ) if worker.mode == ray._private.worker.LOCAL_MODE: assert ( not self._is_cross_language ), "Cross language remote function cannot be executed locally." object_refs = worker.core_worker.submit_task( self._language, self._function_descriptor, list_args, name if name is not None else "", num_returns, resources, max_retries, retry_exceptions, retry_exception_allowlist, scheduling_strategy, worker.debugger_breakpoint, serialized_runtime_env_info or "{}", generator_backpressure_num_objects, enable_task_events, labels, label_selector, fallback_strategy, ) # Reset worker's debug context from the last "remote" command # (which applies only to this .remote call). worker.debugger_breakpoint = b"" if num_returns == STREAMING_GENERATOR_RETURN: # Streaming generator will return a single ref # that is for the generator task. assert len(object_refs) == 1 generator_ref = object_refs[0] return ObjectRefGenerator(generator_ref, worker) if len(object_refs) == 1: return object_refs[0] elif len(object_refs) > 1: return object_refs if self._decorator is not None: invocation = self._decorator(invocation) return invocation(args, kwargs) @DeveloperAPI def bind(self, *args, **kwargs): """ For Ray DAG building that creates static graph from decorated class or functions. """ from ray.dag.function_node import FunctionNode return FunctionNode(self._function, args, kwargs, self._default_options)
RemoteFunction
python
crytic__slither
slither/printers/summary/function.py
{ "start": 171, "end": 3945 }
class ____(AbstractPrinter): ARGUMENT = "function-summary" HELP = "Print a summary of the functions" WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#function-summary" @staticmethod def _convert(l): if l: n = 2 l = [l[i : i + n] for i in range(0, len(l), n)] l = [str(x) for x in l] return "\n".join(l) return str(l) def output(self, _filename): # pylint: disable=too-many-locals """ _filename is not used Args: _filename(string) """ all_tables = [] all_txt = "" for c in self.contracts: (name, inheritance, var, func_summaries, modif_summaries) = c.get_summary() txt = f"\nContract {name}" txt += "\nContract vars: " + str(var) txt += "\nInheritance:: " + str(inheritance) table = MyPrettyTable( [ "Function", "Visibility", "Modifiers", "Read", "Write", "Internal Calls", "External Calls", "Cyclomatic Complexity", ] ) for ( _c_name, f_name, visi, modifiers, read, write, internal_calls, external_calls, cyclomatic_complexity, ) in func_summaries: read = self._convert(sorted(read)) write = self._convert(sorted(write)) internal_calls = self._convert(sorted(internal_calls)) external_calls = self._convert(sorted(external_calls)) table.add_row( [ f_name, visi, sorted(modifiers), read, write, internal_calls, external_calls, cyclomatic_complexity, ] ) txt += "\n \n" + str(table) table = MyPrettyTable( [ "Modifiers", "Visibility", "Read", "Write", "Internal Calls", "External Calls", "Cyclomatic Complexity", ] ) for ( _c_name, f_name, visi, _, read, write, internal_calls, external_calls, cyclomatic_complexity, ) in modif_summaries: read = self._convert(sorted(read)) write = self._convert(sorted(write)) internal_calls = self._convert(sorted(internal_calls)) external_calls = self._convert(sorted(external_calls)) table.add_row( [ f_name, visi, read, write, internal_calls, external_calls, cyclomatic_complexity, ] ) txt += "\n\n" + str(table) txt += "\n" self.info(txt) all_tables.append((name, table)) all_txt += txt res = self.generate_output(all_txt) for name, table in all_tables: res.add_pretty_table(table, name) return res
FunctionSummary
python
jazzband__django-model-utils
tests/test_fields/test_field_tracker.py
{ "start": 26086, "end": 30877 }
class ____(FieldTrackerMixin, TestCase): tracked_class = TrackedFileField instance: TrackedFileField def setUp(self) -> None: self.instance = self.tracked_class() self.tracker = self.instance.tracker self.some_file = 'something.txt' self.another_file = 'another.txt' def test_saved_data_without_instance(self) -> None: """ Tests that instance won't get copied by the Field Tracker. This change was introduced in Django 3.1 with https://github.com/django/django/pull/12055 It results in a dramatic CPU and memory usage of FieldTracker on FileField and its subclasses. The pickling/deepcopying the instance is useless in the context of FieldTracker thus we are skipping it. """ self.assertEqual(self.tracker.saved_data, {}) self.update_instance(some_file=self.some_file) field_file_copy = self.tracker.saved_data.get('some_file') assert field_file_copy is not None self.assertEqual(field_file_copy.__getstate__().get('instance'), None) self.assertEqual(self.instance.some_file.instance, self.instance) self.assertIsInstance(self.instance.some_file, FieldFile) def test_pre_save_changed(self) -> None: self.assertChanged(some_file=None) self.instance.some_file = self.some_file self.assertChanged(some_file=None) def test_pre_save_has_changed(self) -> None: self.assertHasChanged(some_file=True) self.instance.some_file = self.some_file self.assertHasChanged(some_file=True) def test_pre_save_previous(self) -> None: self.assertPrevious(some_file=None) self.instance.some_file = self.some_file self.assertPrevious(some_file=None) def test_post_save_changed(self) -> None: self.update_instance(some_file=self.some_file) self.assertChanged() previous_file = self.instance.some_file self.instance.some_file = self.another_file self.assertChanged(some_file=previous_file) # test deferred file field deferred_instance = self.tracked_class.objects.defer('some_file')[0] deferred_instance.some_file # access field to fetch from database self.assertChanged(tracker=deferred_instance.tracker) previous_file = deferred_instance.some_file deferred_instance.some_file = self.another_file self.assertChanged( tracker=deferred_instance.tracker, some_file=previous_file, ) def test_post_save_has_changed(self) -> None: self.update_instance(some_file=self.some_file) self.assertHasChanged(some_file=False) self.instance.some_file = self.another_file self.assertHasChanged(some_file=True) # test deferred file field deferred_instance = self.tracked_class.objects.defer('some_file')[0] deferred_instance.some_file # access field to fetch from database self.assertHasChanged( tracker=deferred_instance.tracker, some_file=False, ) deferred_instance.some_file = self.another_file self.assertHasChanged( tracker=deferred_instance.tracker, some_file=True, ) def test_post_save_previous(self) -> None: self.update_instance(some_file=self.some_file) previous_file = self.instance.some_file self.instance.some_file = self.another_file self.assertPrevious(some_file=previous_file) # test deferred file field deferred_instance = self.tracked_class.objects.defer('some_file')[0] deferred_instance.some_file # access field to fetch from database self.assertPrevious( tracker=deferred_instance.tracker, some_file=previous_file, ) deferred_instance.some_file = self.another_file self.assertPrevious( tracker=deferred_instance.tracker, some_file=previous_file, ) def test_current(self) -> None: self.assertCurrent(some_file=self.instance.some_file, id=None) self.instance.some_file = self.some_file self.assertCurrent(some_file=self.instance.some_file, id=None) # test deferred file field self.instance.save() deferred_instance = self.tracked_class.objects.defer('some_file')[0] deferred_instance.some_file # access field to fetch from database self.assertCurrent( some_file=self.instance.some_file, id=self.instance.id, ) self.instance.some_file = self.another_file self.assertCurrent( some_file=self.instance.some_file, id=self.instance.id, )
FieldTrackerFileFieldTests
python
django__django
tests/multiple_database/tests.py
{ "start": 80369, "end": 80539 }
class ____: """ A router that sends all writes to the other database. """ def db_for_write(self, model, **hints): return "other"
WriteToOtherRouter
python
spack__spack
lib/spack/spack/error.py
{ "start": 4375, "end": 4494 }
class ____(SpackError): """Raised when the wrong arguments are suppled to the patch directive."""
PatchDirectiveError
python
allegroai__clearml
clearml/backend_api/services/v2_23/queues.py
{ "start": 57164, "end": 57426 }
class ____(Request): """ """ _service = "queues" _action = "get_default" _version = "2.23" _schema = { "additionalProperties": True, "definitions": {}, "properties": {}, "type": "object", }
GetDefaultRequest
python
PrefectHQ__prefect
tests/test_logging.py
{ "start": 53795, "end": 55992 }
class ____: def test_json_log_formatter(self): formatter = JsonFormatter("default", None, "%") record = logging.LogRecord( name="Test Log", level=1, pathname="/path/file.py", lineno=1, msg="log message", args=None, exc_info=None, ) formatted = formatter.format(record) # we should be able to load the formatted JSON successfully deserialized = json.loads(formatted) # we can't check for an exact JSON string because some attributes vary at # runtime, so check some known attributes instead assert deserialized["name"] == "Test Log" assert deserialized["levelname"] == "Level 1" assert deserialized["filename"] == "file.py" assert deserialized["lineno"] == 1 def test_json_log_formatter_with_exception(self): exc_info = None try: raise Exception("test exception") # noqa except Exception as exc: # noqa exc_info = sys.exc_info() formatter = JsonFormatter("default", None, "%") record = logging.LogRecord( name="Test Log", level=1, pathname="/path/file.py", lineno=1, msg="log message", args=None, exc_info=exc_info, ) formatted = formatter.format(record) # we should be able to load the formatted JSON successfully deserialized = json.loads(formatted) # we can't check for an exact JSON string because some attributes vary at # runtime, so check some known attributes instead assert deserialized["name"] == "Test Log" assert deserialized["levelname"] == "Level 1" assert deserialized["filename"] == "file.py" assert deserialized["lineno"] == 1 assert deserialized["exc_info"] is not None assert deserialized["exc_info"]["type"] == "Exception" assert deserialized["exc_info"]["message"] == "test exception" assert deserialized["exc_info"]["traceback"] is not None assert len(deserialized["exc_info"]["traceback"]) > 0
TestJsonFormatter
python
instagram__MonkeyType
tests/test_config.py
{ "start": 290, "end": 1090 }
class ____: def test_excludes_stdlib(self): assert not config.default_code_filter(sysconfig.get_path.__code__) def test_excludes_site_packages(self): assert not config.default_code_filter(pytest.skip.__code__) def test_includes_otherwise(self): assert config.default_code_filter(config.default_code_filter.__wrapped__.__code__) def test_excludes_frozen_importlib(self): assert not config.default_code_filter(_frozen_importlib.spec_from_loader.__code__) def test_includes_stdlib_in_MONKEYTYPE_TRACE_MODULES(self, monkeypatch): monkeypatch.setenv('MONKEYTYPE_TRACE_MODULES', 'sysconfig') assert config.default_code_filter(sysconfig.get_config_vars.__code__) monkeypatch.delenv('MONKEYTYPE_TRACE_MODULES')
TestDefaultCodeFilter
python
great-expectations__great_expectations
tests/datasource/fluent/_fake_cloud_api.py
{ "start": 1925, "end": 2168 }
class ____(pydantic.BaseModel): data: _DatasourceSchema @classmethod def from_datasource_json(cls, ds_payload: str | bytes) -> CloudResponseSchema: data = json.loads(ds_payload) return cls(**data)
CloudResponseSchema
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/sqlite/aiosqlite.py
{ "start": 8225, "end": 9639 }
class ____(SQLiteDialect_pysqlite): driver = "aiosqlite" supports_statement_cache = True is_async = True supports_server_side_cursors = True execution_ctx_cls = SQLiteExecutionContext_aiosqlite @classmethod def import_dbapi(cls) -> AsyncAdapt_aiosqlite_dbapi: return AsyncAdapt_aiosqlite_dbapi( __import__("aiosqlite"), __import__("sqlite3") ) @classmethod def get_pool_class(cls, url: URL) -> type[pool.Pool]: if cls._is_url_file_db(url): return pool.AsyncAdaptedQueuePool else: return pool.StaticPool def is_disconnect( self, e: DBAPIModule.Error, connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]], cursor: Optional[DBAPICursor], ) -> bool: self.dbapi = cast("DBAPIModule", self.dbapi) if isinstance(e, self.dbapi.OperationalError): err_lower = str(e).lower() if ( "no active connection" in err_lower or "connection closed" in err_lower ): return True return super().is_disconnect(e, connection, cursor) def get_driver_connection( self, connection: DBAPIConnection ) -> AsyncIODBAPIConnection: return connection._connection # type: ignore[no-any-return] dialect = SQLiteDialect_aiosqlite
SQLiteDialect_aiosqlite
python
streamlit__streamlit
lib/tests/streamlit/elements/graphviz_test.py
{ "start": 867, "end": 6082 }
class ____(DeltaGeneratorTestCase): """Test ability to marshall graphviz_chart protos.""" def test_spec(self): """Test that it can be called with spec.""" graph = graphviz.Graph(comment="The Round Table") graph.node("A", "King Arthur") graph.node("B", "Sir Bedevere the Wise") graph.edges(["AB"]) st.graphviz_chart(graph) c = self.get_delta_from_queue().new_element.graphviz_chart assert hasattr(c, "spec") def test_dot(self): """Test that it can be called with dot string.""" graph = graphviz.Graph(comment="The Round Table") graph.node("A", "King Arthur") graph.node("B", "Sir Bedevere the Wise") graph.edges(["AB"]) st.graphviz_chart(graph) c = self.get_delta_from_queue().new_element.graphviz_chart assert hasattr(c, "spec") @parameterized.expand( [ (True, "use_stretch", True), (False, "use_content", True), ] ) def test_use_container_width( self, use_container_width_value, expected_field, expected_value ): """Test that use_container_width is properly converted to width parameter.""" graph = graphviz.Graph(comment="The Round Table") graph.node("A", "King Arthur") graph.node("B", "Sir Bedevere the Wise") graph.edges(["AB"]) st.graphviz_chart(graph, use_container_width=use_container_width_value) delta = self.get_delta_from_queue() assert getattr(delta.new_element.width_config, expected_field) == expected_value def test_engines(self): """Test that it can be called with engines.""" engines = ["dot", "neato", "twopi", "circo", "fdp", "osage", "patchwork"] for engine in engines: graph = graphviz.Graph(comment="The Round Table", engine=engine) graph.node("A", "King Arthur") graph.node("B", "Sir Bedevere the gWise") graph.edges(["AB"]) st.graphviz_chart(graph) c = self.get_delta_from_queue().new_element.graphviz_chart assert hasattr(c, "engine") assert c.engine == engine def test_source(self): """Test that it can be called with graphviz.sources.Source object.""" graph = graphviz.Source( 'digraph "the holy hand grenade" { rankdir=LR; 1 -> 2 -> 3 -> lob }' ) st.graphviz_chart(graph) c = self.get_delta_from_queue().new_element.graphviz_chart assert "grenade" in c.spec @parameterized.expand( [ ("content", "use_content", True), ("stretch", "use_stretch", True), (400, "pixel_width", 400), ] ) def test_width_parameter(self, width_value, expected_field, expected_value): """Test that it can be called with different width values.""" graph = graphviz.Graph(comment="The Round Table") graph.node("A", "King Arthur") graph.node("B", "Sir Bedevere the Wise") graph.edges(["AB"]) st.graphviz_chart(graph, width=width_value) delta = self.get_delta_from_queue() assert getattr(delta.new_element.width_config, expected_field) == expected_value @parameterized.expand( [ ("content", "use_content", True), ("stretch", "use_stretch", True), (300, "pixel_height", 300), ] ) def test_height_parameter(self, height_value, expected_field, expected_value): """Test that it can be called with different height values.""" graph = graphviz.Graph(comment="The Round Table") graph.node("A", "King Arthur") graph.node("B", "Sir Bedevere the Wise") graph.edges(["AB"]) st.graphviz_chart(graph, height=height_value) delta = self.get_delta_from_queue() assert ( getattr(delta.new_element.height_config, expected_field) == expected_value ) @parameterized.expand( [ ("invalid_width",), (0,), # width must be positive (-100,), # negative width ] ) def test_graphviz_chart_width_validation_errors(self, invalid_width: str | int): """Test that invalid width values raise validation errors.""" graph = graphviz.Graph(comment="The Round Table") graph.node("A", "King Arthur") graph.node("B", "Sir Bedevere the Wise") graph.edges(["AB"]) with pytest.raises(StreamlitAPIException): st.graphviz_chart(graph, width=invalid_width) @parameterized.expand( [ ("invalid_height",), (0,), # height must be positive (-100,), # negative height ] ) def test_graphviz_chart_height_validation_errors(self, invalid_height: str | int): """Test that invalid height values raise validation errors.""" graph = graphviz.Graph(comment="The Round Table") graph.node("A", "King Arthur") graph.node("B", "Sir Bedevere the Wise") graph.edges(["AB"]) with pytest.raises(StreamlitAPIException): st.graphviz_chart(graph, height=invalid_height)
GraphvizTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 8429, "end": 8940 }
class ____(SQLAlchemyError): """A disconnect is detected on a raw DB-API connection. This error is raised and consumed internally by a connection pool. It can be raised by the :meth:`_events.PoolEvents.checkout` event so that the host pool forces a retry; the exception will be caught three times in a row before the pool gives up and raises :class:`~sqlalchemy.exc.InvalidRequestError` regarding the connection attempt. """ invalidate_pool: bool = False
DisconnectionError
python
django__django
tests/cache/tests.py
{ "start": 107654, "end": 111483 }
class ____(SimpleTestCase): """ Tests various headers w/ TemplateResponse. Most are probably redundant since they manipulate the same object anyway but the ETag header is 'special' because it relies on the content being complete (which is not necessarily always the case with a TemplateResponse) """ path = "/cache/test/" factory = RequestFactory() def tearDown(self): cache.clear() def test_patch_vary_headers(self): headers = ( # Initial vary, new headers, resulting vary. (None, ("Accept-Encoding",), "Accept-Encoding"), ("Accept-Encoding", ("accept-encoding",), "Accept-Encoding"), ("Accept-Encoding", ("ACCEPT-ENCODING",), "Accept-Encoding"), ("Cookie", ("Accept-Encoding",), "Cookie, Accept-Encoding"), ( "Cookie, Accept-Encoding", ("Accept-Encoding",), "Cookie, Accept-Encoding", ), ( "Cookie, Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), (None, ("Accept-Encoding", "COOKIE"), "Accept-Encoding, COOKIE"), ( "Cookie, Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), ( "Cookie , Accept-Encoding", ("Accept-Encoding", "cookie"), "Cookie, Accept-Encoding", ), ) for initial_vary, newheaders, resulting_vary in headers: with self.subTest(initial_vary=initial_vary, newheaders=newheaders): template = engines["django"].from_string("This is a test") response = TemplateResponse(HttpRequest(), template) if initial_vary is not None: response.headers["Vary"] = initial_vary patch_vary_headers(response, newheaders) self.assertEqual(response.headers["Vary"], resulting_vary) def test_get_cache_key(self): request = self.factory.get(self.path) template = engines["django"].from_string("This is a test") response = TemplateResponse(HttpRequest(), template) key_prefix = "localprefix" # Expect None if no headers have been set yet. self.assertIsNone(get_cache_key(request)) # Set headers to an empty list. learn_cache_key(request, response) self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e", ) # A specified key_prefix is taken into account. learn_cache_key(request, response, key_prefix=key_prefix) self.assertEqual( get_cache_key(request, key_prefix=key_prefix), "views.decorators.cache.cache_page.localprefix.GET." "58a0a05c8a5620f813686ff969c26853.d41d8cd98f00b204e9800998ecf8427e", ) def test_get_cache_key_with_query(self): request = self.factory.get(self.path, {"test": 1}) template = engines["django"].from_string("This is a test") response = TemplateResponse(HttpRequest(), template) # Expect None if no headers have been set yet. self.assertIsNone(get_cache_key(request)) # Set headers to an empty list. learn_cache_key(request, response) # The querystring is taken into account. self.assertEqual( get_cache_key(request), "views.decorators.cache.cache_page.settingsprefix.GET." "0f1c2d56633c943073c4569d9a9502fe.d41d8cd98f00b204e9800998ecf8427e", )
TestWithTemplateResponse
python
tensorflow__tensorflow
tensorflow/python/keras/engine/training_utils_v1.py
{ "start": 16739, "end": 68807 }
class ____(Aggregator): """Aggregator that concatenates outputs.""" _structure = None def create(self, batch_outs): # SparseTensorValue is a named tuple which nest will flatten, so we need # to guard it to properly handle the structure. self._structure = nest.get_traverse_shallow_structure( lambda x: not is_composite_or_composite_value(x), batch_outs) batch_outs = nest.flatten_up_to(self._structure, batch_outs) for batch_element in batch_outs: if is_composite_or_composite_value(batch_element): # If the output is not a ndarray, it will be either a composite tensor # or a composite tensor's Value object. In either case, we can't # allocate an array to hold the object - we'll handle it later. self.results.append(ConcatAggregator(self.batch_size)) elif isinstance(batch_element, np.ndarray): self.results.append( (ConcatAggregator(self.batch_size) if self.use_steps else SliceAggregator(self.num_samples, self.batch_size))) else: # This is not a ndarray, a CompositeTensor, or a CompositeTensorValue. # Fail fast rather than trying to concatenate it. raise RuntimeError('Attempted to aggregate unsupported object {}.' .format(batch_element)) self.results[-1].create(batch_element) def aggregate(self, batch_outs, batch_start=None, batch_end=None): batch_outs = nest.flatten_up_to(self._structure, batch_outs) for batch_element, result in zip(batch_outs, self.results): result.aggregate(batch_element, batch_start, batch_end) def finalize(self): for result in self.results: result.finalize() self.results = [i.results for i in self.results] self.results = nest.pack_sequence_as(self._structure, self.results) def get_progbar(model, count_mode, include_metrics=True): """Get Progbar.""" if include_metrics: stateful_metric_names = getattr(model, 'metrics_names', None) if stateful_metric_names: stateful_metric_names = stateful_metric_names[1:] # Exclude `loss` else: stateful_metric_names = None return cbks.ProgbarLogger(count_mode, stateful_metrics=stateful_metric_names) def check_num_samples(ins, batch_size=None, steps=None, steps_name='steps'): """Determine the number of samples provided for training and evaluation. The number of samples is not defined when running with `steps`, in which case the number of samples is set to `None`. Args: ins: List of tensors to be fed to the Keras function. batch_size: Integer batch size or `None` if not defined. steps: Total number of steps (batches of samples) before declaring `_predict_loop` finished. Ignored with the default value of `None`. steps_name: The public API's parameter name for `steps`. Raises: ValueError: when `steps` is `None` and the attribute `ins.shape` does not exist. Also raises ValueError when `steps` is not `None` and `batch_size` is not `None` because they are mutually exclusive. Returns: When steps is `None`, returns the number of samples to be processed based on the size of the first dimension of the first input numpy array. When steps is not `None` and `batch_size` is `None`, returns `None`. """ if steps is not None and batch_size is not None: raise ValueError('If ' + steps_name + ' is set, the `batch_size` must be None.') if check_steps_argument(ins, steps, steps_name): return None if hasattr(ins[0], 'shape'): return int(ins[0].shape[0]) return None # Edge case where ins == [static_learning_phase] def standardize_single_array(x, expected_shape=None): """Expand data of shape (x,) to (x, 1), unless len(expected_shape)==1.""" if x is None: return None if is_composite_or_composite_value(x): return x if isinstance(x, int): raise ValueError( 'Expected an array data type but received an integer: {}'.format(x)) if (x.shape is not None and len(x.shape) == 1 and (expected_shape is None or len(expected_shape) != 1)): if tensor_util.is_tf_type(x): x = array_ops.expand_dims(x, axis=1) else: x = np.expand_dims(x, 1) return x def get_composite_shape(tensor): """Returns the shape of the passed composite tensor.""" if isinstance(tensor, sparse_tensor.SparseTensorValue): # SparseTensorValues use a 'dense_shape' attribute return tensor.dense_shape else: return tensor.shape def standardize_input_data(data, names, shapes=None, check_batch_axis=True, exception_prefix=''): """Normalizes inputs and targets provided by users. Users may pass data as a list of arrays, dictionary of arrays, or as a single array. We normalize this to an ordered list of arrays (same order as `names`), while checking that the provided arrays have shapes that match the network's expectations. Args: data: User-provided input data (polymorphic). names: List of expected array names. shapes: Optional list of expected array shapes. check_batch_axis: Boolean; whether to check that the batch axis of the arrays matches the expected value found in `shapes`. exception_prefix: String prefix used for exception formatting. Returns: List of standardized input arrays (one array per model input). Raises: ValueError: in case of improperly formatted user-provided data. """ try: data_len = len(data) except TypeError: # For instance if data is `None` or a symbolic Tensor. data_len = None if not names: if data_len and not isinstance(data, dict): raise ValueError( 'Error when checking model ' + exception_prefix + ': ' 'expected no data, but got:', data) return [] if data is None: return [None for _ in range(len(names))] if isinstance(data, dict): try: data = [ data[x].values if data[x].__class__.__name__ == 'DataFrame' else data[x] for x in names ] except KeyError as e: raise ValueError('No data provided for "' + e.args[0] + '". Need data ' 'for each key in: ' + str(names)) elif isinstance(data, (list, tuple)): if isinstance(data[0], (list, tuple)): data = [numpy_compat.np_asarray(d) for d in data] elif len(names) == 1 and isinstance(data[0], (float, int)): data = [numpy_compat.np_asarray(data)] else: data = [ x.values if x.__class__.__name__ == 'DataFrame' else x for x in data ] else: data = data.values if data.__class__.__name__ == 'DataFrame' else data data = [data] if shapes is not None: data = [ standardize_single_array(x, shape) for (x, shape) in zip(data, shapes) ] else: data = [standardize_single_array(x) for x in data] if len(data) != len(names): if data and hasattr(data[0], 'shape'): raise ValueError('Error when checking model ' + exception_prefix + ': the list of Numpy arrays that you are passing to ' 'your model is not the size the model expected. ' 'Expected to see ' + str(len(names)) + ' array(s), ' + 'for inputs ' + str(names) + ' but instead got the ' 'following list of ' + str(len(data)) + ' arrays: ' + str(data)[:200] + '...') elif len(names) > 1: raise ValueError('Error when checking model ' + exception_prefix + ': you are passing a list as input to your model, ' 'but the model expects a list of ' + str(len(names)) + ' Numpy arrays instead. The list you passed was: ' + str(data)[:200]) elif len(data) == 1 and not hasattr(data[0], 'shape'): raise TypeError('Error when checking model ' + exception_prefix + ': data should be a Numpy array, or list/dict of ' 'Numpy arrays. Found: ' + str(data)[:200] + '...') elif len(names) == 1: data = [numpy_compat.np_asarray(data)] # Check shapes compatibility. if shapes: for i in range(len(names)): if shapes[i] is not None: if tensor_util.is_tf_type(data[i]): tensorshape = data[i].shape if not tensorshape: continue data_shape = tuple(tensorshape.as_list()) elif is_composite_or_composite_value(data[i]): tensorshape = get_composite_shape(data[i]) data_shape = tuple(tensorshape.as_list()) else: data_shape = data[i].shape shape = shapes[i] if len(data_shape) != len(shape): raise ValueError('Error when checking ' + exception_prefix + ': expected ' + names[i] + ' to have ' + str(len(shape)) + ' dimensions, but got array ' 'with shape ' + str(data_shape)) if not check_batch_axis: data_shape = data_shape[1:] shape = shape[1:] for dim, ref_dim in zip(data_shape, shape): if ref_dim != dim and ref_dim is not None and dim is not None: raise ValueError('Error when checking ' + exception_prefix + ': expected ' + names[i] + ' to have shape ' + str(shape) + ' but got array with shape ' + str(data_shape)) return data def standardize_sample_or_class_weights(x_weight, output_names, weight_type): """Maps `sample_weight` or `class_weight` to model outputs. Args: x_weight: User-provided `sample_weight` or `class_weight` argument. output_names: List of output names (strings) in the model. weight_type: A string used purely for exception printing. Returns: A list of `sample_weight` or `class_weight` where there are exactly one element per model output. Raises: ValueError: In case of invalid user-provided argument. """ if x_weight is None or (isinstance(x_weight, (list, tuple)) and len(x_weight) == 0): # pylint: disable=g-explicit-length-test return [None for _ in output_names] if len(output_names) == 1: if isinstance(x_weight, (list, tuple)) and len(x_weight) == 1: return x_weight if isinstance(x_weight, dict) and output_names[0] in x_weight: return [x_weight[output_names[0]]] else: return [x_weight] if isinstance(x_weight, (list, tuple)): if len(x_weight) != len(output_names): raise ValueError('Provided `' + weight_type + '` was a list of ' + str(len(x_weight)) + ' elements, but the model has ' + str(len(output_names)) + ' outputs. ' 'You should provide one `' + weight_type + '`' 'array per model output.') return x_weight if isinstance(x_weight, collections.abc.Mapping): generic_utils.check_for_unexpected_keys(weight_type, x_weight, output_names) x_weights = [] for name in output_names: x_weights.append(x_weight.get(name)) return x_weights else: raise TypeError('The model has multiple outputs, so `' + weight_type + '` ' 'should be either a list or a dict. ' 'Provided `' + weight_type + '` type not understood: ' + str(x_weight)) def standardize_class_weights(class_weight, output_names): return standardize_sample_or_class_weights(class_weight, output_names, 'class_weight') def standardize_sample_weights(sample_weight, output_names): return standardize_sample_or_class_weights(sample_weight, output_names, 'sample_weight') def check_array_lengths(inputs, targets, weights=None): """Does user input validation for numpy arrays. Args: inputs: list of Numpy arrays of inputs. targets: list of Numpy arrays of targets. weights: list of Numpy arrays of sample weights. Raises: ValueError: in case of incorrectly formatted data. """ def is_tensor_or_composite_tensor(x): return tensor_util.is_tf_type(x) or is_composite_or_composite_value(x) def set_of_lengths(x): # Returns a set with the variation between # different shapes, with None => 0 if x is None: return {} else: return set([ y.shape[0] for y in x if y is not None and not is_tensor_or_composite_tensor(y) ]) set_x = set_of_lengths(inputs) set_y = set_of_lengths(targets) set_w = set_of_lengths(weights) if len(set_x) > 1: raise ValueError('All input arrays (x) should have ' 'the same number of samples. Got array shapes: ' + str([x.shape for x in inputs])) if len(set_y) > 1: raise ValueError('All target arrays (y) should have ' 'the same number of samples. Got array shapes: ' + str([y.shape for y in targets])) if set_x and set_y and list(set_x)[0] != list(set_y)[0]: raise ValueError('Input arrays should have ' 'the same number of samples as target arrays. ' 'Found ' + str(list(set_x)[0]) + ' input samples ' 'and ' + str(list(set_y)[0]) + ' target samples.') if len(set_w) > 1: raise ValueError('All sample_weight arrays should have ' 'the same number of samples. Got array shapes: ' + str([w.shape for w in weights])) if set_y and set_w and list(set_y)[0] != list(set_w)[0]: raise ValueError('Sample_weight arrays should have ' 'the same number of samples as target arrays. Got ' + str(list(set_y)[0]) + ' input samples and ' + str(list(set_w)[0]) + ' target samples.') def check_loss_and_target_compatibility(targets, loss_fns, output_shapes): """Does validation on the compatibility of targets and loss functions. This helps prevent users from using loss functions incorrectly. This check is purely for UX purposes. Args: targets: list of Numpy arrays of targets. loss_fns: list of loss functions. output_shapes: list of shapes of model outputs. Raises: ValueError: if a loss function or target array is incompatible with an output. """ key_loss_fns = { losses.mean_squared_error, losses.binary_crossentropy, losses.categorical_crossentropy } key_loss_classes = (losses.MeanSquaredError, losses.BinaryCrossentropy, losses.CategoricalCrossentropy) for y, loss, shape in zip(targets, loss_fns, output_shapes): if y is None or loss is None or tensor_util.is_tf_type(y): continue if losses.is_categorical_crossentropy(loss): if y.shape[-1] == 1: raise ValueError('You are passing a target array of shape ' + str(y.shape) + ' while using as loss `categorical_crossentropy`. ' '`categorical_crossentropy` expects ' 'targets to be binary matrices (1s and 0s) ' 'of shape (samples, classes). ' 'If your targets are integer classes, ' 'you can convert them to the expected format via:\n' '```\n' 'from keras.utils import to_categorical\n' 'y_binary = to_categorical(y_int)\n' '```\n' '\n' 'Alternatively, you can use the loss function ' '`sparse_categorical_crossentropy` instead, ' 'which does expect integer targets.') is_loss_wrapper = isinstance(loss, losses.LossFunctionWrapper) if (isinstance(loss, key_loss_classes) or (is_loss_wrapper and (loss.fn in key_loss_fns))): for target_dim, out_dim in zip(y.shape[1:], shape[1:]): if out_dim is not None and target_dim != out_dim: loss_name = loss.name if loss_name is None: loss_type = loss.fn if is_loss_wrapper else type(loss) loss_name = loss_type.__name__ raise ValueError('A target array with shape ' + str(y.shape) + ' was passed for an output of shape ' + str(shape) + ' while using as loss `' + loss_name + '`. ' 'This loss expects targets to have the same shape ' 'as the output.') def collect_per_output_metric_info(metrics, output_names, output_shapes, loss_fns, from_serialized=False, is_weighted=False): """Maps metric names and functions to model outputs. Args: metrics: a list or a list of lists or a dict of metric functions. output_names: a list of the names (strings) of model outputs. output_shapes: a list of the shapes (strings) of model outputs. loss_fns: a list of the loss functions corresponding to the model outputs. from_serialized: whether the model the metrics are being sourced from is being initialized from a serialized format. is_weighted: Boolean indicating whether the given metrics are weighted. Returns: A list (one entry per model output) of dicts. For instance, if the model has 2 outputs, and for the first output we want to compute "binary_accuracy" and "binary_crossentropy", and just "binary_accuracy" for the second output, the list would look like: `[{ 'acc': binary_accuracy(), 'ce': binary_crossentropy(), }, { 'acc': binary_accuracy(), }]` Raises: TypeError: if an incorrect type is passed for the `metrics` argument. """ if not metrics: return [{} for _ in output_names] if isinstance(metrics, list): any_sub_list = any(isinstance(m, list) for m in metrics) if any_sub_list: if len(metrics) != len(output_names): raise ValueError('When passing a list of lists as `metrics`, ' 'it should have one entry per model output. ' 'The model has ' + str(len(output_names)) + ' outputs, but you passed metrics=' + str(metrics)) # User has provided a list of len = len(outputs). nested_metrics = [generic_utils.to_list(m) for m in metrics] else: # If it is a single list we then apply all metrics to all outputs. if len(output_names) > 1: nested_metrics = [] for _ in output_names: nested_metrics.append( [metrics_module.clone_metric(m) for m in metrics]) else: nested_metrics = [metrics] elif isinstance(metrics, collections.abc.Mapping): generic_utils.check_for_unexpected_keys('metrics', metrics, output_names) nested_metrics = [] for name in output_names: output_metrics = generic_utils.to_list(metrics.get(name, [])) nested_metrics.append(output_metrics) else: raise TypeError('Type of `metrics` argument not understood. ' 'Expected a list or dictionary, found: ' + str(metrics)) per_output_metrics = [] for i, metrics in enumerate(nested_metrics): metrics_dict = collections.OrderedDict() for metric in metrics: metric_name = get_metric_name(metric, is_weighted) metric_fn = get_metric_function( metric, output_shape=output_shapes[i], loss_fn=loss_fns[i]) metric_fn._from_serialized = from_serialized # pylint: disable=protected-access # If the metric function is not stateful, we create a stateful version. if not isinstance(metric_fn, metrics_module.Metric): metric_fn = metrics_module.MeanMetricWrapper( metric_fn, name=metric_name) # If the metric is being revived from something stateless, such as a # string (e.g. "accuracy"), we may need to later reapply transformations # such as renaming. metric_fn._from_serialized = False # pylint: disable=protected-access metrics_dict[metric_name] = metric_fn per_output_metrics.append(metrics_dict) return per_output_metrics def batch_shuffle(index_array, batch_size): """Shuffles an array in a batch-wise fashion. Useful for shuffling HDF5 arrays (where one cannot access arbitrary indices). Args: index_array: array of indices to be shuffled. batch_size: integer. Returns: The `index_array` array, shuffled in a batch-wise fashion. """ batch_count = int(len(index_array) / batch_size) # to reshape we need to be cleanly divisible by batch size # we stash extra items and reappend them after shuffling last_batch = index_array[batch_count * batch_size:] index_array = index_array[:batch_count * batch_size] index_array = index_array.reshape((batch_count, batch_size)) np.random.shuffle(index_array) index_array = index_array.flatten() return np.append(index_array, last_batch) def standardize_weights(y, sample_weight=None, class_weight=None, sample_weight_mode=None): """Performs sample weight validation and standardization. Everything gets normalized to a single sample-wise (or timestep-wise) weight array. If both `sample_weight` and `class_weight` are provided, the weights are multiplied. Args: y: Numpy array or Tensor of model targets to be weighted. sample_weight: User-provided `sample_weight` argument. class_weight: User-provided `class_weight` argument. sample_weight_mode: One of `None` or `"temporal"`. `"temporal"` indicated that we expect 2D weight data that will be applied to the last 2 dimensions of the targets (i.e. we are weighting timesteps, not samples). Returns: A numpy array of target weights, one entry per sample to weight. Raises: ValueError: In case of invalid user-provided arguments. """ # Iterator may return sample_weight as 1-tuple if isinstance(sample_weight, tuple): sample_weight = sample_weight[0] if sample_weight_mode is not None and sample_weight_mode != 'samplewise': if sample_weight_mode != 'temporal': raise ValueError('"sample_weight_mode ' 'should be None or "temporal". ' 'Found: ' + str(sample_weight_mode)) if len(y.shape) < 3: raise ValueError('Found a sample_weight array for ' 'an input with shape ' + str(y.shape) + '. ' 'Timestep-wise sample weighting (use of ' 'sample_weight_mode="temporal") is restricted to ' 'outputs that are at least 3D, i.e. that have ' 'a time dimension.') if sample_weight is not None and len(sample_weight.shape) != 2: raise ValueError('Found a sample_weight array with shape ' + str(sample_weight.shape) + '. ' 'In order to use timestep-wise sample weighting, ' 'you should pass a 2D sample_weight array.') else: if sample_weight is not None and len(sample_weight.shape) != 1: raise ValueError( 'Found a sample_weight array with shape {}. In order to ' 'use timestep-wise sample weights, you should specify ' 'sample_weight_mode="temporal" in compile(); founssd "{}" ' 'instead. If you just mean to use sample-wise weights, ' 'make sure your sample_weight array is 1D.'.format( sample_weight.shape, sample_weight_mode)) if sample_weight is not None: if len(sample_weight.shape) > len(y.shape): raise ValueError('Found a sample_weight with shape' + str(sample_weight.shape) + '.' 'Expected sample_weight with rank ' 'less than or equal to ' + str(len(y.shape))) if (not tensor_util.is_tf_type(sample_weight) and y.shape[:sample_weight.ndim] != sample_weight.shape): raise ValueError('Found a sample_weight array with shape ' + str(sample_weight.shape) + ' for an input with shape ' + str(y.shape) + '. ' 'sample_weight cannot be broadcast.') # Class weights applied per-sample. class_sample_weight = None if isinstance(class_weight, dict): if len(y.shape) > 2: raise ValueError('`class_weight` not supported for ' '3+ dimensional targets.') if tensor_util.is_tf_type(y): # Few classes are expected, so densifying is reasonable. keys = np.array(sorted(class_weight.keys())) values = np.array([class_weight[i] for i in keys]) weight_vector = np.zeros(np.max(keys) + 1) weight_vector[:] = np.nan weight_vector[keys] = values y_classes = smart_cond.smart_cond( len(y.shape.as_list()) == 2 and backend.shape(y)[1] > 1, lambda: backend.argmax(y, axis=1), lambda: math_ops.cast(backend.reshape(y, (-1,)), dtypes.int64)) class_sample_weight = array_ops.gather(weight_vector, y_classes) gen_array_ops.check_numerics( class_sample_weight, 'Invalid classes or class weights detected. NaN values indicate that ' 'an appropriate class weight could not be determined.') class_sample_weight = math_ops.cast(class_sample_weight, backend.floatx()) if sample_weight is not None: sample_weight = math_ops.cast( tensor_conversion.convert_to_tensor_v2_with_dispatch(sample_weight), backend.floatx(), ) else: y_classes = y if len(y.shape) == 2: if y.shape[1] > 1: y_classes = np.argmax(y, axis=1) elif y.shape[1] == 1: y_classes = np.reshape(y, y.shape[0]) class_sample_weight = numpy_compat.np_asarray( [class_weight[cls] for cls in y_classes if cls in class_weight]) if len(class_sample_weight) != len(y_classes): # subtract the sets to pick all missing classes existing_classes = set(y_classes) existing_class_weight = set(class_weight.keys()) raise ValueError( '`class_weight` must contain all classes in the data.' ' The classes %s exist in the data but not in ' '`class_weight`.' % (existing_classes - existing_class_weight)) if class_sample_weight is not None and sample_weight is not None: # Multiply weights if both are provided. return class_sample_weight * sample_weight if sample_weight is not None: return sample_weight if class_sample_weight is not None: return class_sample_weight return None def has_symbolic_tensors(ls): if context.executing_eagerly(): return False return has_tensors(ls) def has_tensors(ls): """Returns true if `ls` contains tensors.""" # Note: at some point in time ragged tensors didn't count as tensors, so this # returned false for ragged tensors. Making this return true fails some tests # which would then require a steps_per_epoch argument. if isinstance(ls, (list, tuple)): return any( tensor_util.is_tf_type(v) and not isinstance(v, ragged_tensor.RaggedTensor) for v in ls) if isinstance(ls, dict): return any( tensor_util.is_tf_type(v) and not isinstance(v, ragged_tensor.RaggedTensor) for _, v in ls.items()) return tensor_util.is_tf_type(ls) and not isinstance( ls, ragged_tensor.RaggedTensor) def get_metric_name(metric, weighted=False): """Returns the name corresponding to the given metric input. Args: metric: Metric function name or reference. weighted: Boolean indicating if the given metric is weighted. Returns: The metric name. """ if tf2.enabled(): # We keep the string that the user has set in compile as the metric name. if isinstance(metric, str): return metric metric = metrics_module.get(metric) return metric.name if hasattr(metric, 'name') else metric.__name__ else: metric_name_prefix = 'weighted_' if weighted else '' if metric in ('accuracy', 'acc', 'crossentropy', 'ce'): if metric in ('accuracy', 'acc'): suffix = 'acc' elif metric in ('crossentropy', 'ce'): suffix = 'ce' else: metric_fn = metrics_module.get(metric) # Get metric name as string if hasattr(metric_fn, 'name'): suffix = metric_fn.name else: suffix = metric_fn.__name__ metric_name = metric_name_prefix + suffix return metric_name def get_metric_function(metric, output_shape=None, loss_fn=None): """Returns the metric function corresponding to the given metric input. Args: metric: Metric function name or reference. output_shape: The shape of the output that this metric will be calculated for. loss_fn: The loss function used. Returns: The metric function. """ if metric not in ['accuracy', 'acc', 'crossentropy', 'ce']: return metrics_module.get(metric) is_sparse_categorical_crossentropy = ( isinstance(loss_fn, losses.SparseCategoricalCrossentropy) or (isinstance(loss_fn, losses.LossFunctionWrapper) and loss_fn.fn == losses.sparse_categorical_crossentropy)) is_binary_crossentropy = ( isinstance(loss_fn, losses.BinaryCrossentropy) or (isinstance(loss_fn, losses.LossFunctionWrapper) and loss_fn.fn == losses.binary_crossentropy)) if metric in ['accuracy', 'acc']: if output_shape[-1] == 1 or is_binary_crossentropy: return metrics_module.binary_accuracy elif is_sparse_categorical_crossentropy: return metrics_module.sparse_categorical_accuracy # If the output_shape[-1] is not 1, then we know output is `categorical`. # We assume it is sparse categorical only if loss is explicitly given # as sparse categorical crossentropy loss. return metrics_module.categorical_accuracy else: if output_shape[-1] == 1 or is_binary_crossentropy: return metrics_module.binary_crossentropy elif is_sparse_categorical_crossentropy: return metrics_module.sparse_categorical_crossentropy return metrics_module.categorical_crossentropy def call_metric_function(metric_fn, y_true, y_pred=None, weights=None, mask=None): """Invokes metric function and returns the metric result tensor.""" if mask is not None: mask = math_ops.cast(mask, y_pred.dtype) if weights is None: # Use mask as sample weight. weights = mask else: # Update dimensions of weights to match with mask. weights = math_ops.cast(weights, dtype=y_pred.dtype) mask, _, weights = losses_utils.squeeze_or_expand_dimensions( mask, sample_weight=weights) weights *= mask if y_pred is not None: return metric_fn(y_true, y_pred, sample_weight=weights) # `Mean` metric only takes a single value. return metric_fn(y_true, sample_weight=weights) def get_loss_function(loss): """Returns the loss corresponding to the loss input in `compile` API.""" if loss is None or isinstance(loss, losses.Loss): return loss if tf_inspect.isclass(loss) and issubclass(loss, losses.Loss): # It is not safe to assume that the loss takes no constructor arguments. raise ValueError( 'Received uninstantiated Loss class: {}\nPlease call loss ""classes ' 'before passing them to Model.compile.'.format(loss)) # Deserialize loss configuration, if needed. if isinstance(loss, collections.abc.Mapping): loss = losses.get(loss) # Custom callable class. if callable(loss) and not hasattr(loss, '__name__'): return loss # Wrap loss function with signature `(y_true, y_pred, **kwargs)` # in `LossFunctionWrapper` class. loss_fn = losses.get(loss) # For losses which are given as strings/functions in the compile API, # we always set the loss reduction type to be `SUM_OVER_BATCH_SIZE` # (both in distribution strategy context and otherwise). return losses.LossFunctionWrapper( loss_fn, name=loss_fn.__name__, reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE) def validate_dataset_input(x, y, sample_weight, validation_split=None): """Validates user input arguments when a dataset iterator is passed. Args: x: Input data. A `tf.data` dataset or iterator. y: Target data. It could be either Numpy array(s) or TensorFlow tensor(s). Expected to be `None` when `x` is a dataset iterator. sample_weight: An optional sample-weight array passed by the user to weight the importance of each sample in `x`. Expected to be `None` when `x` is a dataset iterator validation_split: Float between 0 and 1. Fraction of the training data to be used as validation data. Expected to be `None` when `x` is a dataset iterator. Raises: ValueError: if argument `y` or `sample_weight` or `validation_split` are provided by user. """ if y is not None: raise ValueError('You passed a dataset or dataset iterator (%s) as ' 'input `x` to your model. In that case, you should ' 'not specify a target (`y`) argument, since the dataset ' 'or dataset iterator generates both input data and ' 'target data. ' 'Received: %s' % (x, y)) if sample_weight is not None: raise ValueError('`sample_weight` argument is not supported when input ' '`x` is a dataset or a dataset iterator. Instead, you' 'can provide sample_weight as the third element of your' 'dataset, i.e. (inputs, targets, sample_weight). ' 'Received: x=%s, sample_weight=%s' % (x, sample_weight)) if validation_split is not None and validation_split != 0.0: raise ValueError( '`validation_split` argument is not supported when ' 'input `x` is a dataset or a dataset iterator. ' 'Received: x=%s, validation_split=%f' % (x, validation_split)) def validate_input_types(inp, orig_inp, allow_dict=True, field_name='inputs'): """Helper function to validate either inputs or targets.""" if isinstance(inp, (list, tuple)): if not all(isinstance(v, np.ndarray) or tensor_util.is_tf_type(v) for v in inp): raise ValueError( 'Please provide as model inputs either a single array or a list of ' 'arrays. You passed: {}={}'.format(field_name, str(orig_inp))) elif isinstance(inp, dict): if not allow_dict: raise ValueError( 'You cannot pass a dictionary as model {}.'.format(field_name)) elif not isinstance(inp, np.ndarray) and not tensor_util.is_tf_type(inp): raise ValueError( 'Please provide as model inputs either a single array or a list of ' 'arrays. You passed: {}={}'.format(field_name, orig_inp)) def check_generator_arguments(y=None, sample_weight=None, validation_split=None): """Validates arguments passed when using a generator.""" if y is not None: raise ValueError('`y` argument is not supported when data is' 'a generator or Sequence instance. Instead pass targets' ' as the second element of the generator.') if sample_weight is not None: raise ValueError('`sample_weight` argument is not supported when data is' 'a generator or Sequence instance. Instead pass sample' ' weights as the third element of the generator.') if validation_split: raise ValueError('If your data is in the form of a Python generator, ' 'you cannot use `validation_split`.') def check_steps_argument(input_data, steps, steps_name): """Validates `steps` argument based on input data's type. The cases when `steps` value must be provided are when 1. input data passed is an iterator. 2. model was built on top of symbolic tensors, input data is not required and is `None`. 3. input data passed is a symbolic tensor. Args: input_data: Input data. Can be Numpy array(s) or TensorFlow tensor(s) or tf.data.Dataset iterator or `None`. steps: Integer or `None`. Total number of steps (batches of samples) to execute. steps_name: The public API's parameter name for `steps`. Returns: boolean, True if `steps` argument is required, else False. Raises: ValueError: if `steps` argument is required for given input data type but not provided. """ is_x_iterator = isinstance( input_data, (iterator_ops.Iterator, iterator_ops.IteratorBase)) if (input_data is None or is_x_iterator or has_symbolic_tensors(input_data) or (isinstance(input_data, list) and not input_data)): if steps is None: input_type_str = 'a Dataset iterator' if is_x_iterator else 'data tensors' raise ValueError('When using {input_type} as input to a model, you should' ' specify the `{steps_name}` argument.'.format( input_type=input_type_str, steps_name=steps_name)) return True if isinstance(input_data, (data_types.DatasetV1, data_types.DatasetV2)): return True if steps is not None: list_types = (np.ndarray, list, tuple) if (isinstance(input_data, list_types) or (isinstance(input_data, dict) and any(isinstance(v, list_types) for v in input_data.values()))): logging.warning('When passing input data as arrays, do not specify ' '`steps_per_epoch`/`steps` argument. ' 'Please use `batch_size` instead.') return False def cast_single_tensor(x, dtype=None): if isinstance(x, np.ndarray): x = tensor_conversion.convert_to_tensor_v2_with_dispatch(x) dtype = dtype or backend.floatx() if x.dtype.is_floating: return math_ops.cast(x, dtype=dtype) return x def cast_if_floating_dtype_and_mismatch(targets, outputs): """Returns target data tensors using correct datatype. Checks that each target and output pair are the same datatype. If not, casts the target to the output's datatype. Args: targets: tensor or list of targets. outputs: tensor or list of outputs. Returns: Targets in appropriate datatype. """ if tensor_util.is_tf_type(targets): # There is one target, so output[0] should be the only output. return cast_single_tensor(targets, dtype=outputs[0].dtype) new_targets = [] for target, out in zip(targets, outputs): if isinstance(target, np.ndarray): target = tensor_conversion.convert_to_tensor_v2_with_dispatch(target) if target.dtype != out.dtype: new_targets.append(cast_single_tensor(target, dtype=out.dtype)) else: new_targets.append(target) return new_targets def cast_if_floating_dtype(x, dtype=None): """Casts the given data tensors to the default floating point type. Casts only if the input is already a floating point type. Args: x: tensor or list/tuple of tensors. dtype: The dtype to which Tensors should be cast. Returns: Converted input. """ return nest.map_structure(functools.partial(cast_single_tensor, dtype=dtype), x) def cast_to_model_input_dtypes(x, model): """Casts the given data tensors to the dtypes of the model inputs. Args: x: tensor or list/tuple of tensors. model: The model. Returns: Converted input. Each tensor is casted to the corresponding input in `model.inputs`. """ input_dtypes = nest.map_structure(lambda t: t.dtype, model.inputs) return nest.map_structure(math_ops.cast, x, input_dtypes) def prepare_sample_weight_modes(training_endpoints, sample_weight_mode): """Prepares sample weight modes for the model. Args: training_endpoints: List of model _TrainingEndpoints. sample_weight_mode: sample weight mode user input passed from compile API. Raises: ValueError: In case of invalid `sample_weight_mode` input. """ if isinstance(sample_weight_mode, collections.abc.Mapping): generic_utils.check_for_unexpected_keys( 'sample_weight_mode', sample_weight_mode, [e.output_name for e in training_endpoints]) for end_point in training_endpoints: if not end_point.should_skip_target_weights(): if end_point.output_name not in sample_weight_mode: raise ValueError('Output ' + end_point.output_name + 'missing from `_sample_weight_modes` dictionary') else: end_point.sample_weight_mode = sample_weight_mode.get( end_point.output_name) elif isinstance(sample_weight_mode, (list, tuple)): if len(sample_weight_mode) != len(training_endpoints): raise ValueError('When passing a list as sample_weight_mode, ' 'it should have one entry per model output. ' 'The model has ' + str(len(training_endpoints)) + ' outputs, but you passed ' + str(len(sample_weight_mode)) + '_sample_weight_modes.') for mode, endpoint in zip(sample_weight_mode, training_endpoints): if not endpoint.should_skip_target_weights(): endpoint.sample_weight_mode = mode else: for endpoint in training_endpoints: if not endpoint.should_skip_target_weights(): endpoint.sample_weight_mode = sample_weight_mode def prepare_loss_functions(loss, output_names): """Converts loss to a list of loss functions. Args: loss: String (name of objective function), objective function or `tf.losses.Loss` instance. See `tf.losses`. If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model will then be the sum of all individual losses. output_names: List of model output names. Returns: A list of loss objective functions. Raises: ValueError: If loss is a dict with keys not in model output names, or if loss is a list with len not equal to model outputs. """ if isinstance(loss, collections.abc.Mapping): generic_utils.check_for_unexpected_keys('loss', loss, output_names) loss_functions = [] for name in output_names: if name not in loss: logging.warning( 'Output {0} missing from loss dictionary. We assume ' 'this was done on purpose. The fit and evaluate APIs will not be ' 'expecting any data to be passed to {0}.'.format(name)) loss_functions.append(get_loss_function(loss.get(name, None))) elif isinstance(loss, str): loss_functions = [get_loss_function(loss) for _ in output_names] elif isinstance(loss, collections.abc.Sequence): if len(loss) != len(output_names): raise ValueError('When passing a list as loss, it should have one entry ' 'per model outputs. The model has {} outputs, but you ' 'passed loss={}'.format(len(output_names), loss)) loss_functions = nest.map_structure(get_loss_function, loss) else: loss_functions = [get_loss_function(loss) for _ in range(len(output_names))] return loss_functions def prepare_loss_weights(training_endpoints, loss_weights=None): """Converts loss weights to a list of loss weights. The result loss weights will be populated on the training endpoint. Args: training_endpoints: List of model training endpoints. loss_weights: Optional list or dictionary specifying scalar coefficients (Python floats) to weight the loss contributions of different model outputs. The loss value that will be minimized by the model will then be the *weighted sum* of all individual losses, weighted by the `loss_weights` coefficients. If a list, it is expected to have a 1:1 mapping to the model's outputs. If a dict, it is expected to map output names (strings) to scalar coefficients. Raises: ValueError: If loss weight is a dict with key not in model output names, or if loss is a list with len not equal to model outputs. """ if loss_weights is None: for e in training_endpoints: e.loss_weight = 1. elif isinstance(loss_weights, collections.abc.Mapping): generic_utils.check_for_unexpected_keys( 'loss_weights', loss_weights, [e.output_name for e in training_endpoints]) for e in training_endpoints: e.loss_weight = loss_weights.get(e.output_name, 1.) elif isinstance(loss_weights, list): if len(loss_weights) != len(training_endpoints): raise ValueError('When passing a list as loss_weights, ' 'it should have one entry per model output. ' 'The model has ' + str(len(training_endpoints)) + ' outputs, but you passed loss_weights=' + str(loss_weights)) for w, e in zip(loss_weights, training_endpoints): e.loss_weight = w else: raise TypeError('Could not interpret loss_weights argument: ' + str(loss_weights) + ' - expected a list of dicts.') # TODO(rohanj): This is a hack to get around not depending on feature_column and # create a cyclical dependency. Figure out a cleaner solution def is_feature_layer(layer): """Returns whether `layer` is a FeatureLayer or not.""" return getattr(layer, '_is_feature_layer', False) def is_eager_dataset_or_iterator(data): return context.executing_eagerly() and isinstance( data, (data_types.DatasetV1, data_types.DatasetV2, iterator_ops.IteratorBase)) # pylint: disable=protected-access def get_dataset_graph_def(dataset): if context.executing_eagerly(): graph_def_str = dataset._as_serialized_graph().numpy() else: graph_def_str = backend.get_value(dataset._as_serialized_graph()) return graph_pb2.GraphDef().FromString(graph_def_str) def verify_dataset_shuffled(x): """Verifies that the dataset is shuffled. Args: x: Dataset passed as an input to the model. Returns: boolean, whether the input dataset is shuffled or not. """ assert isinstance(x, data_types.DatasetV2) graph_def = get_dataset_graph_def(x) for node in graph_def.node: if node.op.startswith('ShuffleDataset'): return True # Also check graph_def.library.function for ds.interleave or ds.flat_map for function in graph_def.library.function: for node in function.node_def: if node.op.startswith('ShuffleDataset'): return True logging.warning('Expected a shuffled dataset but input dataset `x` is ' 'not shuffled. Please invoke `shuffle()` on input dataset.') return False def is_dataset_or_iterator(data): return isinstance(data, (data_types.DatasetV1, data_types.DatasetV2, iterator_ops.Iterator, iterator_ops.IteratorBase)) def get_iterator(dataset): """Create and initialize an iterator from a dataset.""" if context.executing_eagerly(): iterator = dataset_ops.make_one_shot_iterator(dataset) else: iterator = dataset_ops.make_initializable_iterator(dataset) initialize_iterator(iterator) return iterator def initialize_iterator(iterator): if not context.executing_eagerly(): init_op = iterator.initializer backend.get_session((init_op,)).run(init_op) def extract_tensors_from_dataset(dataset): """Extract a tuple of tensors `inputs, targets, sample_weight` from a dataset. Args: dataset: Dataset instance. Returns: Tuple of tensors `x, y, weights`. `y` and `weights` entry may be None. """ iterator = get_iterator(dataset) inputs, targets, sample_weight = unpack_iterator_input(iterator) return inputs, targets, sample_weight def unpack_iterator_input(iterator): """Convert a dataset iterator to a tuple of tensors `x, y, sample_weights`. Args: iterator: Instance of a dataset iterator. Returns: Tuple of tensors `x, y, weights`. `y` and `weights` entry may be None. """ try: next_element = iterator.get_next() except errors.OutOfRangeError: raise RuntimeError('Your dataset iterator ran out of data; ' 'Make sure that your dataset can generate ' 'required number of samples.') if isinstance(next_element, (list, tuple)): if len(next_element) not in [2, 3]: raise ValueError( 'Please provide model inputs as a list or tuple of 2 or 3 ' 'elements: (input, target) or (input, target, sample_weights) ' 'Received %s' % next_element) if len(next_element) == 2: x, y = next_element weights = None else: x, y, weights = next_element else: x = next_element y = None weights = None return x, y, weights def infer_steps_for_dataset(model, dataset, steps, epochs=1, steps_name='steps'): """Infers steps_per_epoch needed to loop through a dataset. Args: model: Keras model instance. dataset: Input data of type tf.data.Dataset. steps: Number of steps to draw from the dataset (may be None if unknown). epochs: Number of times to iterate over the dataset. steps_name: The string name of the steps argument, either `steps`, `validation_steps`, or `steps_per_epoch`. Only used for error message formatting. Returns: Integer or `None`. Inferred number of steps to loop through the dataset. `None` is returned if 1) the size of the dataset is unknown and `steps` was not specified, or 2) this is multi-worker training and auto sharding is enabled. Raises: ValueError: In case of invalid argument values. """ assert isinstance(dataset, data_types.DatasetV2) if (model._in_multi_worker_mode() and (dataset.options().experimental_distribute.auto_shard_policy != options_lib.AutoShardPolicy.OFF)): # If the dataset would be auto-sharded, we should not infer a local # steps_per_epoch due to the possible imbalanced sharding between workers. return None size = backend.get_value(cardinality.cardinality(dataset)) if size == cardinality.INFINITE and steps is None: raise ValueError('When passing an infinitely repeating dataset, you ' 'must specify the `%s` argument.' % (steps_name,)) if size >= 0: if steps is not None and steps * epochs > size: if epochs > 1: raise ValueError('The dataset you passed contains %s batches, but you ' 'passed `epochs=%s` and `%s=%s`, which is a total of ' '%s steps. We cannot draw that many steps from this ' 'dataset. We suggest to set `%s=%s`.' % (size, epochs, steps_name, steps, steps * epochs, steps_name, size // epochs)) else: raise ValueError('The dataset you passed contains %s batches, but you ' 'passed `%s=%s`. We cannot draw that many steps from ' 'this dataset. We suggest to set `%s=%s`.' % (size, steps_name, steps, steps_name, size)) if steps is None: if size >= 0: return size return None return steps
OutputsAggregator
python
scikit-learn__scikit-learn
asv_benchmarks/benchmarks/decomposition.py
{ "start": 1623, "end": 2406 }
class ____(Transformer, Estimator, Benchmark): """ Benchmarks for MiniBatchDictionaryLearning """ param_names = ["fit_algorithm", "n_jobs"] params = (["lars", "cd"], Benchmark.n_jobs_vals) def setup_cache(self): super().setup_cache() def make_data(self, params): return _olivetti_faces_dataset() def make_estimator(self, params): fit_algorithm, n_jobs = params estimator = MiniBatchDictionaryLearning( n_components=15, fit_algorithm=fit_algorithm, alpha=0.1, batch_size=3, random_state=0, n_jobs=n_jobs, ) return estimator def make_scorers(self): make_dict_learning_scorers(self)
MiniBatchDictionaryLearningBenchmark
python
dagster-io__dagster
python_modules/libraries/dagster-mlflow/dagster_mlflow/resources.py
{ "start": 1676, "end": 2352 }
class ____(type): """Mlflow Metaclass to create methods that "inherit" all of Mlflow's methods. If the class has a method defined it is excluded from the attribute setting from mlflow. """ def __new__(cls, name, bases, attrs): class_cls = super().__new__(cls, name, bases, attrs) for attr in (attr for attr in dir(mlflow) if attr not in dir(class_cls)): mlflow_attribute = getattr(mlflow, attr) if callable(mlflow_attribute): setattr(class_cls, attr, staticmethod(mlflow_attribute)) else: setattr(class_cls, attr, mlflow_attribute) return class_cls @beta
MlflowMeta
python
astropy__astropy
astropy/samp/tests/test_helpers.py
{ "start": 1188, "end": 2198 }
class ____: def __init__(self, client): self.client = client def receive_notification(self, private_key, sender_id, mtype, params, extra): write_output(mtype, private_key, sender_id, params) def receive_call(self, private_key, sender_id, msg_id, mtype, params, extra): # Here we need to make sure that we first reply, *then* write out the # file, otherwise the tests see the file and move to the next call # before waiting for the reply to be received. self.client.reply(msg_id, TEST_REPLY) self.receive_notification(private_key, sender_id, mtype, params, extra) def receive_response(self, private_key, sender_id, msg_id, response): pass def random_id(length=16): return "".join(random.sample(string.ascii_letters + string.digits, length)) def random_params(directory): return { "verification_file": os.path.join(directory, random_id()), "parameter1": "abcde", "parameter2": 1331, }
Receiver
python
tensorflow__tensorflow
tensorflow/python/data/ops/from_tensor_slices_op.py
{ "start": 1103, "end": 2409 }
class ____(dataset_ops.DatasetSource): """A `Dataset` of slices from a dataset element.""" def __init__(self, element, is_files=False, name=None): """See `Dataset.from_tensor_slices` for details.""" element = structure.normalize_element(element) batched_spec = structure.type_spec_from_value(element) self._tensors = structure.to_batched_tensor_list(batched_spec, element) if not self._tensors: raise ValueError("Invalid `element`. `element` should not be empty.") self._structure = nest.map_structure( lambda component_spec: component_spec._unbatch(), batched_spec) # pylint: disable=protected-access self._name = name batch_dim = tensor_shape.Dimension( tensor_shape.dimension_value(self._tensors[0].get_shape()[0])) for t in self._tensors[1:]: batch_dim.assert_is_compatible_with( tensor_shape.Dimension( tensor_shape.dimension_value(t.get_shape()[0]))) variant_tensor = gen_dataset_ops.tensor_slice_dataset( self._tensors, output_shapes=structure.get_flat_tensor_shapes(self._structure), is_files=is_files, metadata=self._metadata.SerializeToString()) super().__init__(variant_tensor) @property def element_spec(self): return self._structure
_TensorSliceDataset
python
getsentry__sentry
src/sentry/analytics/events/base_notification_sent.py
{ "start": 67, "end": 412 }
class ____(analytics.Event, abc.ABC): organization_id: int project_id: int | None = None category: str actor_id: int | None = None user_id: int | None = None group_id: int | None = None id: int | None = None actor_type: str | None = None notification_uuid: str alert_id: int | None = None
BaseNotificationSent
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_table07.py
{ "start": 315, "end": 914 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("table07.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with tables.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_column("C:F", 10.288) worksheet.add_table("C3:F13", {"header_row": 0}) worksheet.write("A1", "Foo") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
mlflow__mlflow
mlflow/utils/async_logging/run_artifact.py
{ "start": 93, "end": 1074 }
class ____: def __init__( self, filename: str, artifact_path: str, artifact: Union["PIL.Image.Image"], completion_event: threading.Event, ) -> None: """Initializes an instance of `RunArtifacts`. Args: filename: Filename of the artifact to be logged artifact_path: Directory within the run's artifact directory in which to log the artifact. artifact: The artifact to be logged. completion_event: A threading.Event object. """ self.filename = filename self.artifact_path = artifact_path self.artifact = artifact self.completion_event = completion_event self._exception = None @property def exception(self): """Exception raised during logging the batch.""" return self._exception @exception.setter def exception(self, exception): self._exception = exception
RunArtifact
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py
{ "start": 2339, "end": 2775 }
class ____: """Test EcsTaskInfo dataclass.""" def test_ecs_task_info_creation(self): """Test EcsTaskInfo object creation.""" cmd = ["echo", "hello"] queue = "default" config = {"key": "value"} task_info = EcsTaskInfo(cmd=cmd, queue=queue, config=config) assert task_info.cmd == cmd assert task_info.queue == queue assert task_info.config == config
TestEcsTaskInfo
python
crytic__slither
slither/tools/upgradeability/checks/variables_order.py
{ "start": 8432, "end": 9303 }
class ____(ExtraVariablesProxy): ARGUMENT = "extra-vars-v2" HELP = "Extra vars in the v2" WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#extra-variables-in-the-v2" WIKI_TITLE = "Extra variables in the v2" # region wiki_description WIKI_DESCRIPTION = """ Show new variables in the updated contract. This finding does not have an immediate security impact and is informative. """ # endregion wiki_description # region wiki_recommendation WIKI_RECOMMENDATION = """ Ensure that all the new variables are expected. """ # endregion wiki_recommendation IMPACT = CheckClassification.INFORMATIONAL REQUIRE_CONTRACT = True REQUIRE_PROXY = False REQUIRE_CONTRACT_V2 = True def _contract2(self) -> Contract: assert self.contract_v2 return self.contract_v2
ExtraVariablesNewContract
python
realpython__materials
flask-connexion-rest-part-4/models.py
{ "start": 1728, "end": 2030 }
class ____(ma.ModelSchema): """ This class exists to get around a recursion issue """ def __init__(self, **kwargs): super().__init__(strict=True, **kwargs) person_id = fields.Int() lname = fields.Str() fname = fields.Str() timestamp = fields.Str()
NotePersonSchema