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
ray-project__ray
python/ray/serve/handle.py
{ "start": 25264, "end": 29338 }
class ____(_DeploymentHandleBase): """A handle used to make requests to a deployment at runtime. This is primarily used to compose multiple deployments within a single application. It can also be used to make calls to the ingress deployment of an application (e.g., for programmatic testing). Example: .. code-block:: python import ray from ray import serve from ray.serve.handle import DeploymentHandle, DeploymentResponse @serve.deployment class Downstream: def say_hi(self, message: str): return f"Hello {message}!" self._message = message @serve.deployment class Ingress: def __init__(self, handle: DeploymentHandle): self._downstream_handle = handle async def __call__(self, name: str) -> str: response = self._downstream_handle.say_hi.remote(name) return await response app = Ingress.bind(Downstream.bind()) handle: DeploymentHandle = serve.run(app) response = handle.remote("world") assert response.result() == "Hello world!" """ def options( self, *, method_name: Union[str, DEFAULT] = DEFAULT.VALUE, multiplexed_model_id: Union[str, DEFAULT] = DEFAULT.VALUE, stream: Union[bool, DEFAULT] = DEFAULT.VALUE, use_new_handle_api: Union[bool, DEFAULT] = DEFAULT.VALUE, _prefer_local_routing: Union[bool, DEFAULT] = DEFAULT.VALUE, ) -> "DeploymentHandle": """Set options for this handle and return an updated copy of it. Example: .. code-block:: python response: DeploymentResponse = handle.options( method_name="other_method", multiplexed_model_id="model:v1", ).remote() """ if use_new_handle_api is not DEFAULT.VALUE: warnings.warn( "Setting `use_new_handle_api` no longer has any effect. " "This argument will be removed in a future version." ) if _prefer_local_routing is not DEFAULT.VALUE: warnings.warn( "Modifying `_prefer_local_routing` with `options()` is " "deprecated. Please use `init()` instead." ) return self._options( method_name=method_name, multiplexed_model_id=multiplexed_model_id, stream=stream, _prefer_local_routing=_prefer_local_routing, ) def remote( self, *args, **kwargs ) -> Union[DeploymentResponse, DeploymentResponseGenerator]: """Issue a remote call to a method of the deployment. By default, the result is a `DeploymentResponse` that can be awaited to fetch the result of the call or passed to another `.remote()` call to compose multiple deployments. If `handle.options(stream=True)` is set and a generator method is called, this returns a `DeploymentResponseGenerator` instead. Example: .. code-block:: python # Fetch the result directly. response = handle.remote() result = await response # Pass the result to another handle call. composed_response = handle2.remote(handle1.remote()) composed_result = await composed_response Args: *args: Positional arguments to be serialized and passed to the remote method call. **kwargs: Keyword arguments to be serialized and passed to the remote method call. """ future, request_metadata = self._remote(args, kwargs) if self.handle_options.stream: response_cls = DeploymentResponseGenerator else: response_cls = DeploymentResponse return response_cls( future, request_metadata, _is_router_running_in_separate_loop=self._is_router_running_in_separate_loop(), )
DeploymentHandle
python
huggingface__transformers
src/transformers/models/hiera/modeling_hiera.py
{ "start": 1436, "end": 2451 }
class ____(ModelOutput): r""" reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of shape `(batch_size, height, width, hidden_size)`. These are the reshaped and re-rolled hidden states of the model. Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to include the spatial dimensions. """ last_hidden_state: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass @auto_docstring( custom_intro=""" Hiera model's outputs that also contains a pooling of the last hidden states. """ )
HieraEncoderOutput
python
dask__distributed
distributed/http/scheduler/api.py
{ "start": 149, "end": 302 }
class ____(RequestHandler): def get(self): self.write("API V1") self.set_header("Content-Type", "text/plain; charset=utf-8")
APIHandler
python
kamyu104__LeetCode-Solutions
Python/permutations.py
{ "start": 709, "end": 1608 }
class ____(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] self.dfs(nums, [], res) return res def dfs(self, nums, path, res): if not nums: res.append(path) for i in xrange(len(nums)): # e.g., [1, 2, 3]: 3! = 6 cases # idx -> nums, path # 0 -> [2, 3], [1] -> 0: [3], [1, 2] -> [], [1, 2, 3] # -> 1: [2], [1, 3] -> [], [1, 3, 2] # # 1 -> [1, 3], [2] -> 0: [3], [2, 1] -> [], [2, 1, 3] # -> 1: [1], [2, 3] -> [], [2, 3, 1] # # 2 -> [1, 2], [3] -> 0: [2], [3, 1] -> [], [3, 1, 2] # -> 1: [1], [3, 2] -> [], [3, 2, 1] self.dfs(nums[:i] + nums[i+1:], path + [nums[i]], res)
Solution2
python
pytorch__pytorch
torch/utils/tensorboard/_pytorch_graph.py
{ "start": 852, "end": 1650 }
class ____: def __init__( self, debugName=None, inputs=None, scope=None, tensor_size=None, op_type="UnSpecified", attributes="", ) -> None: # TODO; Specify a __slots__ for this class or potentially # used namedtuple instead self.debugName = debugName self.inputs = inputs self.tensor_size = tensor_size self.kind = op_type self.attributes = attributes self.scope = scope def __repr__(self) -> str: repr = [] repr.append(str(type(self))) repr.extend( m + ": " + str(getattr(self, m)) + str(type(getattr(self, m))) for m in dir(self) if "__" not in m ) return "\n".join(repr) + "\n\n"
NodeBase
python
numba__numba
numba/pycc/platform.py
{ "start": 2157, "end": 7421 }
class ____(object): def __init__(self): if not external_compiler_works(): self._raise_external_compiler_error() self._verbose = False self._compiler = new_compiler() customize_compiler(self._compiler) self._build_ext = build_ext(Distribution()) self._build_ext.finalize_options() self._py_lib_dirs = self._build_ext.library_dirs self._py_include_dirs = self._build_ext.include_dirs np_compile_args = {'include_dirs': [np.get_include(),],} if sys.platform == 'win32': np_compile_args['libraries'] = [] else: np_compile_args['libraries'] = ['m',] self._math_info = np_compile_args @property def verbose(self): return self._verbose @verbose.setter def verbose(self, value): self._verbose = value # DEBUG will let Numpy spew many messages, so stick to INFO # to print commands executed by distutils log.set_threshold(log.INFO if value else log.WARN) def _raise_external_compiler_error(self): basemsg = ("Attempted to compile AOT function without the " "compiler used by `numpy.distutils` present.") conda_msg = "If using conda try:\n\n#> conda install %s" plt = sys.platform if plt.startswith('linux'): if sys.maxsize <= 2 ** 32: compilers = ['gcc_linux-32', 'gxx_linux-32'] else: compilers = ['gcc_linux-64', 'gxx_linux-64'] msg = "%s %s" % (basemsg, conda_msg % ' '.join(compilers)) elif plt.startswith('darwin'): compilers = ['clang_osx-64', 'clangxx_osx-64'] msg = "%s %s" % (basemsg, conda_msg % ' '.join(compilers)) elif plt.startswith('win32'): winmsg = "Cannot find suitable msvc." msg = "%s %s" % (basemsg, winmsg) else: msg = "Unknown platform %s" % plt raise RuntimeError(msg) def compile_objects(self, sources, output_dir, include_dirs=(), depends=(), macros=(), extra_cflags=None): """ Compile the given source files into a separate object file each, all beneath the *output_dir*. A list of paths to object files is returned. *macros* has the same format as in distutils: a list of 1- or 2-tuples. If a 1-tuple (name,), the given name is considered undefined by the C preprocessor. If a 2-tuple (name, value), the given name is expanded into the given value by the C preprocessor. """ objects = self._compiler.compile(sources, output_dir=output_dir, include_dirs=include_dirs, depends=depends, macros=macros or [], extra_preargs=extra_cflags) return objects def link_shared(self, output, objects, libraries=(), library_dirs=(), export_symbols=(), extra_ldflags=None): """ Create a shared library *output* linking the given *objects* and *libraries* (all strings). """ output_dir, output_filename = os.path.split(output) self._compiler.link(CCompiler.SHARED_OBJECT, objects, output_filename, output_dir, libraries, library_dirs, export_symbols=export_symbols, extra_preargs=extra_ldflags) def get_python_libraries(self): """ Get the library arguments necessary to link with Python. """ libs = self._build_ext.get_libraries(_DummyExtension()) if sys.platform == 'win32': # Under Windows, need to link explicitly against the CRT, # as the MSVC compiler would implicitly do. # (XXX msvcrtd in pydebug mode?) libs = libs + ['msvcrt'] return libs + self._math_info['libraries'] def get_python_library_dirs(self): """ Get the library directories necessary to link with Python. """ return list(self._py_lib_dirs) def get_python_include_dirs(self): """ Get the include directories necessary to compile against the Python and Numpy C APIs. """ return list(self._py_include_dirs) + self._math_info['include_dirs'] def get_ext_filename(self, ext_name): """ Given a C extension's module name, return its intended filename. """ return self._build_ext.get_ext_filename(ext_name) def _quote_arg(arg): """ Quote the argument for safe use in a shell command line. """ # If there is a quote in the string, assume relevants parts of the # string are already quoted (e.g. '-I"C:\\Program Files\\..."') if '"' not in arg and ' ' in arg: return '"%s"' % arg return arg def _is_sequence(arg): if isinstance(arg, (str, bytes)): return False try: len(arg) return True except Exception: return False
Toolchain
python
mlflow__mlflow
mlflow/system_metrics/metrics/rocm_monitor.py
{ "start": 608, "end": 4426 }
class ____(BaseMetricsMonitor): """ Class for monitoring AMD GPU stats. This is class has been modified and has been inspired by the original GPUMonitor class written by MLflow. This class uses the package pyrsmi which is an official ROCM python package which tracks and monitor AMD GPU's, has been tested on AMD MI250x 128GB GPUs For more information see: https://github.com/ROCm/pyrsmi PyPi package: https://pypi.org/project/pyrsmi/ """ def __init__(self): if "pyrsmi" not in sys.modules: # Only instantiate if `pyrsmi` is installed. raise ImportError( "`pyrsmi` is not installed, to log GPU metrics please run `pip install pyrsmi` " "to install it." ) try: rocml.smi_initialize() except RuntimeError: raise RuntimeError("Failed to initialize RSMI, skip logging GPU metrics") super().__init__() # Check if GPU is virtual. If so, collect power information from physical GPU self.physical_idx = [] for i in range(rocml.smi_get_device_count()): try: self.raise_error(rocml.smi_get_device_average_power, i) # physical GPU if no error is raised self.physical_idx.append(i) except SystemError: # virtual if error is raised # all virtual GPUs must share physical GPU with previous virtual/physical GPU assert i >= 1 self.physical_idx.append(self.physical_idx[-1]) @staticmethod def raise_error(func, *args, **kwargs): """Raise error if message containing 'error' is printed out to stdout or stderr.""" stdout = io.StringIO() stderr = io.StringIO() with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): func(*args, **kwargs) out = stdout.getvalue() err = stderr.getvalue() # Check if there is an error message in either stdout or stderr if "error" in out.lower(): raise SystemError(out) if "error" in err.lower(): raise SystemError(err) def collect_metrics(self): # Get GPU metrics. self.num_gpus = rocml.smi_get_device_count() for i in range(self.num_gpus): memory_used = rocml.smi_get_device_memory_used(i) memory_total = rocml.smi_get_device_memory_total(i) self._metrics[f"gpu_{i}_memory_usage_percentage"].append( round(memory_used / memory_total * 100, 1) ) self._metrics[f"gpu_{i}_memory_usage_gigabytes"].append(memory_used / 1e9) device_utilization = rocml.smi_get_device_utilization(i) self._metrics[f"gpu_{i}_utilization_percentage"].append(device_utilization) power_watts = rocml.smi_get_device_average_power(self.physical_idx[i]) power_capacity_watts = 500 # hard coded for now, should get this from rocm-smi self._metrics[f"gpu_{i}_power_usage_watts"].append(power_watts) self._metrics[f"gpu_{i}_power_usage_percentage"].append( (power_watts / power_capacity_watts) * 100 ) # TODO: # memory_busy (and other useful metrics) are available in pyrsmi>1.1.0. # We are currently on pyrsmi==1.0.1, so these are not available # memory_busy = rocml.smi_get_device_memory_busy(i) # self._metrics[f"gpu_{i}_memory_busy_time_percent"].append(memory_busy) def aggregate_metrics(self): return {k: round(sum(v) / len(v), 1) for k, v in self._metrics.items()} def __del__(self): if is_rocml_available: rocml.smi_shutdown()
ROCMMonitor
python
ray-project__ray
ci/ray_ci/doc/api.py
{ "start": 418, "end": 566 }
class ____(Enum): PUBLIC_API = "PublicAPI" DEVELOPER_API = "DeveloperAPI" DEPRECATED = "Deprecated" UNKNOWN = "Unknown"
AnnotationType
python
tensorflow__tensorflow
tensorflow/python/framework/ops_test.py
{ "start": 133507, "end": 134023 }
class ____(object): """Pretend user-side class for `ConvertToCompositeTensorTest .""" def __init__(self, components): super(_MyTuple, self).__init__() self._components = tuple(components) def __getitem__(self, key): return self._components[key] def __len__(self): return len(self._components) def __iter__(self): return iter(self._components) tensor_conversion_registry.register_tensor_conversion_function( _MyTuple, conversion_func=lambda x, *_, **__: _TupleTensor(x))
_MyTuple
python
realpython__materials
python-protocol/contents.py
{ "start": 30, "end": 105 }
class ____(Protocol): def create_content(self) -> str: ...
ContentCreator
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 254767, "end": 255231 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("client_mutation_id", "enterprise", "organization") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") enterprise = sgqlc.types.Field("Enterprise", graphql_name="enterprise") organization = sgqlc.types.Field("Organization", graphql_name="organization")
CreateEnterpriseOrganizationPayload
python
pyinstaller__pyinstaller
PyInstaller/lib/modulegraph/modulegraph.py
{ "start": 23780, "end": 23824 }
class ____(BaseModule): pass
BuiltinModule
python
huggingface__transformers
tests/models/glm4v/test_modeling_glm4v.py
{ "start": 6149, "end": 10606 }
class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): all_model_classes = (Glm4vModel, Glm4vForConditionalGeneration) if is_torch_available() else () model_split_percents = [0.7, 0.9] # model too big to split at 0.5 _is_composite = True def setUp(self): self.model_tester = Glm4vVisionText2TextModelTester(self) self.config_tester = ConfigTester(self, config_class=Glm4vConfig, has_text_modality=False) def test_config(self): self.config_tester.run_common_tests() # GLM4V has images shaped as (bs*patch_len, dim) so we can't slice to batches in generate def prepare_config_and_inputs_for_generate(self, batch_size=2): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() # We don't want a few model inputs in our model input dictionary for generation tests input_keys_to_ignore = [ # we don't want to mask attention heads # we don't want encoder-decoder models to start from filled decoder ids "decoder_input_ids", "decoder_attention_mask", # we'll set cache use in each test differently "use_cache", # Ignore labels if it is in the input dict "labels", # model-specific exceptions should overload/overwrite this function ] # The diff from the general `prepare_config_and_inputs_for_generate` lies here patch_size = config.vision_config.patch_size filtered_image_length = batch_size * (self.model_tester.image_size**2) // (patch_size**2) filtered_inputs_dict = { k: v[:batch_size, ...] if isinstance(v, torch.Tensor) else v for k, v in inputs_dict.items() if k not in input_keys_to_ignore } filtered_inputs_dict["pixel_values"] = inputs_dict["pixel_values"][:filtered_image_length] # It is important set `eos_token_id` to `None` to avoid early stopping (would break for length-based checks) text_gen_config = config.get_text_config(decoder=True) if text_gen_config.eos_token_id is not None and text_gen_config.pad_token_id is None: text_gen_config.pad_token_id = ( text_gen_config.eos_token_id if isinstance(text_gen_config.eos_token_id, int) else text_gen_config.eos_token_id[0] ) text_gen_config.eos_token_id = None text_gen_config.forced_eos_token_id = None return config, filtered_inputs_dict @unittest.skip(reason="No available kernels - not supported") def test_sdpa_can_dispatch_on_flash(self): pass @unittest.skip(reason="Size mismatch") def test_multi_gpu_data_parallel_forward(self): pass @unittest.skip("Error with compilation") def test_generate_from_inputs_embeds_with_static_cache(self): pass def test_inputs_embeds(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) input_ids = inputs["input_ids"] del inputs["input_ids"] del inputs["pixel_values"] del inputs["image_grid_thw"] wte = model.get_input_embeddings() inputs["inputs_embeds"] = wte(input_ids) with torch.no_grad(): model(**inputs)[0] def test_inputs_embeds_matches_input_ids(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() inputs = self._prepare_for_class(inputs_dict, model_class) input_ids = inputs["input_ids"] del inputs["input_ids"] del inputs["pixel_values"] del inputs["image_grid_thw"] inputs_embeds = model.get_input_embeddings()(input_ids) with torch.no_grad(): out_ids = model(input_ids=input_ids, **inputs)[0] out_embeds = model(inputs_embeds=inputs_embeds, **inputs)[0] torch.testing.assert_close(out_embeds, out_ids) @require_torch
Glm4vModelTest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py
{ "start": 2345, "end": 2516 }
class ____(graphene.ObjectType): invalidRunId = graphene.NonNull(graphene.String) class Meta: name = "MissingRunIdErrorEvent"
GrapheneMissingRunIdErrorEvent
python
tensorflow__tensorflow
tensorflow/python/saved_model/loader_test.py
{ "start": 2607, "end": 12460 }
class ____(test.TestCase, parameterized.TestCase): def export_simple_graph(self, builder_cls): g, sig_def_map, _ = build_graph_helper() with session.Session(graph=g) as sess: self.evaluate(variables.global_variables_initializer()) builder = builder_cls(SIMPLE_ADD_SAVED_MODEL) builder.add_meta_graph_and_variables(sess, ["foo_graph"], sig_def_map) builder.save() def export_graph_with_main_op(self, builder_cls): g, sig_def_map, y = build_graph_helper() with session.Session(graph=g) as sess: self.evaluate(variables.global_variables_initializer()) assign_op = control_flow_ops.group(state_ops.assign(y, 7)) builder = builder_cls(SAVED_MODEL_WITH_MAIN_OP) if builder_cls == saved_model_builder._SavedModelBuilder: builder.add_meta_graph_and_variables( sess, ["foo_graph"], sig_def_map, init_op=assign_op) else: builder.add_meta_graph_and_variables( sess, ["foo_graph"], sig_def_map, main_op=assign_op) builder.save() def tearDown(self): super(SavedModelLoaderTest, self).tearDown() shutil.rmtree(test.get_temp_dir(), ignore_errors=True) def test_load_function(self, builder_cls): # Force test to run in graph mode. # The SavedModelLoader.load method is a v1-only API that requires a session # to work. with ops.Graph().as_default(): self.export_simple_graph(builder_cls) loader = loader_impl.SavedModelLoader(SIMPLE_ADD_SAVED_MODEL) with self.session(graph=ops.Graph()) as sess: loader.load(sess, ["foo_graph"]) self.assertEqual(5, sess.run(_tensor_name("x"))) self.assertEqual(11, sess.run(_tensor_name("y"))) self.export_graph_with_main_op(builder_cls) loader2 = loader_impl.SavedModelLoader(SAVED_MODEL_WITH_MAIN_OP) with self.session(graph=ops.Graph()) as sess: loader2.load(sess, ["foo_graph"]) self.assertEqual(5, sess.run(_tensor_name("x"))) self.assertEqual(7, sess.run(_tensor_name("y"))) def test_load_graph(self, builder_cls): self.export_simple_graph(builder_cls) loader = loader_impl.SavedModelLoader(SIMPLE_ADD_SAVED_MODEL) graph = ops.Graph() loader.load_graph(graph, ["foo_graph"]) x = graph.get_tensor_by_name(_tensor_name("x")) y = graph.get_tensor_by_name(_tensor_name("y")) with self.assertRaises(KeyError): graph.get_tensor_by_name(_tensor_name("z")) with graph.as_default(), self.session(): # Check that x and y are not initialized with self.assertRaises(errors.FailedPreconditionError): self.evaluate(x) with self.assertRaises(errors.FailedPreconditionError): self.evaluate(y) def test_load_with_import_scope(self, builder_cls): # Force test to run in graph mode. # The SavedModelLoader.restore_variables and SavedModelLoader.run_init_ops # methods are v1-only APIs that require a session to work. with ops.Graph().as_default(): self.export_graph_with_main_op(builder_cls) loader = loader_impl.SavedModelLoader(SAVED_MODEL_WITH_MAIN_OP) with self.session(graph=ops.Graph()) as sess: saver, _ = loader.load_graph( sess.graph, ["foo_graph"], import_scope="baz") # The default saver should not work when the import scope is set. with self.assertRaises(errors.NotFoundError): loader.restore_variables(sess, tf_saver.Saver()) loader.restore_variables(sess, saver) if builder_cls == saved_model_builder._SavedModelBuilder: with self.assertRaises(errors.NotFoundError): loader.run_init_ops(sess, ["foo_graph"]) loader.run_init_ops(sess, ["foo_graph"], import_scope="baz") else: loader.run_init_ops(sess, ["foo_graph"]) self.assertEqual(5, sess.run(_tensor_name("baz/x"))) self.assertEqual(7, sess.run(_tensor_name("baz/y"))) # Test combined load function. loader = loader_impl.SavedModelLoader(SAVED_MODEL_WITH_MAIN_OP) with self.session(graph=ops.Graph()) as sess: loader.load(sess, ["foo_graph"], import_scope="baa") self.assertEqual(5, sess.run(_tensor_name("baa/x"))) self.assertEqual(7, sess.run(_tensor_name("baa/y"))) def test_restore_variables(self, builder_cls): # Force test to run in graph mode. # The SavedModelLoader.restore_variables method is a v1-only API requiring a # session to work. with ops.Graph().as_default(): self.export_graph_with_main_op(builder_cls) loader = loader_impl.SavedModelLoader(SAVED_MODEL_WITH_MAIN_OP) with self.session() as sess: x = variable_v1.VariableV1(0, name="x") y = variable_v1.VariableV1(0, name="y") z = x * y self.evaluate(variables.global_variables_initializer()) # There are variables to restore, so a saver must be created. with self.assertRaises(ValueError): loader.restore_variables(sess, None) loader.restore_variables(sess, tf_saver.Saver()) self.assertEqual(55, self.evaluate(z)) def test_run_init_op(self, builder_cls): # Force test to run in graph mode. # The SavedModelLoader.restore_variables and SavedModelLoader.run_init_ops # methods are v1-only APIs that require a session to work. with ops.Graph().as_default(): self.export_graph_with_main_op(builder_cls) loader = loader_impl.SavedModelLoader(SAVED_MODEL_WITH_MAIN_OP) graph = ops.Graph() saver, _ = loader.load_graph(graph, ["foo_graph"]) with self.session(graph=graph) as sess: loader.restore_variables(sess, saver) self.assertEqual(5, sess.run(_tensor_name("x"))) self.assertEqual(11, sess.run(_tensor_name("y"))) loader.run_init_ops(sess, ["foo_graph"]) self.assertEqual(5, sess.run(_tensor_name("x"))) self.assertEqual(7, sess.run(_tensor_name("y"))) def test_parse_saved_model(self, builder_cls): self.export_simple_graph(builder_cls) loader = loader_impl.SavedModelLoader(SIMPLE_ADD_SAVED_MODEL) meta_graph = loader.get_meta_graph_def_from_tags(["foo_graph"]) self.assertIsNotNone(meta_graph) self.assertIn("foo", meta_graph.signature_def) self.assertIn("bar", meta_graph.signature_def) def test_load_invalid_meta_graph(self, builder_cls): self.export_simple_graph(builder_cls) loader = loader_impl.SavedModelLoader(SIMPLE_ADD_SAVED_MODEL) with self.assertRaises(RuntimeError): loader.get_meta_graph_def_from_tags([]) with self.assertRaises(RuntimeError): loader.get_meta_graph_def_from_tags([""]) with self.assertRaises(RuntimeError): loader.get_meta_graph_def_from_tags(["not_a_graph"]) def test_load_saved_model_with_no_variables(self, builder_cls): """Test that SavedModel runs saver when there appear to be no variables. When no variables are detected, this may mean that the variables were saved to different collections, or the collections weren't saved to the SavedModel. If the SavedModel MetaGraphDef contains a saver, it should still run in either of these cases. Args: builder_cls: SavedModelBuilder or _SavedModelBuilder class """ # Force test to run in graph mode. # The SavedModelBuilder.add_meta_graph_and_variables and # SavedModelLoader.load methods are v1-only APIs that require a session to # work. with ops.Graph().as_default(): path = _get_export_dir("no_variable_saved_model") with session.Session(graph=ops.Graph()) as sess: x = variable_v1.VariableV1( 5, name="x", collections=["not_global_variable"]) y = variable_v1.VariableV1( 11, name="y", collections=["not_global_variable"]) self.assertFalse(variables._all_saveable_objects()) z = x + y self.evaluate(variables.variables_initializer([x, y])) foo_sig_def = signature_def_utils.build_signature_def( {"foo_input": utils.build_tensor_info(x)}, {"foo_output": utils.build_tensor_info(z)}) builder = saved_model_builder.SavedModelBuilder(path) builder.add_meta_graph_and_variables( sess, ["foo_graph"], {"foo": foo_sig_def}, saver=tf_saver.Saver([x, y])) builder.save() loader = loader_impl.SavedModelLoader(path) with self.session(graph=ops.Graph()) as sess: saver, _ = loader.load_graph(sess.graph, ["foo_graph"]) self.assertFalse(variables._all_saveable_objects()) self.assertIsNotNone(saver) with self.session(graph=ops.Graph()) as sess: loader.load(sess, ["foo_graph"]) self.assertEqual(5, sess.run(_tensor_name("x"))) self.assertEqual(11, sess.run(_tensor_name("y"))) def test_load_saved_model_graph_with_return_elements(self, builder_cls): """Ensure that the correct elements are returned.""" self.export_simple_graph(builder_cls) loader = loader_impl.SavedModelLoader(SIMPLE_ADD_SAVED_MODEL) graph = ops.Graph() _, ret = loader.load_graph(graph, ["foo_graph"], return_elements=["y:0", "x:0"]) self.assertEqual(graph.get_tensor_by_name("y:0"), ret[0]) self.assertEqual(graph.get_tensor_by_name("x:0"), ret[1]) with self.assertRaisesRegex(ValueError, "not found in graph"): loader.load_graph(graph, ["foo_graph"], return_elements=["z:0"]) def test_parse_saved_model_exception(self, builder_cls): """Test that error message for not exist model have OS-depend delimiter in path""" path = _get_export_dir("not_existing_dir") pattern = os.path.sep + "{" with self.assertRaises(IOError) as err: loader_impl.parse_saved_model(path) self.assertTrue(pattern in str(err.exception)) if __name__ == "__main__": test.main()
SavedModelLoaderTest
python
django__django
django/contrib/gis/db/models/lookups.py
{ "start": 11705, "end": 11805 }
class ____(DistanceLookupFromFunction): lookup_name = "distance_lte" op = "<="
DistanceLTELookup
python
pola-rs__polars
py-polars/src/polars/io/database/_executor.py
{ "start": 1936, "end": 23014 }
class ____: """Abstraction for querying databases with user-supplied connection objects.""" # indicate if we can/should close the cursor on scope exit. note that we # should never close the underlying connection, or a user-supplied cursor. can_close_cursor: bool = False def __init__(self, connection: ConnectionOrCursor) -> None: self.driver_name = ( "arrow_odbc_proxy" if isinstance(connection, ODBCCursorProxy) else type(connection).__module__.split(".", 1)[0].lower() ) if self.driver_name == "surrealdb": connection = SurrealDBCursorProxy(client=connection) self.cursor = self._normalise_cursor(connection) self.result: Any = None def __enter__(self) -> Self: return self def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: # if we created it and are finished with it, we can # close the cursor (but NOT the connection) if self._is_alchemy_async(self.cursor): from sqlalchemy.ext.asyncio import AsyncConnection if isinstance(self.cursor, AsyncConnection): _run_async(self._close_async_cursor()) elif self.can_close_cursor and hasattr(self.cursor, "close"): self.cursor.close() def __repr__(self) -> str: return f"<{type(self).__name__} module={self.driver_name!r}>" @staticmethod def _apply_overrides(df: DataFrame, schema_overrides: SchemaDict) -> DataFrame: """Apply schema overrides to a DataFrame.""" existing_schema = df.schema if cast_cols := [ F.col(col).cast(dtype) for col, dtype in schema_overrides.items() if col in existing_schema and dtype != existing_schema[col] ]: df = df.with_columns(cast_cols) return df async def _close_async_cursor(self) -> None: if self.can_close_cursor and hasattr(self.cursor, "close"): from sqlalchemy.ext.asyncio.exc import AsyncContextNotStarted with suppress(AsyncContextNotStarted): await self.cursor.close() @staticmethod def _check_module_version(module_name: str, minimum_version: str) -> None: """Check the module version against a minimum required version.""" mod = __import__(module_name) with suppress(AttributeError): module_version: tuple[int, ...] | None = None for version_attr in ("__version__", "version"): if isinstance(ver := getattr(mod, version_attr, None), str): module_version = parse_version(ver) break if module_version and module_version < parse_version(minimum_version): msg = f"`read_database` queries require at least {module_name} version {minimum_version}" raise ModuleUpgradeRequiredError(msg) def _fetch_arrow( self, driver_properties: ArrowDriverProperties, *, batch_size: int | None, iter_batches: bool, ) -> Iterable[pa.RecordBatch]: """Yield Arrow data as a generator of one or more RecordBatches or Tables.""" fetch_batches = driver_properties["fetch_batches"] if not iter_batches or fetch_batches is None: fetch_method = driver_properties["fetch_all"] yield getattr(self.result, fetch_method)() else: size = [batch_size] if driver_properties["exact_batch_size"] else [] repeat_batch_calls = driver_properties["repeat_batch_calls"] fetchmany_arrow = getattr(self.result, fetch_batches) if not repeat_batch_calls: yield from fetchmany_arrow(*size) else: while True: arrow = fetchmany_arrow(*size) if not arrow: break yield arrow @staticmethod def _fetchall_rows(result: Cursor, *, is_alchemy: bool) -> Iterable[Sequence[Any]]: """Fetch row data in a single call, returning the complete result set.""" rows = result.fetchall() return ( rows if rows and (is_alchemy or isinstance(rows[0], (list, tuple, dict))) else [tuple(row) for row in rows] ) def _fetchmany_rows( self, result: Cursor, *, batch_size: int | None, is_alchemy: bool ) -> Iterable[Sequence[Any]]: """Fetch row data incrementally, yielding over the complete result set.""" while True: rows = result.fetchmany(batch_size) if not rows: break elif is_alchemy or isinstance(rows[0], (list, tuple, dict)): yield rows else: yield [tuple(row) for row in rows] def _from_arrow( self, *, batch_size: int | None, iter_batches: bool, schema_overrides: SchemaDict | None, infer_schema_length: int | None, ) -> DataFrame | Iterator[DataFrame] | None: """Return resultset data in Arrow format for frame init.""" from polars import DataFrame try: # all ADBC drivers have the same method names driver = ( "adbc" if self.driver_name.startswith("adbc_") else self.driver_name ) driver_properties_list = ARROW_DRIVER_REGISTRY.get(driver, []) for i, driver_properties in enumerate(driver_properties_list, start=1): if ver := driver_properties["minimum_version"]: # for ADBC drivers, the minimum version constraint is on the driver # manager rather than the driver itself driver_to_check = ( "adbc_driver_manager" if driver == "adbc" else self.driver_name ) # if the minimum version constraint is not met, try additional # driver properties with lower constraints try: self._check_module_version(driver_to_check, ver) except ModuleUpgradeRequiredError: if i < len(driver_properties_list): continue raise if iter_batches and ( driver_properties["exact_batch_size"] and not batch_size ): msg = ( f"Cannot set `iter_batches` for {self.driver_name} " "without also setting a non-zero `batch_size`" ) raise ValueError(msg) # noqa: TRY301 frames = ( self._apply_overrides(batch, (schema_overrides or {})) if isinstance(batch, DataFrame) else from_arrow(batch, schema_overrides=schema_overrides) for batch in self._fetch_arrow( driver_properties, iter_batches=iter_batches, batch_size=batch_size, ) ) return frames if iter_batches else next(frames) # type: ignore[arg-type,return-value] except Exception as err: # eg: valid turbodbc/snowflake connection, but no arrow support # compiled in to the underlying driver (or on this connection) arrow_not_supported = ( "does not support Apache Arrow", "Apache Arrow format is not supported", ) if not any(e in str(err) for e in arrow_not_supported): raise return None def _from_rows( self, *, batch_size: int | None, iter_batches: bool, schema_overrides: SchemaDict | None, infer_schema_length: int | None, ) -> DataFrame | Iterator[DataFrame] | None: """Return resultset data row-wise for frame init.""" from polars import DataFrame if iter_batches and not batch_size: msg = ( "Cannot set `iter_batches` without also setting a non-zero `batch_size`" ) raise ValueError(msg) if is_async := isinstance(original_result := self.result, Coroutine): self.result = _run_async(self.result) try: if hasattr(self.result, "fetchall"): if is_alchemy := (self.driver_name == "sqlalchemy"): if hasattr(self.result, "cursor"): cursor_desc = [ (d[0], d[1:]) for d in self.result.cursor.description ] elif hasattr(self.result, "_metadata"): cursor_desc = [(k, None) for k in self.result._metadata.keys] else: msg = f"Unable to determine metadata from query result; {self.result!r}" raise ValueError(msg) elif hasattr(self.result, "description"): cursor_desc = [(d[0], d[1:]) for d in self.result.description] else: cursor_desc = [] schema_overrides = self._inject_type_overrides( description=cursor_desc, schema_overrides=(schema_overrides or {}), ) result_columns = [nm for nm, _ in cursor_desc] frames = ( DataFrame( data=rows, schema=result_columns or None, schema_overrides=schema_overrides, infer_schema_length=infer_schema_length, orient="row", ) for rows in ( self._fetchmany_rows( self.result, batch_size=batch_size, is_alchemy=is_alchemy, ) if iter_batches else [self._fetchall_rows(self.result, is_alchemy=is_alchemy)] # type: ignore[list-item] ) ) return frames if iter_batches else next(frames) # type: ignore[arg-type] return None finally: if is_async: original_result.close() def _inject_type_overrides( self, description: list[tuple[str, Any]], schema_overrides: SchemaDict, ) -> SchemaDict: """ Attempt basic dtype inference from a cursor description. Notes ----- This is limited; the `type_code` description attr may contain almost anything, from strings or python types to driver-specific codes, classes, enums, etc. We currently only do the additional inference from string/python type values. (Further refinement will require per-driver module knowledge and lookups). """ dupe_check = set() for nm, desc in description: if nm in dupe_check: msg = f"column {nm!r} appears more than once in the query/result cursor" raise DuplicateError(msg) elif desc is not None and nm not in schema_overrides: dtype = dtype_from_cursor_description(self.cursor, desc) if dtype is not None: schema_overrides[nm] = dtype # type: ignore[index] dupe_check.add(nm) return schema_overrides @staticmethod def _is_alchemy_async(conn: Any) -> bool: """Check if the given connection is SQLALchemy async.""" try: from sqlalchemy.ext.asyncio import ( AsyncConnection, AsyncSession, async_sessionmaker, ) return isinstance(conn, (AsyncConnection, AsyncSession, async_sessionmaker)) except ImportError: return False @staticmethod def _is_alchemy_engine(conn: Any) -> bool: """Check if the given connection is a SQLAlchemy Engine.""" from sqlalchemy.engine import Engine if isinstance(conn, Engine): return True try: from sqlalchemy.ext.asyncio import AsyncEngine return isinstance(conn, AsyncEngine) except ImportError: return False @staticmethod def _is_alchemy_object(conn: Any) -> bool: """Check if the given connection is a SQLAlchemy object (of any kind).""" return type(conn).__module__.split(".", 1)[0] == "sqlalchemy" @staticmethod def _is_alchemy_session(conn: Any) -> bool: """Check if the given connection is a SQLAlchemy Session object.""" from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Session, sessionmaker if isinstance(conn, (AsyncSession, Session, sessionmaker)): return True try: from sqlalchemy.ext.asyncio import async_sessionmaker return isinstance(conn, async_sessionmaker) except ImportError: return False @staticmethod def _is_alchemy_result(result: Any) -> bool: """Check if the given result is a SQLAlchemy Result object.""" try: from sqlalchemy.engine import CursorResult if isinstance(result, CursorResult): return True from sqlalchemy.ext.asyncio import AsyncResult return isinstance(result, AsyncResult) except ImportError: return False def _normalise_cursor(self, conn: Any) -> Cursor: """Normalise a connection object such that we have the query executor.""" if self.driver_name == "sqlalchemy": if self._is_alchemy_session(conn): return conn else: # where possible, use the raw connection to access arrow integration if conn.engine.driver == "databricks-sql-python": self.driver_name = "databricks" return conn.engine.raw_connection().cursor() elif conn.engine.driver == "duckdb_engine": self.driver_name = "duckdb" return conn elif self._is_alchemy_engine(conn): # note: if we create it, we can close it self.can_close_cursor = True return conn.connect() else: return conn elif hasattr(conn, "cursor"): # connection has a dedicated cursor; prefer over direct execute cursor = cursor() if callable(cursor := conn.cursor) else cursor self.can_close_cursor = True return cursor elif hasattr(conn, "execute"): # can execute directly (given cursor, sqlalchemy connection, etc) return conn msg = ( f"Unrecognised connection type {qualified_type_name(conn)!r}; no " "'execute' or 'cursor' method" ) raise TypeError(msg) async def _sqlalchemy_async_execute(self, query: TextClause, **options: Any) -> Any: """Execute a query using an async SQLAlchemy connection.""" is_session = self._is_alchemy_session(self.cursor) cursor = self.cursor.begin() if is_session else self.cursor # type: ignore[attr-defined] async with cursor as conn: # type: ignore[union-attr] if is_session and not hasattr(conn, "execute"): conn = conn.session result = await conn.execute(query, **options) return result def _sqlalchemy_setup( self, query: str | TextClause | Selectable, options: dict[str, Any] ) -> tuple[Any, dict[str, Any], str | TextClause | Selectable]: """Prepare a query for execution using a SQLAlchemy connection.""" from sqlalchemy.orm import Session from sqlalchemy.sql import text from sqlalchemy.sql.elements import TextClause param_key = "parameters" cursor_execute = None if ( isinstance(self.cursor, Session) and "parameters" in options and "params" not in options ): options = options.copy() options["params"] = options.pop("parameters") param_key = "params" params = options.get(param_key) is_async = self._is_alchemy_async(self.cursor) if ( not is_async and isinstance(params, Sequence) and hasattr(self.cursor, "exec_driver_sql") ): cursor_execute = self.cursor.exec_driver_sql if isinstance(query, TextClause): query = str(query) if isinstance(params, list) and not all( isinstance(p, (dict, tuple)) for p in params ): options[param_key] = tuple(params) elif isinstance(query, str): query = text(query) if cursor_execute is None: cursor_execute = ( self._sqlalchemy_async_execute if is_async else self.cursor.execute ) return cursor_execute, options, query def execute( self, query: str | TextClause | Selectable, *, options: dict[str, Any] | None = None, select_queries_only: bool = True, ) -> Self: """Execute a query and reference the result set.""" if select_queries_only and isinstance(query, str): q = re.search(r"\w{3,}", re.sub(r"/\*(.|[\r\n])*?\*/", "", query)) if (query_type := "" if not q else q.group(0)) in _INVALID_QUERY_TYPES: msg = f"{query_type} statements are not valid 'read' queries" raise UnsuitableSQLError(msg) options = options or {} if self._is_alchemy_object(self.cursor): cursor_execute, options, query = self._sqlalchemy_setup(query, options) else: cursor_execute = self.cursor.execute # note: some cursor execute methods (eg: sqlite3) only take positional # params, hence the slightly convoluted resolution of the 'options' dict try: params = signature(cursor_execute).parameters except ValueError: params = {} # type: ignore[assignment] if not options or any( p.kind in (Parameter.KEYWORD_ONLY, Parameter.POSITIONAL_OR_KEYWORD) for p in params.values() ): result = cursor_execute(query, **options) else: positional_options = ( options[o] for o in (params or options) if (not options or o in options) ) result = cursor_execute(query, *positional_options) # note: some cursors execute in-place, some access results via a property result = self.cursor if (result is None or result is True) else result if self.driver_name == "duckdb" and self._is_alchemy_result(result): result = result.cursor self.result = result return self def to_polars( self, *, iter_batches: bool = False, batch_size: int | None = None, schema_overrides: SchemaDict | None = None, infer_schema_length: int | None = N_INFER_DEFAULT, ) -> DataFrame | Iterator[DataFrame]: """ Convert the result set to a DataFrame. Wherever possible we try to return arrow-native data directly; only fall back to initialising with row-level data if no other option. """ if self.result is None: msg = "cannot return a frame before executing a query" raise RuntimeError(msg) can_close = self.can_close_cursor if defer_cursor_close := (iter_batches and can_close): self.can_close_cursor = False for frame_init in ( self._from_arrow, # init from arrow-native data (where support exists) self._from_rows, # row-wise fallback (sqlalchemy, dbapi2, pyodbc, etc) ): frame = frame_init( batch_size=batch_size, iter_batches=iter_batches, schema_overrides=schema_overrides, infer_schema_length=infer_schema_length, ) if frame is not None: if defer_cursor_close: frame = ( df for df in CloseAfterFrameIter( frame, cursor=self.result, ) ) return frame msg = ( f"Currently no support for {self.driver_name!r} connection {self.cursor!r}" ) raise NotImplementedError(msg)
ConnectionExecutor
python
huggingface__transformers
tests/models/kosmos2/test_modeling_kosmos2.py
{ "start": 9243, "end": 20164 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (Kosmos2Model, Kosmos2ForConditionalGeneration) if is_torch_available() else () additional_model_inputs = ["input_ids", "image_embeds_position_mask"] pipeline_model_mapping = ( { "feature-extraction": Kosmos2Model, "image-to-text": Kosmos2ForConditionalGeneration, "image-text-to-text": Kosmos2ForConditionalGeneration, } if is_torch_available() else {} ) test_resize_embeddings = False test_attention_outputs = False _is_composite = True # TODO: `image-to-text` pipeline for this model needs Processor. # TODO: Tiny model needs fixing for `image-text-to-text` (latent_query_num=3 not compatible with num_image_tokens=64). def is_pipeline_test_to_skip( self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, image_processor_name, feature_extractor_name, processor_name, ): return ( pipeline_test_case_name == "ImageToTextPipelineTests" or pipeline_test_case_name == "ImageTextToTextPipelineTests" ) def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): inputs_dict = copy.deepcopy(inputs_dict) if return_labels: if model_class.__name__ == "Kosmos2ForConditionalGeneration": inputs_dict["labels"] = torch.zeros( (self.model_tester.text_model_tester.batch_size, self.model_tester.text_model_tester.seq_length), dtype=torch.long, device=torch_device, ) return inputs_dict def setUp(self): self.model_tester = Kosmos2ModelTester(self) self.config_tester = ConfigTester( self, config_class=Kosmos2Config, has_text_modality=False, common_properties=["latent_query_num"] ) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_forward_signature(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) signature = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic arg_names = [*signature.parameters.keys()] expected_arg_names = ["pixel_values"] self.assertListEqual(arg_names[:1], expected_arg_names) def test_load_save_without_tied_weights(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() config.text_config.tie_word_embeddings = False for model_class in self.all_model_classes: model = model_class(config) with tempfile.TemporaryDirectory() as d: model.save_pretrained(d) model_reloaded, infos = model_class.from_pretrained(d, output_loading_info=True) # Checking the state dicts are correct reloaded_state = model_reloaded.state_dict() for k, v in model.state_dict().items(): self.assertIn(k, reloaded_state, f"Key {k} is missing from reloaded") torch.testing.assert_close( v, reloaded_state[k], msg=lambda x: f"{model_class.__name__}: Tensor {k}: {x}" ) # Checking there was no complain of missing weights self.assertEqual(infos["missing_keys"], set()) # overwrite from common in order to use `self.model_tester.text_model_tester.num_hidden_layers` def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.hidden_states expected_num_layers = getattr( self.model_tester, "expected_num_hidden_layers", self.model_tester.text_model_tester.num_hidden_layers + 1, ) self.assertEqual(len(hidden_states), expected_num_layers) seq_length = self.model_tester.text_model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:]), [seq_length, self.model_tester.text_model_tester.hidden_size], ) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True check_hidden_states_output(inputs_dict, config, model_class) @parameterized.expand(TEST_EAGER_MATCHES_SDPA_INFERENCE_PARAMETERIZATION) @unittest.skip("KOSMOS-2 doesn't support padding") def test_eager_matches_sdpa_inference( self, name, dtype, padding_side, use_attention_mask, output_attentions, enable_kernels ): pass @unittest.skip("KOSMOS-2 doesn't support padding") def test_flash_attention_2_padding_matches_padding_free_with_position_ids(self): pass @unittest.skip("KOSMOS-2 doesn't support padding") def test_flash_attention_2_padding_matches_padding_free_with_position_ids_and_fa_kwargs(self): pass @unittest.skip("KOSMOS-2 doesn't support padding") def test_eager_padding_matches_padding_free_with_position_ids(self): pass @unittest.skip("KOSMOS-2 doesn't support padding") def test_sdpa_padding_matches_padding_free_with_position_ids(self): pass @unittest.skip(reason="Kosmos2 has no separate base model without a head.") def test_model_base_model_prefix(self): pass @pytest.mark.generate def test_left_padding_compatibility(self): # Overwrite -- kosmos2 needs to prepare `image_embeds_position_mask`, and it must be padded accordingly _, inputs_dict = self.prepare_config_and_inputs_for_generate() input_ids = inputs_dict["input_ids"] def _prepare_image_embeds_position_mask(input_ids, pad_size): image_embeds_position_mask = torch.zeros( input_ids.shape[0], input_ids.shape[1] + pad_size, device=torch_device, dtype=input_ids.dtype ) image_embeds_position_mask[:, (pad_size + 1) : pad_size + 1 + self.model_tester.latent_query_num] = 1 return image_embeds_position_mask # `image_embeds_position_mask` is randomly generated in `prepare_config_and_inputs_for_generate`, and it must # match its padded version for the test to be valid -- we need to pass both unpadded_custom_inputs = {"image_embeds_position_mask": _prepare_image_embeds_position_mask(input_ids, 0)} padded_custom_inputs = {"image_embeds_position_mask": _prepare_image_embeds_position_mask(input_ids, 32)} super().test_left_padding_compatibility( unpadded_custom_inputs=unpadded_custom_inputs, padded_custom_inputs=padded_custom_inputs ) @slow def test_model_from_pretrained(self): model_name = "microsoft/kosmos-2-patch14-224" model = Kosmos2Model.from_pretrained(model_name) self.assertIsNotNone(model) @pytest.mark.generate @parameterized.expand([("greedy", 1), ("beam search", 2)]) def test_generate_from_inputs_embeds(self, _, num_beams): """Tests that we can generate from `inputs_embeds` instead of `input_ids` in LLMs, VLMs, etc""" # NOTE: overwritten because Kosmos with ids prepares position ids differently from embeds # If the model get ids, all pad tokens are masked from position ids. That is not possible with embeds # When supported, tests that the decoder model can generate from `inputs_embeds` instead of `input_ids` # if fails, you should probably update the `prepare_inputs_for_generation` function for model_class in self.all_generative_model_classes: config, inputs_dict = self.prepare_config_and_inputs_for_generate() config.is_decoder = True # Skip models without explicit support model = model_class(config).to(torch_device).eval() # Traditional way of generating text input_ids = inputs_dict.pop("input_ids") input_ids[input_ids == config.get_text_config().pad_token_id] = 0 generation_kwargs = { "return_dict_in_generate": True, "output_scores": True, "num_beams": num_beams, "do_sample": False, "max_new_tokens": 5, "min_new_tokens": 5, # generate exactly 5 tokens "use_cache": True, } outputs_from_ids = model.generate(input_ids=input_ids, **generation_kwargs, **inputs_dict) self.assertEqual(outputs_from_ids.sequences.shape[:2], (input_ids.shape[0], input_ids.shape[1] + 5)) # Same thing, but from input embeddings (`input_ids` is passed so the prompt is present in the output). # The output of the two calls should be the same. inputs_embeds = model.get_input_embeddings()(input_ids) outputs_from_embeds = model.generate( input_ids=input_ids, inputs_embeds=inputs_embeds, **generation_kwargs, **inputs_dict ) self.assertTrue(has_similar_generate_outputs(outputs_from_ids, outputs_from_embeds)) # input_ids is not a required input on most models -- if we don't pass it, the newly generated tokens will # be the same outputs_from_embeds_wo_ids = model.generate( inputs_embeds=inputs_embeds, **generation_kwargs, **inputs_dict ) outputs_from_embeds.sequences = outputs_from_embeds.sequences[:, inputs_embeds.shape[1] :] self.assertTrue(has_similar_generate_outputs(outputs_from_embeds_wo_ids, outputs_from_embeds)) # We will verify our results on an image of cute cats def prepare_img(): url = "https://huggingface.co/hf-internal-testing/Kosmos2-test-image/resolve/main/demo.jpg" im = Image.open(requests.get(url, stream=True).raw) return im @require_vision @require_torch @slow
Kosmos2ModelTest
python
apache__airflow
providers/presto/src/airflow/providers/presto/hooks/presto.py
{ "start": 2583, "end": 2893 }
class ____(Exception): """Presto exception.""" def _boolify(value): if isinstance(value, bool): return value if isinstance(value, str): if value.lower() == "false": return False if value.lower() == "true": return True return value
PrestoException
python
spyder-ide__spyder
spyder/plugins/explorer/widgets/remote_explorer.py
{ "start": 1345, "end": 1463 }
class ____: General = 'remote_general_section' Language = 'remote_language_section'
RemoteViewNewSubMenuSections
python
doocs__leetcode
solution/0600-0699/0650.2 Keys Keyboard/Solution.py
{ "start": 0, "end": 346 }
class ____: def minSteps(self, n: int) -> int: @cache def dfs(n): if n == 1: return 0 i, ans = 2, n while i * i <= n: if n % i == 0: ans = min(ans, dfs(n // i) + i) i += 1 return ans return dfs(n)
Solution
python
run-llama__llama_index
llama-index-core/llama_index/core/llama_dataset/evaluator_evaluation.py
{ "start": 5015, "end": 9620 }
class ____(BaseLlamaDataset[BaseEvaluator]): """LabelledEvalationDataset class.""" _example_type = LabelledEvaluatorDataExample def to_pandas(self) -> Any: """Create pandas dataframe.""" try: import pandas as pd except ImportError: raise ImportError( "pandas is required for this function. Please install it with `pip install pandas`." ) data: Dict[str, List] = { "query": [], "answer": [], "contexts": [], "ground_truth_answer": [], "query_by": [], "answer_by": [], "ground_truth_answer_by": [], "reference_feedback": [], "reference_score": [], "reference_evaluation_by": [], } for example in self.examples: if not isinstance(example, LabelledEvaluatorDataExample): raise ValueError( "LabelledEvaluatorDataset can only contain LabelledEvaluatorDataExample instances." ) data["query"].append(example.query) data["answer"].append(example.answer) data["contexts"].append(example.contexts) data["ground_truth_answer"].append(example.ground_truth_answer) data["query_by"].append(str(example.query_by)) data["answer_by"].append(str(example.answer_by)) data["ground_truth_answer_by"].append(str(example.ground_truth_answer_by)) data["reference_feedback"].append(example.reference_feedback) data["reference_score"].append(example.reference_score) data["reference_evaluation_by"].append(str(example.reference_evaluation_by)) return pd.DataFrame(data) async def _apredict_example( # type: ignore self, predictor: BaseEvaluator, example: LabelledEvaluatorDataExample, sleep_time_in_seconds: int, ) -> EvaluatorExamplePrediction: """Async predict RAG example with a query engine.""" await asyncio.sleep(sleep_time_in_seconds) try: eval_result: EvaluationResult = await predictor.aevaluate( query=example.query, response=example.answer, contexts=example.contexts, reference=example.ground_truth_answer, sleep_time_in_seconds=sleep_time_in_seconds, ) except Exception as err: # TODO: raise warning here as well return EvaluatorExamplePrediction( invalid_prediction=True, invalid_reason=f"Caught error {err!s}" ) if not eval_result.invalid_result: return EvaluatorExamplePrediction( feedback=eval_result.feedback or "", score=eval_result.score ) else: return EvaluatorExamplePrediction( invalid_prediction=True, invalid_reason=eval_result.invalid_reason ) def _predict_example( # type: ignore self, predictor: BaseEvaluator, example: LabelledEvaluatorDataExample, sleep_time_in_seconds: int = 0, ) -> EvaluatorExamplePrediction: """Predict RAG example with a query engine.""" time.sleep(sleep_time_in_seconds) try: eval_result: EvaluationResult = predictor.evaluate( query=example.query, response=example.answer, contexts=example.contexts, reference=example.ground_truth_answer, sleep_time_in_seconds=sleep_time_in_seconds, ) except Exception as err: # TODO: raise warning here as well return EvaluatorExamplePrediction( invalid_prediction=True, invalid_reason=f"Caught error {err!s}" ) if not eval_result.invalid_result: return EvaluatorExamplePrediction( feedback=eval_result.feedback or "", score=eval_result.score ) else: return EvaluatorExamplePrediction( invalid_prediction=True, invalid_reason=eval_result.invalid_reason ) def _construct_prediction_dataset( # type: ignore self, predictions: Sequence[EvaluatorExamplePrediction] ) -> EvaluatorPredictionDataset: """Construct prediction dataset.""" return EvaluatorPredictionDataset(predictions=predictions) @property def class_name(self) -> str: """Class name.""" return "LabelledEvaluatorDataset"
LabelledEvaluatorDataset
python
donnemartin__interactive-coding-challenges
online_judges/license_key/test_format_license_key.py
{ "start": 18, "end": 834 }
class ____(unittest.TestCase): def test_format_license_key(self): solution = Solution() self.assertRaises(TypeError, solution.format_license_key, None, None) license_key = '---' k = 3 expected = '' self.assertEqual(solution.format_license_key(license_key, k), expected) license_key = '2-4A0r7-4k' k = 3 expected = '24-A0R-74K' self.assertEqual(solution.format_license_key(license_key, k), expected) license_key = '2-4A0r7-4k' k = 4 expected = '24A0-R74K' self.assertEqual(solution.format_license_key(license_key, k), expected) print('Success: test_format_license_key') def main(): test = TestSolution() test.test_format_license_key() if __name__ == '__main__': main()
TestSolution
python
pypa__packaging
tests/test_markers.py
{ "start": 2619, "end": 4676 }
class ____: def test_matches_expected(self) -> None: environment = default_environment() iver = ( f"{sys.implementation.version.major}." f"{sys.implementation.version.minor}." f"{sys.implementation.version.micro}" ) if sys.implementation.version.releaselevel != "final": iver = ( f"{iver}{sys.implementation.version.releaselevel[0]}" f"{sys.implementation.version.serial}" ) assert environment == { "implementation_name": sys.implementation.name, "implementation_version": iver, "os_name": os.name, "platform_machine": platform.machine(), "platform_release": platform.release(), "platform_system": platform.system(), "platform_version": platform.version(), "python_full_version": platform.python_version(), "platform_python_implementation": platform.python_implementation(), "python_version": ".".join(platform.python_version_tuple()[:2]), "sys_platform": sys.platform, } def test_multidigit_minor_version(self, monkeypatch: pytest.MonkeyPatch) -> None: version_info = (3, 10, 0, "final", 0) monkeypatch.setattr(sys, "version_info", version_info, raising=False) monkeypatch.setattr(platform, "python_version", lambda: "3.10.0", raising=False) monkeypatch.setattr( platform, "python_version_tuple", lambda: ("3", "10", "0"), raising=False ) environment = default_environment() assert environment["python_version"] == "3.10" def tests_when_releaselevel_final(self) -> None: v = FakeVersionInfo(3, 4, 2, "final", 0) assert format_full_version(v) == "3.4.2" # type: ignore[arg-type] def tests_when_releaselevel_not_final(self) -> None: v = FakeVersionInfo(3, 4, 2, "beta", 4) assert format_full_version(v) == "3.4.2b4" # type: ignore[arg-type]
TestDefaultEnvironment
python
tensorflow__tensorflow
tensorflow/python/debug/cli/evaluator_test.py
{ "start": 5809, "end": 11002 }
class ____(test_util.TensorFlowTestCase): def testEvaluateSingleTensor(self): dump = test.mock.MagicMock() def fake_get_tensors(node_name, output_slot, debug_op, device_name=None): del node_name, output_slot, debug_op, device_name # Unused. return [np.array([[1.0, 2.0, 3.0]])] with test.mock.patch.object( dump, "get_tensors", side_effect=fake_get_tensors): ev = evaluator.ExpressionEvaluator(dump) self.assertEqual(3, ev.evaluate("np.size(`a:0`)")) # Whitespace in backticks should be tolerated. self.assertEqual(3, ev.evaluate("np.size(` a:0 `)")) def testEvaluateTwoTensors(self): dump = test.mock.MagicMock() def fake_get_tensors(node_name, output_slot, debug_op, device_name=None): del debug_op, device_name # Unused. if node_name == "a" and output_slot == 0: return [np.array([[1.0, -2.0], [0.0, 1.0]])] elif node_name == "b" and output_slot == 0: return [np.array([[-1.0], [1.0]])] with test.mock.patch.object( dump, "get_tensors", side_effect=fake_get_tensors): ev = evaluator.ExpressionEvaluator(dump) self.assertAllClose([[-3.0], [1.0]], ev.evaluate("np.matmul(`a:0`, `b:0`)")) self.assertAllClose( [[-4.0], [2.0]], ev.evaluate("np.matmul(`a:0`, `b:0`) + `b:0`")) def testEvaluateNoneExistentTensorGeneratesError(self): dump = test.mock.MagicMock() def fake_get_tensors(node_name, output_slot, debug_op, device_name=None): del node_name, output_slot, debug_op, device_name # Unused. raise debug_data.WatchKeyDoesNotExistInDebugDumpDirError() with test.mock.patch.object( dump, "get_tensors", side_effect=fake_get_tensors): ev = evaluator.ExpressionEvaluator(dump) with self.assertRaisesRegex( ValueError, "Eval failed due to the value of .* being unavailable"): ev.evaluate("np.matmul(`a:0`, `b:0`)") def testEvaluateWithMultipleDevicesContainingTheSameTensorName(self): dump = test.mock.MagicMock() def fake_get_tensors(node_name, output_slot, debug_op, device_name=None): del output_slot, debug_op # Unused. if node_name == "a" and device_name is None: raise ValueError( "There are multiple (2) devices with nodes named 'a' but " "device_name is not specified") elif (node_name == "a" and device_name == "/job:worker/replica:0/task:0/cpu:0"): return [np.array(10.0)] elif (node_name == "a" and device_name == "/job:worker/replica:0/task:1/cpu:0"): return [np.array(20.0)] with test.mock.patch.object( dump, "get_tensors", side_effect=fake_get_tensors): ev = evaluator.ExpressionEvaluator(dump) with self.assertRaisesRegex(ValueError, r"multiple \(2\) devices"): ev.evaluate("`a:0` + `a:0`") self.assertAllClose( 30.0, ev.evaluate("`/job:worker/replica:0/task:0/cpu:0:a:0` + " "`/job:worker/replica:0/task:1/cpu:0:a:0`")) def testEvaluateWithNonDefaultDebugOp(self): dump = test.mock.MagicMock() def fake_get_tensors(node_name, output_slot, debug_op, device_name=None): del device_name # Unused. if node_name == "a" and output_slot == 0 and debug_op == "DebugIdentity": return [np.array([[-1.0], [1.0]])] elif node_name == "a" and output_slot == 0 and debug_op == "DebugFoo": return [np.array([[-2.0, 2.0]])] with test.mock.patch.object( dump, "get_tensors", side_effect=fake_get_tensors): ev = evaluator.ExpressionEvaluator(dump) self.assertAllClose( [[4.0]], ev.evaluate("np.matmul(`a:0:DebugFoo`, `a:0:DebugIdentity`)")) def testEvaluateWithMultipleExecIndexes(self): dump = test.mock.MagicMock() def fake_get_tensors(node_name, output_slot, debug_op, device_name=None): del debug_op, device_name # Unused. if node_name == "a" and output_slot == 0: return [np.array([[-1.0], [1.0]]), np.array([[-2.0], [2.0]])] with test.mock.patch.object( dump, "get_tensors", side_effect=fake_get_tensors): ev = evaluator.ExpressionEvaluator(dump) self.assertAllClose( [[4.0]], ev.evaluate("np.matmul(`a:0[1]`.T, `a:0[0]`)")) def testEvaluateExpressionWithUnmatchedBacktick(self): dump = test.mock.MagicMock() ev = evaluator.ExpressionEvaluator(dump) with self.assertRaises(SyntaxError): ev.evaluate("np.matmul(`a:0`, `b:0`) + `b:0") def testEvaluateExpressionWithInvalidDebugTensorName(self): dump = test.mock.MagicMock() ev = evaluator.ExpressionEvaluator(dump) with self.assertRaisesRegex(ValueError, r".* tensor name .* expression .* malformed"): ev.evaluate("np.matmul(`a`, `b`)") with self.assertRaisesRegex(ValueError, r".* tensor name .* expression .* malformed"): ev.evaluate("np.matmul(`a:0:DebugIdentity:0`, `b:1:DebugNanCount:2`)") with self.assertRaises(ValueError): ev.evaluate("np.matmul(`a:0[]`, `b:0[]`)") if __name__ == "__main__": test.main()
EvaluatorTest
python
numba__llvmlite
llvmlite/ir/instructions.py
{ "start": 1994, "end": 2149 }
class ____(AttributeSet): _known = frozenset(['fast', 'nnan', 'ninf', 'nsz', 'arcp', 'contract', 'afn', 'reassoc'])
FastMathFlags
python
charliermarsh__ruff
crates/ty_python_semantic/resources/corpus/ty_extensions.py
{ "start": 294, "end": 472 }
class ____: ... def _(x: Not[A]): pass def _(x: Intersection[A], y: Intersection[A, B]): pass def _(x: TypeOf[1j]): pass def _(x: CallableTypeOf[str]): pass
B
python
apache__airflow
providers/yandex/tests/unit/yandex/secrets/test_lockbox.py
{ "start": 1278, "end": 16055 }
class ____: @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secret_value") def test_yandex_lockbox_secret_backend_get_connection(self, mock_get_value): conn_id = "fake_conn" conn_type = "scheme" host = "host" login = "user" password = "pass" port = 100 uri = f"{conn_type}://{login}:{password}@{host}:{port}" mock_get_value.return_value = uri conn = LockboxSecretBackend().get_connection(conn_id) assert conn.conn_id == conn_id assert conn.conn_type == conn_type assert conn.host == host assert conn.schema == "" assert conn.login == login assert conn.password == password assert conn.port == port assert conn.get_uri() == uri @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secret_value") def test_yandex_lockbox_secret_backend_get_connection_from_json(self, mock_get_value): conn_id = "airflow_to_yandexcloud" conn_type = "yandex_cloud" extra = '{"some": "extra values"}' c = { "conn_type": conn_type, "extra": extra, } mock_get_value.return_value = json.dumps(c) conn = LockboxSecretBackend().get_connection(conn_id) assert conn.extra == extra assert conn.conn_id == conn_id assert conn.conn_type == conn_type @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secret_value") def test_yandex_lockbox_secret_backend_get_variable(self, mock_get_value): k = "this-is-key" v = "this-is-value" mock_get_value.return_value = v value = LockboxSecretBackend().get_variable(k) assert value == v @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secret_value") def test_yandex_lockbox_secret_backend_get_config(self, mock_get_value): k = "this-is-key" v = "this-is-value" mock_get_value.return_value = v value = LockboxSecretBackend().get_config(k) assert value == v @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secret_value") def test_yandex_lockbox_secret_backend_get_connection_prefix_is_none(self, mock_get_value): uri = "scheme://user:pass@host:100" mock_get_value.return_value = uri conn = LockboxSecretBackend( connections_prefix=None, ).get_connection("fake_conn") assert conn is None @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secret_value") def test_yandex_lockbox_secret_backend_get_connection_with_oauth_token_auth(self, mock_get_value): conn_id = "yandex_cloud" uri = "scheme://user:pass@host:100" mock_get_value.return_value = uri conn = LockboxSecretBackend( yc_oauth_token="y3_Vd3eub7w9bIut67GHeL345gfb5GAnd3dZnf08FR1vjeUFve7Yi8hGvc", ).get_connection(conn_id) assert conn.conn_id == conn_id assert conn.get_uri() == uri @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secret_value") def test_yandex_lockbox_secret_backend_get_connection_conn_id_for_backend(self, mock_get_value): conn_id = "yandex_cloud" uri = "scheme://user:pass@host:100" mock_get_value.return_value = uri conn = LockboxSecretBackend( yc_connection_id=conn_id, ).get_connection(conn_id) assert conn is None @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secret_value") def test_yandex_lockbox_secret_backend_get_connection_default_conn_id(self, mock_get_value): conn_id = default_conn_name uri = "scheme://user:pass@host:100" mock_get_value.return_value = uri conn = LockboxSecretBackend().get_connection(conn_id) assert conn is None @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secret_value") def test_yandex_lockbox_secret_backend_get_variable_prefix_is_none(self, mock_get_value): k = "this-is-key" v = "this-is-value" mock_get_value.return_value = v value = LockboxSecretBackend( variables_prefix=None, ).get_variable(k) assert value is None @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secret_value") def test_yandex_lockbox_secret_backend_get_config_prefix_is_none(self, mock_get_value): k = "this-is-key" v = "this-is-value" mock_get_value.return_value = v value = LockboxSecretBackend( config_prefix=None, ).get_config(k) assert value is None def test_yandex_lockbox_secret_backend__client_created_without_exceptions(self): yc_oauth_token = "y3_Vd3eub7w9bIut67GHeL345gfb5GAnd3dZnf08FR1vjeUFve7Yi8hGvc" sm = LockboxSecretBackend( yc_oauth_token=yc_oauth_token, ) assert sm._client is not None @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_field") def test_yandex_lockbox_secret_backend__client_credentials_received_from_connection(self, mock_get_field): yc_oauth_token = "y3_Vd3eub7w9bIut67GHeL345gfb5GAnd3dZnf08FR1vjeUFve7Yi8hGvc" yc_sa_key_json = "sa_key_json" yc_sa_key_json_path = "sa_key_json_path" folder_id = "folder_id123" endpoint = "some-custom-api-endpoint.cloud.yandex.net" yc_connection_id = "connection_id" fields = { "oauth": yc_oauth_token, "service_account_json": yc_sa_key_json, "service_account_json_path": yc_sa_key_json_path, "folder_id": folder_id, "endpoint": endpoint, } mock_get_field.side_effect = lambda key: fields[key] sm = LockboxSecretBackend( yc_connection_id=yc_connection_id, ) client = sm._client assert client is not None assert sm.yc_oauth_token == yc_oauth_token assert sm.yc_sa_key_json == yc_sa_key_json assert sm.yc_sa_key_json_path == yc_sa_key_json_path assert sm.folder_id == folder_id assert sm.endpoint == endpoint assert sm.yc_connection_id == yc_connection_id def test_yandex_lockbox_secret_backend__get_endpoint(self): endpoint = "some-custom-api-endpoint.cloud.yandex.net" expected = { "endpoint": endpoint, } res = LockboxSecretBackend( endpoint=endpoint, )._get_endpoint() assert res == expected def test_yandex_lockbox_secret_backend__get_endpoint_not_specified(self): expected = {} res = LockboxSecretBackend()._get_endpoint() assert res == expected def test_yandex_lockbox_secret_backend__build_secret_name(self): prefix = "this-is-prefix" key = "this-is-key" expected = "this-is-prefix/this-is-key" res = LockboxSecretBackend()._build_secret_name(prefix, key) assert res == expected def test_yandex_lockbox_secret_backend__build_secret_name_no_prefix(self): prefix = "" key = "this-is-key" expected = "this-is-key" res = LockboxSecretBackend()._build_secret_name(prefix, key) assert res == expected def test_yandex_lockbox_secret_backend__build_secret_name_custom_sep(self): sep = "_" prefix = "this-is-prefix" key = "this-is-key" expected = "this-is-prefix_this-is-key" res = LockboxSecretBackend( sep=sep, )._build_secret_name(prefix, key) assert res == expected @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secrets") @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_payload") def test_yandex_lockbox_secret_backend__get_secret_value(self, mock_get_payload, mock_get_secrets): target_name = "target_name" target_text = "target_text" mock_get_secrets.return_value = [ secret_pb.Secret( id="123", name="one", ), secret_pb.Secret( id="456", name=target_name, ), secret_pb.Secret( id="789", name="two", ), ] mock_get_payload.return_value = payload_pb.Payload( entries=[ payload_pb.Payload.Entry(text_value=target_text), ], ) res = LockboxSecretBackend()._get_secret_value("", target_name) assert res == target_text @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secrets") @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_payload") def test_yandex_lockbox_secret_backend__get_secret_value_not_found( self, mock_get_payload, mock_get_secrets ): target_name = "target_name" target_text = "target_text" mock_get_secrets.return_value = [ secret_pb.Secret( id="123", name="one", ), secret_pb.Secret( id="789", name="two", ), ] mock_get_payload.return_value = payload_pb.Payload( entries=[ payload_pb.Payload.Entry(text_value=target_text), ], ) res = LockboxSecretBackend()._get_secret_value("", target_name) assert res is None @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secrets") @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_payload") def test_yandex_lockbox_secret_backend__get_secret_value_no_text_entries( self, mock_get_payload, mock_get_secrets ): target_name = "target_name" target_value = b"01010101" mock_get_secrets.return_value = [ secret_pb.Secret( id="123", name="one", ), secret_pb.Secret( id="456", name="two", ), secret_pb.Secret( id="789", name=target_name, ), ] mock_get_payload.return_value = payload_pb.Payload( entries=[ payload_pb.Payload.Entry(binary_value=target_value), ], ) res = LockboxSecretBackend()._get_secret_value("", target_name) assert res is None @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._client") @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._list_secrets") def test_yandex_lockbox_secret_backend__get_secrets(self, mock_list_secrets, mock_client): secrets = secret_service_pb.ListSecretsResponse( secrets=[ secret_pb.Secret( id="123", ), secret_pb.Secret( id="456", ), ], ) mock_list_secrets.return_value = secrets mock_client.return_value = None res = LockboxSecretBackend( folder_id="some-id", )._get_secrets() assert res == secrets.secrets @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._client") @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._list_secrets") def test_yandex_lockbox_secret_backend__get_secrets_page_token(self, mock_list_secrets, mock_client): first_secrets = secret_service_pb.ListSecretsResponse( secrets=[ secret_pb.Secret( id="123", ), secret_pb.Secret( id="456", ), ], next_page_token="token", ) second_secrets = secret_service_pb.ListSecretsResponse( secrets=[ secret_pb.Secret( id="789", ), secret_pb.Secret( id="000", ), ], next_page_token="", ) mock_list_secrets.side_effect = [ first_secrets, second_secrets, ] mock_client.return_value = None res = LockboxSecretBackend( folder_id="some-id", )._get_secrets() assert res == [*first_secrets.secrets, *second_secrets.secrets] @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._client") def test_yandex_lockbox_secret_backend__get_payload(self, mock_client): mock_stub = MagicMock() mock_response = payload_pb.Payload() mock_stub.Get.return_value = mock_response mock_client.return_value = mock_stub result = LockboxSecretBackend()._get_payload( secret_id="test_secret", version_id="test_version", ) mock_client.assert_called_once() mock_stub.Get.assert_called_once() assert result == mock_response @patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._client") def test_yandex_lockbox_secret_backend__list_secrets(self, mock_client): mock_stub = MagicMock() mock_response = secret_service_pb.ListSecretsResponse() mock_stub.List.return_value = mock_response mock_client.return_value = mock_stub result = LockboxSecretBackend()._list_secrets( folder_id="test_folder", ) mock_client.assert_called_once() mock_stub.List.assert_called_once() assert result == mock_response def test_yandex_lockbox_secret_backend_folder_id(self): folder_id = "id1" res = LockboxSecretBackend( folder_id=folder_id, ).folder_id assert res == folder_id @patch("airflow.models.connection.Connection.get_connection_from_secrets") def test_yandex_lockbox_secret_backend_folder_id_from_connection(self, mock_get_connection): folder_id = "id1" mock_get_connection.return_value = Mock( connection_id=default_conn_name, extra_dejson={"folder_id": folder_id}, ) sm = LockboxSecretBackend() _ = sm._client res = sm.folder_id assert res == folder_id def test_yandex_lockbox_secret_backend__get_field_connection_not_specified(self): sm = LockboxSecretBackend() sm.yc_connection_id = None res = sm._get_field("some-field") assert res is None
TestLockboxSecretBackend
python
getsentry__sentry
src/sentry/auth/authenticators/u2f.py
{ "start": 1683, "end": 9873 }
class ____(AuthenticatorInterface): type = 3 interface_id = "u2f" configure_button = _("Configure") name = _("Passkey / Biometric / Security Key") description = _( "Authenticate using a Passkey, Biometrics, or a physical security key such as a YubiKey." ) allow_multi_enrollment = True @cached_property def rp_id(self) -> str | None: # rp is a relying party for webauthn, this would be sentry.io for SAAS # and the prefix for self-hosted / dev environments return urlparse(_get_url_prefix()).hostname @cached_property def rp(self) -> PublicKeyCredentialRpEntity: return PublicKeyCredentialRpEntity(self.rp_id, "Sentry") @cached_property def webauthn_registration_server(self) -> Fido2Server: return Fido2Server(self.rp) def __init__( self, authenticator: Authenticator | None = None, status: EnrollmentStatus = EnrollmentStatus.EXISTING, ) -> None: super().__init__(authenticator, status) self.webauthn_authentication_server = U2FFido2Server( app_id=self.u2f_app_id, rp={"id": self.rp_id, "name": "Sentry"} ) @classproperty def u2f_app_id(cls) -> str: rv = options.get("u2f.app-id") return rv or absolute_uri(reverse("sentry-u2f-app-id")) @classproperty def u2f_facets(cls) -> list[str]: facets = options.get("u2f.facets") if not facets: return [_get_url_prefix()] return [x.rstrip("/") for x in facets] @classproperty def is_available(cls) -> bool: url_prefix = _get_url_prefix() return bool(url_prefix) and url_prefix.startswith("https://") def _get_kept_devices(self, key: str) -> list[dict[str, Any]]: def _key_does_not_match(device: dict[str, Any]) -> bool: if isinstance(device["binding"], AuthenticatorData): return decode_credential_id(device) != key else: return device["binding"]["keyHandle"] != key return [device for device in self.config.get("devices", ()) if _key_does_not_match(device)] def generate_new_config(self) -> dict[str, Any]: return {} def start_enrollment(self, user: User) -> tuple[cbor, Fido2Server]: credentials = self.credentials() registration_data, state = self.webauthn_registration_server.register_begin( user={ "id": user.id.to_bytes(64, byteorder="big"), "name": user.username, "displayName": user.username, }, credentials=credentials, # user_verification is where the authenticator verifies that the user is authorized # to use the authenticator, this isn't needed for our usecase so set a discouraged user_verification="discouraged", ) return cbor.encode(registration_data), state def get_u2f_devices(self) -> list[AuthenticatorData | DeviceRegistration]: rv = [] for data in self.config.get("devices", ()): # XXX: The previous version of python-u2flib-server didn't store # the `version` in the device binding. Defaulting to `U2F_V2` here # so that we don't break existing u2f registrations. if isinstance(data["binding"], AuthenticatorData): rv.append(data["binding"]) else: data["binding"].setdefault("version", "U2F_V2") rv.append(DeviceRegistration(data["binding"])) return rv def credentials(self) -> list[base.AttestedCredentialData]: credentials = [] # there are 2 types of registered keys from the registered devices, those with type # AuthenticatorData are those from WebAuthn registered devices that we don't have to modify # the other is those registered with u2f-api and it a dict with the keys keyHandle and publicKey for device in self.get_u2f_devices(): if isinstance(device, AuthenticatorData): credentials.append(device.credential_data) else: credentials.append(create_credential_object(device)) return credentials def remove_u2f_device(self, key: str) -> bool: """Removes a U2F device but never removes the last one. This returns False if the last device would be removed. """ devices = self._get_kept_devices(key) if devices: self.config["devices"] = devices return True return False def get_device_name(self, key: str) -> str | None: for device in self.config.get("devices", ()): if isinstance(device["binding"], AuthenticatorData): if decode_credential_id(device) == key: return device["name"] elif device["binding"]["keyHandle"] == key: return device["name"] return None def get_registered_devices(self) -> list[dict[str, Any]]: rv = [] for device in self.config.get("devices", ()): if isinstance(device["binding"], AuthenticatorData): rv.append( { "timestamp": to_datetime(device["ts"]), "name": device["name"], "key_handle": decode_credential_id(device), "app_id": self.rp_id, } ) else: rv.append( { "timestamp": to_datetime(device["ts"]), "name": device["name"], "key_handle": device["binding"]["keyHandle"], "app_id": device["binding"]["appId"], } ) rv.sort(key=lambda x: x["name"]) return rv def try_enroll( self, enrollment_data: str, response_data: str, device_name: str | None = None, state: dict[str, Any] | None = None, ) -> None: data = orjson.loads(response_data) client_data = ClientData(websafe_decode(data["response"]["clientDataJSON"])) att_obj = base.AttestationObject(websafe_decode(data["response"]["attestationObject"])) binding = self.webauthn_registration_server.register_complete(state, client_data, att_obj) devices = self.config.setdefault("devices", []) devices.append( {"name": device_name or "Security Key", "ts": int(time()), "binding": binding} ) def activate(self, request: HttpRequest) -> ActivationChallengeResult: credentials = self.credentials() challenge, state = self.webauthn_authentication_server.authenticate_begin( credentials=credentials ) request.session["webauthn_authentication_state"] = state return ActivationChallengeResult(challenge=cbor.encode(challenge["publicKey"])) def validate_response( self, request: HttpRequest, challenge: bytes | None, response: dict[str, Any] ) -> bool: state = request.session.get("webauthn_authentication_state") if state is None: logger.warning( "u2f_authentication.missing_session_state", extra={"user_id": getattr(request.user, "id", None)}, ) return False try: credentials = self.credentials() self.webauthn_authentication_server.authenticate_complete( state=state, credentials=credentials, credential_id=websafe_decode(response["keyHandle"]), client_data=ClientData(websafe_decode(response["clientData"])), auth_data=AuthenticatorData(websafe_decode(response["authenticatorData"])), signature=websafe_decode(response["signatureData"]), ) except (InvalidSignature, InvalidKey, StopIteration): return False finally: # Cleanup the U2F state from the session request.session.pop("webauthn_authentication_state", None) return True
U2fInterface
python
kamyu104__LeetCode-Solutions
Python/split-array-into-maximum-number-of-subarrays.py
{ "start": 38, "end": 343 }
class ____(object): def maxSubarrays(self, nums): """ :type nums: List[int] :rtype: int """ result = curr = 0 for x in nums: curr = curr&x if curr else x if not curr: result += 1 return max(result, 1)
Solution
python
getsentry__sentry
src/sentry/deletions/defaults/monitor_incident.py
{ "start": 134, "end": 506 }
class ____(ModelDeletionTask[MonitorIncident]): def get_child_relations(self, instance: MonitorIncident) -> list[BaseRelation]: from sentry.monitors import models return [ ModelRelation( models.MonitorEnvBrokenDetection, {"monitor_incident_id": instance.id}, ), ]
MonitorIncidentDeletionTask
python
openai__openai-python
src/openai/types/responses/tool_choice_function.py
{ "start": 195, "end": 384 }
class ____(BaseModel): name: str """The name of the function to call.""" type: Literal["function"] """For function calling, the type is always `function`."""
ToolChoiceFunction
python
walkccc__LeetCode
solutions/96. Unique Binary Search Trees/96.py
{ "start": 0, "end": 263 }
class ____: def numTrees(self, n: int) -> int: # dp[i] := the number of unique BST's that store values 1..i dp = [1, 1] + [0] * (n - 1) for i in range(2, n + 1): for j in range(i): dp[i] += dp[j] * dp[i - j - 1] return dp[n]
Solution
python
getsentry__sentry
src/sentry/issues/auto_source_code_config/frame_info.py
{ "start": 1048, "end": 1725 }
class ____(ABC): raw_path: str normalized_path: str stack_root: str def __init__(self, frame: Mapping[str, Any]) -> None: self.process_frame(frame) def __repr__(self) -> str: return f"FrameInfo: {self.raw_path} stack_root: {self.stack_root}" def __eq__(self, other: object) -> bool: if not isinstance(other, FrameInfo): return False return self.raw_path == other.raw_path @abstractmethod def process_frame(self, frame: Mapping[str, Any]) -> None: """Process the frame and set the necessary attributes.""" raise NotImplementedError("Subclasses must implement process_frame")
FrameInfo
python
arrow-py__arrow
tests/test_parser.py
{ "start": 61283, "end": 61837 }
class ____: # Regression test for issue #860 def test_no_match_group(self): fmt_str = str(b"[|\x1f\xb9\x03\x00\x00\x00\x00:-yI:][\x01yI:yI:I") payload = str(b"") with pytest.raises(parser.ParserMatchError): self.parser.parse(payload, fmt_str) # Regression test for issue #854 def test_regex_module_error(self): fmt_str = str(b"struct n[X+,N-M)MMXdMM]<") payload = str(b"") with pytest.raises(parser.ParserMatchError): self.parser.parse(payload, fmt_str)
TestFuzzInput
python
dagster-io__dagster
examples/with_wandb/with_wandb/assets/example/fashion_data.py
{ "start": 122, "end": 6462 }
class ____(data.Dataset): """`MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset. Args: root (string): Root directory of dataset where ``processed/training.pt`` and ``processed/test.pt`` exist. train (bool, optional): If True, creates dataset from ``training.pt``, otherwise from ``test.pt``. download (bool, optional): If true, downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, it is not downloaded again. transform (callable, optional): A function/transform that takes in an PIL image and returns a transformed version. E.g, ``transforms.RandomCrop`` target_transform (callable, optional): A function/transform that takes in the target and transforms it. """ urls = [ "http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz", "http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz", "http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz", "http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz", ] raw_folder = "raw" processed_folder = "processed" training_file = "training.pt" test_file = "test.pt" def __init__(self, root, train=True, transform=None, target_transform=None, download=False): self.root = os.path.expanduser(root) self.transform = transform self.target_transform = target_transform self.train = train # training set or test set if download: self.download() if not self._check_exists(): raise RuntimeError("Dataset not found." + " You can use download=True to download it") if self.train: self.train_data, self.train_labels = torch.load( os.path.join(root, self.processed_folder, self.training_file) ) else: self.test_data, self.test_labels = torch.load( os.path.join(root, self.processed_folder, self.test_file) ) def __getitem__(self, index): """Args: index (int): Index Returns: tuple: (image, target) where target is index of the target class. """ if self.train: img, target = self.train_data[index], self.train_labels[index] else: img, target = self.test_data[index], self.test_labels[index] # doing this so that it is consistent with all other datasets # to return a PIL Image img = Image.fromarray(img.numpy(), mode="L") if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) return img, target def __len__(self): if self.train: return len(self.train_data) else: return len(self.test_data) def _check_exists(self): return os.path.exists( os.path.join(self.root, self.processed_folder, self.training_file) ) and os.path.exists(os.path.join(self.root, self.processed_folder, self.test_file)) def download(self): """Download the MNIST data if it doesn't exist in processed_folder already.""" import gzip from six.moves import urllib if self._check_exists(): return # download files try: os.makedirs(os.path.join(self.root, self.raw_folder)) os.makedirs(os.path.join(self.root, self.processed_folder)) except OSError as e: if e.errno == errno.EEXIST: pass else: raise for url in self.urls: print("Downloading " + url) # noqa: T201 data = urllib.request.urlopen(url) filename = url.rpartition("/")[2] file_path = os.path.join(self.root, self.raw_folder, filename) with open(file_path, "wb") as f: f.write(data.read()) with ( open(file_path.replace(".gz", ""), "wb") as out_f, gzip.GzipFile(file_path) as zip_f, ): out_f.write(zip_f.read()) os.unlink(file_path) # process and save as torch files print("Processing...") # noqa: T201 training_set = ( read_image_file(os.path.join(self.root, self.raw_folder, "train-images-idx3-ubyte")), read_label_file(os.path.join(self.root, self.raw_folder, "train-labels-idx1-ubyte")), ) test_set = ( read_image_file(os.path.join(self.root, self.raw_folder, "t10k-images-idx3-ubyte")), read_label_file(os.path.join(self.root, self.raw_folder, "t10k-labels-idx1-ubyte")), ) with open(os.path.join(self.root, self.processed_folder, self.training_file), "wb") as f: torch.save(training_set, f) with open(os.path.join(self.root, self.processed_folder, self.test_file), "wb") as f: torch.save(test_set, f) print("Done!") # noqa: T201 def get_int(b): return int(codecs.encode(b, "hex"), 16) def parse_byte(b): if isinstance(b, str): return ord(b) return b def read_label_file(path): with open(path, "rb") as f: data = f.read() assert get_int(data[:4]) == 2049 length = get_int(data[4:8]) labels = [parse_byte(b) for b in data[8:]] assert len(labels) == length return torch.LongTensor(labels) def read_image_file(path): with open(path, "rb") as f: data = f.read() assert get_int(data[:4]) == 2051 length = get_int(data[4:8]) num_rows = get_int(data[8:12]) num_cols = get_int(data[12:16]) images = [] idx = 16 for _ in range(length): img = [] images.append(img) for r in range(num_rows): row = [] img.append(row) for _ in range(num_cols): row.append(parse_byte(data[idx])) idx += 1 assert len(images) == length return torch.ByteTensor(images).view(-1, 28, 28)
fashion
python
google__jax
tests/pallas/export_back_compat_pallas_test.py
{ "start": 1692, "end": 5474 }
class ____(bctu.CompatTestBase): def setUp(self): if jax.config.x64_enabled: self.skipTest("Only works in 32-bit") super().setUp() @unittest.skip("This test is checking backwards compatibility " "of Triton IR, but Triton doesn't promise backwards " "compatibility for its IR, and we have since removed " "the corresponding custom call from the guaranteed stable list.") def test_triton_add_one(self): if not jtu.is_cuda_compute_capability_at_least("8.0"): self.skipTest("Only works on GPUs with capability >= sm80") def func(x): def add_one(x_ref, o_ref): o_ref[0] = x_ref[0] + 1 return pl.pallas_call(add_one, out_shape=jax.ShapeDtypeStruct((8,), jnp.float32), in_specs=[pl.BlockSpec((1,), lambda i: i)], out_specs=pl.BlockSpec((1,), lambda i: i), grid=8)(x) data = self.load_testdata(triton_add_one.data_2024_05_02) self.run_one_test(func, data) def test_mosaic_gpu_add_one(self): if not jtu.is_cuda_compute_capability_at_least("9.0"): self.skipTest("Only works on GPUs with capability >= sm90") @functools.partial( pl.pallas_call, out_shape=jax.ShapeDtypeStruct((128 * 2,), jnp.float32), grid=2, backend="mosaic_gpu", ) def add_one(x_ref, o_ref): o_ref[...] = x_ref[...] + 1 data = self.load_testdata(mosaic_gpu_add_one.data_2025_11_27) self.run_one_test(add_one, data) def test_mosaic_gpu_kernel_add_one(self): if not jtu.is_cuda_compute_capability_at_least("9.0"): self.skipTest("Only works on GPUs with capability >= sm90") @functools.partial( plgpu.kernel, out_shape=jax.ShapeDtypeStruct((128,), jnp.float32), grid=(2,), grid_names=("x",), ) def add_one(x_ref, o_ref): o_ref[...] = x_ref[...] + 1 data = self.load_testdata(mosaic_gpu_add_one.kernel_data_2025_09_07) self.run_one_test(add_one, data) @jax.default_matmul_precision("bfloat16") def test_mosaic_matmul(self): dtype = jnp.float32 def func(): # Build the inputs here, to reduce the size of the golden inputs. x_shape = (1024, 512) bias = 1.0 scale = 1e-3 x = bias + scale * jnp.arange( math.prod(x_shape), dtype=dtype).reshape(x_shape) y = x[:512, :256] res = matmul.matmul(x, y, block_shape=(256, 256)) # Keep only slices of the output, to reduce the size of the goldens. return res[::16, ::16] data = self.load_testdata(mosaic_matmul.data_2024_09_24) self.run_one_test(func, data, rtol=2e-7) def test_mosaic_semaphore_dma(self): if not (jtu.test_device_matches(["tpu"]) and jtu.is_device_tpu_at_least(4)): # TODO: crashes during compilation on TPU v4 self.skipTest("Only works on TPU v5+") # The signatures of TPU ops for semaphore and DMA have changed. # This test ensures that the new signatures are backwards compatible. def func(): def dma_kernel(x, y): def body(dma_sem, sem): pltpu.async_copy(x, y, dma_sem).wait() pltpu.semaphore_signal(sem) pltpu.semaphore_wait(sem) pl.run_scoped( body, pltpu.SemaphoreType.DMA, pltpu.SemaphoreType.REGULAR ) x = jnp.arange(128 * 128, dtype=jnp.float32).reshape(128, 128) y = pl.pallas_call(dma_kernel, out_shape=x)(x) return jnp.array_equal(x, y).astype(jnp.float32) data = self.load_testdata( mosaic_semaphore_dma.semaphore_and_dma_2024_04_22) self.run_one_test(func, data) if __name__ == "__main__": absltest.main(testLoader=jtu.JaxTestLoader())
CompatTest
python
kamyu104__LeetCode-Solutions
Python/next-greater-element-iii.py
{ "start": 50, "end": 716 }
class ____(object): def nextGreaterElement(self, n): """ :type n: int :rtype: int """ digits = map(int, list(str(n))) k, l = -1, 0 for i in xrange(len(digits) - 1): if digits[i] < digits[i + 1]: k = i if k == -1: digits.reverse() return -1 for i in xrange(k + 1, len(digits)): if digits[i] > digits[k]: l = i digits[k], digits[l] = digits[l], digits[k] digits[k + 1:] = digits[:k:-1] result = int("".join(map(str, digits))) return -1 if result >= 0x7FFFFFFF else result
Solution
python
Textualize__textual
src/textual/widgets/_option_list.py
{ "start": 1035, "end": 1155 }
class ____(OptionListError): """Raised if a duplicate ID is used when adding options to an option list."""
DuplicateID
python
huggingface__transformers
src/transformers/models/yolos/modeling_yolos.py
{ "start": 15732, "end": 16970 }
class ____(GradientCheckpointingLayer): """This corresponds to the Block class in the timm implementation.""" def __init__(self, config: YolosConfig): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = YolosAttention(config) self.intermediate = YolosIntermediate(config) self.output = YolosOutput(config) self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states_norm = self.layernorm_before(hidden_states) attention_output = self.attention(hidden_states_norm) # first residual connection hidden_states = attention_output + hidden_states # in Yolos, layernorm is also applied after self-attention layer_output = self.layernorm_after(hidden_states) layer_output = self.intermediate(layer_output) # second residual connection is done here layer_output = self.output(layer_output, hidden_states) return layer_output
YolosLayer
python
joke2k__faker
faker/providers/currency/de_DE/__init__.py
{ "start": 48, "end": 286 }
class ____(CurrencyProvider): price_formats = ["#,##", "%#,##", "%##,##", "%.###,##", "%#.###,##"] def pricetag(self): return self.numerify(self.random_element(self.price_formats)) + "\N{NO-BREAK SPACE}\N{EURO SIGN}"
Provider
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_athena.py
{ "start": 1215, "end": 3174 }
class ____: def setup_method(self, _): self.default_op_kwargs = dict( task_id="test_athena_sensor", query_execution_id="abc", sleep_time=5, max_retries=1, ) self.sensor = AthenaSensor(**self.default_op_kwargs, aws_conn_id=None) def test_base_aws_op_attributes(self): op = AthenaSensor(**self.default_op_kwargs) assert op.hook.aws_conn_id == "aws_default" assert op.hook._region_name is None assert op.hook._verify is None assert op.hook._config is None assert op.hook.log_query is True op = AthenaSensor( **self.default_op_kwargs, aws_conn_id="aws-test-custom-conn", region_name="eu-west-1", verify=False, botocore_config={"read_timeout": 42}, ) assert op.hook.aws_conn_id == "aws-test-custom-conn" assert op.hook._region_name == "eu-west-1" assert op.hook._verify is False assert op.hook._config is not None assert op.hook._config.read_timeout == 42 @pytest.mark.parametrize("state", ["SUCCEEDED"]) def test_poke_success_states(self, state, mock_poll_query_status): mock_poll_query_status.side_effect = [state] assert self.sensor.poke({}) is True @pytest.mark.parametrize("state", ["RUNNING", "QUEUED"]) def test_poke_intermediate_states(self, state, mock_poll_query_status): mock_poll_query_status.side_effect = [state] assert self.sensor.poke({}) is False @pytest.mark.parametrize("state", ["FAILED", "CANCELLED"]) def test_poke_failure_states(self, state, mock_poll_query_status): mock_poll_query_status.side_effect = [state] sensor = AthenaSensor(**self.default_op_kwargs, aws_conn_id=None) message = "Athena sensor failed" with pytest.raises(AirflowException, match=message): sensor.poke({})
TestAthenaSensor
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 30322, "end": 30386 }
class ____(str, Enum): ASC = "asc" DESC = "desc"
Direction
python
neetcode-gh__leetcode
python/0678-valid-parenthesis-string.py
{ "start": 725, "end": 1268 }
class ____: def checkValidString(self, s: str) -> bool: leftMin, leftMax = 0, 0 for c in s: if c == "(": leftMin, leftMax = leftMin + 1, leftMax + 1 elif c == ")": leftMin, leftMax = leftMin - 1, leftMax - 1 else: leftMin, leftMax = leftMin - 1, leftMax + 1 if leftMax < 0: return False if leftMin < 0: # required because -> s = ( * ) ( leftMin = 0 return leftMin == 0
Solution
python
huggingface__transformers
tests/models/mbart/test_modeling_mbart.py
{ "start": 15261, "end": 15897 }
class ____(unittest.TestCase): maxDiff = 1000 # longer string compare tracebacks checkpoint_name = None @classmethod def setUpClass(cls): cls.tokenizer = AutoTokenizer.from_pretrained(cls.checkpoint_name, use_fast=False) return cls @cached_property def model(self): """Only load the model if needed.""" model = MBartForConditionalGeneration.from_pretrained(self.checkpoint_name).to(torch_device) if "cuda" in torch_device: model = model.half() return model @require_torch @require_sentencepiece @require_tokenizers @slow
AbstractSeq2SeqIntegrationTest
python
ansible__ansible
lib/ansible/plugins/doc_fragments/action_common_attributes.py
{ "start": 183, "end": 2442 }
class ____(object): # Standard documentation fragment DOCUMENTATION = r""" attributes: check_mode: description: Can run in check_mode and return changed status prediction without modifying target, if not supported the action will be skipped. diff_mode: description: Will return details on what has changed (or possibly needs changing in check_mode), when in diff mode platform: description: Target OS/families that can be operated against support: N/A """ ACTIONGROUPS = r""" attributes: action_group: description: Action is part of action_group(s), for convenient setting of module_defaults. support: N/A membership: [] """ CONN = r""" attributes: become: description: Is usable alongside become keywords connection: description: Uses the target's configured connection information to execute code on it delegation: description: Can be used in conjunction with delegate_to and related keywords """ FACTS = r""" attributes: facts: description: Action returns an C(ansible_facts) dictionary that will update existing host facts """ FILES = r""" attributes: safe_file_operations: description: Uses Ansible's strict file operation functions to ensure proper permissions and avoid data corruption vault: description: Can automatically decrypt Ansible vaulted files """ FLOW = r""" attributes: action: description: Indicates this has a corresponding action plugin so some parts of the options can be executed on the controller async: description: Supports being used with the C(async) keyword bypass_host_loop: description: - Forces a 'global' task that does not execute per host, this bypasses per host templating and serial, throttle and other loop considerations - Conditionals will work as if C(run_once) is being used, variables used will be from the first available host - This action will not work normally outside of lockstep strategies """ RAW = r""" attributes: raw: description: Indicates if an action takes a 'raw' or 'free form' string as an option and has it's own special parsing of it """
ModuleDocFragment
python
pypa__setuptools
setuptools/_vendor/jaraco/collections/__init__.py
{ "start": 24086, "end": 24852 }
class ____: """ A value that is always greater than any other >>> greatest = Greatest() >>> 3 < greatest True >>> 3 > greatest False >>> greatest < 3 False >>> greatest > 3 True >>> greatest >= 3 True >>> 'x' > greatest False >>> None > greatest False """ def __ge__(self, other): return True __gt__ = __ge__ def __le__(self, other): return False __lt__ = __le__ def pop_all(items): """ Clear items in place and return a copy of items. >>> items = [1, 2, 3] >>> popped = pop_all(items) >>> popped is items False >>> popped [1, 2, 3] >>> items [] """ result, items[:] = items[:], [] return result
Greatest
python
pytorch__pytorch
torch/distributed/pipelining/stage.py
{ "start": 41057, "end": 52612 }
class ____(_PipelineStageBase): def __init__( self, stage_module: torch.nn.Module, stage_index: int, pipe_info: PipeInfo, device: torch.device, group: dist.ProcessGroup | None = None, ): """ Create a pipeline stage given a stage_module to be wrapped by this stage and a `pipe_info` describing the stage relationship of the pipeline. Args: stage_module (torch.nn.Module): the module to be wrapped by this stage stage_index (int): the index of this stage in the pipeline pipe_info (PipeInfo): information about the pipeline, can be retrieved by `pipe.info()` device (torch.device): the device to be used by this stage group (Optional[dist.ProcessGroup]): the process group to be used by this stage """ _PipelineStageBase.__init__( self, stage_module, stage_index, pipe_info.num_stages, device, group, ) self.pipe_info = pipe_info # Find stage nodes in graph submod_nodes = [ node for node in pipe_info.graph.nodes if node.op == "call_module" ] if len(submod_nodes) != self.num_stages: raise AssertionError( f"Number of submodules in pipe graph {len(submod_nodes)} does not match number of stages {self.num_stages}" ) # Find my stage node in graph self.node = submod_nodes[self.stage_index] self.name = self.node.name logger.info( "[%s] Creating PipelineStage %s for %s", self.group_rank, stage_index, self.name, ) # Create mapping from stage name to stage index self.submod_to_stage_index: dict[str, int] = {} for i, node in enumerate(submod_nodes): self.submod_to_stage_index.setdefault(node.name, i) # Cast submodule to device self._move_submod_to_device() def _move_submod_to_device(self): # Move submodule to indicated device if possible # Note: we cannot move meta module to real devices because meta tensors # do not support to() method. One needs to do an in-place tensor swap in # that case. has_meta_param = any( isinstance(p, FakeTensor) or p.is_meta for p in self.submod.parameters() ) if has_meta_param: logger.debug("%s Found meta parameters!", self.log_prefix) else: self.submod.to(self.device) def _prepare_forward_infra( self, num_microbatches: int, args: tuple[Any, ...], kwargs: dict[str, Any] | None = None, ) -> tuple[Any, ...]: """ Create send/recv infrastructures for activations (during forward) """ # TODO(whc) # this method should be deleted once lazy buffer allocation is implemented # for now, it ignores args/kwargs because it should not need to do shape inference for chunk in range(num_microbatches): self.args_recv_info[chunk] = self._create_act_recv_info() # Send info during forward for each activation self.act_send_info = self._create_act_send_info() return tuple() def get_stage_index_of_submod( self, submod_name: str, ): """ Given a submodule name, return the stage index of the submodule. """ if submod_name not in self.submod_to_stage_index: raise AssertionError(f"Stage id of {submod_name} not found") return self.submod_to_stage_index[submod_name] def _create_act_recv_info( self, ): """ Create a tuple of `_RecvInfo` for inputs to the stage. """ def create_recv_tensor(placeholder, arg_node): """ Create a receive buffer for a placeholder. """ example_value = placeholder.meta["val"] if arg_node.op == "placeholder": # This is a root level placeholder, thus an input argument to the entire model. # We are likely at stage 0, hence no need to create a receive buffer. return _RootArgPlaceholder(example_value) # Figure out the source stage of this input while arg_node.target is operator.getitem: # If the input is a getitem, we need to go deeper arg_node = arg_node.args[0] assert arg_node.op == "call_module", ( f"Expecting call_module, got {arg_node.op}" ) src_stage = self.get_stage_index_of_submod(arg_node.name) # Create a receive buffer for this placeholder logger.debug( "%s Creating recv buffer for input '%s' : %s, %s", self.log_prefix, placeholder.name, example_value.shape, example_value.dtype, ) buffer = _make_tensor_from_meta(example_value, self.device) # In case there is backward pass, set requires_grad for receive buffers # before first forward if self.has_backward: buffer.requires_grad_(True) return _RecvInfo( arg_node.name, src_stage, buffer, ) args_recv_info: list[InputInfo] = [] # Filter out placeholder nodes from `self.submod` (a GraphModule) placeholders = filter( # type: ignore[var-annotated] lambda node: node.op == "placeholder", # type: ignore[arg-type] self.submod.graph.nodes, # type: ignore[arg-type,union-attr] ) # `placeholders` are nodes internal to submod. # `self.node.args` are dependency nodes in the outer graph. # The two are 1:1. for placeholder, arg_node in zip(placeholders, self.node.args): # Create a receive buffer for this placeholder recv_info = create_recv_tensor(placeholder, arg_node) args_recv_info.append(recv_info) logger.debug( "%s Activation recv / args info: %s", self.log_prefix, args_recv_info ) # `args` is a Tuple, hence we will return a Tuple[InputInfo] return tuple(args_recv_info) def find_dst_rank( self, user: fx.Node, ) -> int | None: """ Find the destination rank of a `user` node. If the `user` is not a submod, `None` may be returned. """ if user.op == "call_module": # User is a stage (`call_module`) return self.get_stage_index_of_submod(user.name) else: # - If user.op == "output": # No need to send back to rank 0 # - If user.target is stage_backward: # No need to send assuming submod output is stored locally or # should be re-calculated in case of activation checkpointing return None def _create_act_send_info(self): """ Create a dict of send info for activations. The dict is of the form: { output_index: [dst_rank_0, dst_rank_1, ...], ... } where the list of `dst_rank`s covers the case where an output value may be consumed by multiple stages. """ # Output index: List of receiver ranks act_send_info: dict[int, list] = {} out_idx = 0 for user in self.node.users: if user.target is operator.getitem: # Recursively find the real destination gi_dsts = act_send_info.setdefault(out_idx, []) for gi_user in user.users: dst_rank = self.find_dst_rank(gi_user) if dst_rank is not None: gi_dsts.append(dst_rank) # Next `getitem` will point to the next output index out_idx += 1 else: # In case of single output value, `out_idx` will not increase dsts = act_send_info.setdefault(out_idx, []) dst_rank = self.find_dst_rank(user) if dst_rank is not None: dsts.append(dst_rank) output_node = self._get_output_node() output_vals: tuple[torch.Tensor] = tuple( v.meta["val"] for v in flatten_args(output_node.args) ) self._configure_outputs_meta(output_vals) logger.debug("%s Send info: %s", self.log_prefix, act_send_info) return act_send_info def _get_output_node(self): output_nodes = [node for node in self.submod.graph.nodes if node.op == "output"] # type: ignore[union-attr] assert len(output_nodes) == 1 output_node = output_nodes[0] return output_node def _create_grad_recv_info( self, act_send_info: dict, ) -> tuple[_RecvInfo, ...]: """ Create a tuple of `_RecvInfo` for gradients. """ # Dict[output_index, _RecvInfo] grad_recv_info: dict[int, _RecvInfo] = {} output_node = self._get_output_node() # The output node may take multiple args, meaning the submod having multiple output values. output_vals = flatten_args(output_node.args) for out_idx, dst_list in act_send_info.items(): if not dst_list: # No actual receiver for activation so no grad coming back continue output = output_vals[out_idx] example_value = output.meta["val"] logger.debug( f"{self.log_prefix} Creating grad recv buffer for output {output.name} " # noqa: G004 f": {example_value.shape}, {example_value.dtype}" ) # TODO: otherwise needs grad accumulation assert len(dst_list) == 1, "Backward of skip connections not supported yet" grad_src = dst_list[0] grad_recv_info[out_idx] = _RecvInfo( f"{grad_src}", # noqa: G004 grad_src, _make_tensor_from_meta(example_value, self.device), ) # Convert to tuple for convenience in get_ops and retrieve tensor grad_recv_info_tuple = tuple(grad_recv_info.values()) logger.debug("%s Grad recv info: %s", self.log_prefix, grad_recv_info_tuple) return grad_recv_info_tuple # A helper function to create a pipeline stage based on traced pipeline information def build_stage( stage_module: torch.nn.Module, stage_index: int, pipe_info: PipeInfo, device: torch.device, group: dist.ProcessGroup | None = None, ) -> _PipelineStage: """ Create a pipeline stage given a stage_module to be wrapped by this stage and pipeline information. Args: stage_module (torch.nn.Module): the module to be wrapped by this stage stage_index (int): the index of this stage in the pipeline pipe_info (PipeInfo): information about the pipeline, can be retrieved by `pipe.info()` device (torch.device): the device to be used by this stage group (Optional[dist.ProcessGroup]): the process group to be used by this stage Returns: _PipelineStage: a pipeline stage that can run with `PipelineSchedules`. """ return _PipelineStage( stage_module, stage_index, pipe_info, device, group, )
_PipelineStage
python
scipy__scipy
scipy/signal/tests/test_filter_design.py
{ "start": 6319, "end": 7599 }
class ____: @skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883") @pytest.mark.parametrize('dt', ('float64', 'complex128')) def test_simple(self, dt, xp): dtyp = getattr(xp, dt) z_r = xp.asarray([0.5, -0.5]) p_r = xp.asarray([1.j / math.sqrt(2), -1.j / math.sqrt(2)]) # Sort the zeros/poles so that we don't fail the test if the order # changes z_r = _sort_cmplx(z_r, xp=xp) p_r = _sort_cmplx(p_r, xp=xp) b = xp.astype(_pu.poly(z_r, xp=xp), dtyp) a = xp.astype(_pu.poly(p_r, xp=xp), dtyp) z, p, k = tf2zpk(b, a) z = _sort_cmplx(z, xp=xp) # The real part of `p` is ~0.0, so sort by imaginary part p = p[xp.argsort(xp.imag(p))] assert_array_almost_equal(z, z_r) assert_array_almost_equal(p, p_r) assert math.isclose(xp.real(k), 1.) assert k.dtype == dtyp def test_bad_filter(self): # Regression test for #651: better handling of badly conditioned # filter coefficients. with warnings.catch_warnings(): warnings.simplefilter("error", BadCoefficients) assert_raises(BadCoefficients, tf2zpk, [1e-15], [1.0, 1.0]) @make_xp_test_case(zpk2tf)
TestTf2zpk
python
walkccc__LeetCode
solutions/84. Largest Rectangle in Histogram/84.py
{ "start": 0, "end": 368 }
class ____: def largestRectangleArea(self, heights: list[int]) -> int: ans = 0 stack = [] for i in range(len(heights) + 1): while stack and (i == len(heights) or heights[stack[-1]] > heights[i]): h = heights[stack.pop()] w = i - stack[-1] - 1 if stack else i ans = max(ans, h * w) stack.append(i) return ans
Solution
python
ray-project__ray
python/ray/data/examples/data/video_processing/http_utils.py
{ "start": 564, "end": 5835 }
class ____: """Small helper around ``requests``/``aiohttp`` for reuseable HTTP clients.""" def __init__(self, *, reuse_client: bool = True) -> None: self.reuse_client = reuse_client self._sync_client: Optional[Any] = None self._async_client: Optional[Any] = None def get_sync_client(self): if requests is None: raise ImportError( "requests is required for HTTPConnection. Install with `pip install requests`." ) if self._sync_client is None or not self.reuse_client: if self._sync_client is not None and not self.reuse_client: try: self._sync_client.close() except Exception: pass self._sync_client = requests.Session() return self._sync_client async def get_async_client(self): if aiohttp is None: raise ImportError( "aiohttp is required for HTTPConnection. Install with `pip install aiohttp`." ) if self._async_client is None or not self.reuse_client: if ( self._async_client is not None and not self._async_client.closed and not self.reuse_client ): try: await self._async_client.close() except Exception: pass self._async_client = aiohttp.ClientSession() return self._async_client def _validate_http_url(self, url: str) -> None: parsed_url = urlparse(url) if parsed_url.scheme not in ("http", "https"): raise ValueError("Invalid HTTP URL: scheme must be 'http' or 'https'.") def _headers(self, **extras: str) -> MutableMapping[str, str]: return dict(extras) def get_response( self, url: str, *, stream: bool = False, timeout: Optional[float] = None, extra_headers: Optional[Mapping[str, str]] = None, ): self._validate_http_url(url) client = self.get_sync_client() extra_headers = extra_headers or {} return client.get( url, headers=self._headers(**extra_headers), stream=stream, timeout=timeout, ) async def get_async_response( self, url: str, *, timeout: Optional[float] = None, extra_headers: Optional[Mapping[str, str]] = None, ): self._validate_http_url(url) client = await self.get_async_client() extra_headers = extra_headers or {} return client.get( url, headers=self._headers(**extra_headers), timeout=timeout, ) def get_bytes(self, url: str, *, timeout: Optional[float] = None) -> bytes: with self.get_response(url, stream=False, timeout=timeout) as r: r.raise_for_status() return r.content async def async_get_bytes( self, url: str, *, timeout: Optional[float] = None, ) -> bytes: async with await self.get_async_response(url, timeout=timeout) as r: r.raise_for_status() return await r.read() def download_file( self, url: str, save_path: Path, *, timeout: Optional[float] = None, chunk_size: int = 512 * 1024, ) -> Path: with self.get_response(url, stream=True, timeout=timeout) as r: r.raise_for_status() with save_path.open("wb") as f: for chunk in r.iter_content(chunk_size): if chunk: f.write(chunk) return save_path async def async_download_file( self, url: str, save_path: Path, *, timeout: Optional[float] = None, chunk_size: int = 512 * 1024, ) -> Path: async with await self.get_async_response(url, timeout=timeout) as r: r.raise_for_status() with save_path.open("wb") as f: async for chunk in r.content.iter_chunked(chunk_size): if chunk: f.write(chunk) return save_path def download_bytes_chunked( self, url: str, *, timeout: Optional[float] = None, chunk_size: int = 512 * 1024, ) -> bytes: """Stream a response into memory to avoid large one-shot downloads.""" with self.get_response(url, stream=True, timeout=timeout) as r: r.raise_for_status() bio = BytesIO() for chunk in r.iter_content(chunk_size): if chunk: bio.write(chunk) return bio.getvalue() def close(self): if self._sync_client is not None: try: self._sync_client.close() except Exception: pass self._sync_client = None async def aclose(self): if self._async_client is not None and not self._async_client.closed: try: await self._async_client.close() except Exception: pass self._async_client = None
HTTPConnection
python
getsentry__sentry
src/sentry/api/endpoints/organization_stats_summary.py
{ "start": 5142, "end": 10920 }
class ____(OrganizationEndpoint): publish_status = {"GET": ApiPublishStatus.PUBLIC} owner = ApiOwner.ENTERPRISE @extend_schema( operation_id="Retrieve an Organization's Events Count by Project", parameters=[GlobalParams.ORG_ID_OR_SLUG, OrgStatsSummaryQueryParamsSerializer], request=None, responses={ 200: inline_sentry_response_serializer( "OrganizationStatsSummaryResponse", StatsSummaryApiResponse ), 401: RESPONSE_UNAUTHORIZED, 404: RESPONSE_NOT_FOUND, }, examples=OrganizationExamples.RETRIEVE_SUMMARY_EVENT_COUNT, ) def get(self, request: Request, organization: Organization) -> HttpResponse: """ Query summarized event counts by project for your Organization. Also see https://docs.sentry.io/api/organizations/retrieve-event-counts-for-an-organization-v2/ for reference. """ with self.handle_query_errors(): tenant_ids = {"organization_id": organization.id} with sentry_sdk.start_span(op="outcomes.endpoint", name="build_outcomes_query"): query = self.build_outcomes_query( request, organization, ) with sentry_sdk.start_span(op="outcomes.endpoint", name="run_outcomes_query"): result_totals = run_outcomes_query_totals(query, tenant_ids=tenant_ids) with sentry_sdk.start_span(op="outcomes.endpoint", name="massage_outcomes_result"): projects, result = massage_sessions_result_summary( query, result_totals, request.GET.getlist("outcome") ) if request.GET.get("download"): csv_content = self._generate_csv(projects) response = HttpResponse(content_type="text/csv", status=200) response["Content-Disposition"] = 'attachment; filename="stats_summary.csv"' response.write(csv_content) return response return Response(result, status=200) def build_outcomes_query(self, request: Request, organization): params = {"organization_id": organization.id} project_ids = self._get_projects_for_orgstats_query(request, organization) query_dict = request.GET.copy() group_by = ["project", "outcome", "category"] if query_dict.get("reason"): group_by.append("reason") query_dict.setlist("groupBy", group_by) if project_ids: params["project_id"] = project_ids return QueryDefinition.from_query_dict(query_dict, params) def _get_projects_for_orgstats_query(self, request: Request, organization): req_proj_ids = self.get_requested_project_ids_unchecked(request) # the projects table always filters by project # the projects in the table should be those the user has access to projects = self.get_projects(request, organization, project_ids=req_proj_ids) if not projects: raise NoProjects("No projects available") return [p.id for p in projects] def _is_org_total_query(self, project_ids): return all([not project_ids or project_ids == ALL_ACCESS_PROJECTS]) def _generate_csv(self, projects): if not len(projects): return output = StringIO() csv_writer = csv.writer(output) longest_key = None max_length = 0 for key, value in projects.items(): if len(value) > max_length: max_length = len(value) longest_key = key headers = ["project_id", "project_slug"] longest_key_project = projects[longest_key] for category_stats in longest_key_project.values(): for category, stats in category_stats.items(): for outcome in stats["outcomes"]: headers.append(outcome + "_" + category + "s") for total in stats["totals"]: headers.append(total + "_" + category + "s") csv_writer.writerow(headers) ids = projects.keys() project_id_to_slug = dict(Project.objects.filter(id__in=ids).values_list("id", "slug")) for project_id, project_stats in projects.items(): slug = project_id_to_slug[project_id] row = {"project_id": project_id, "project_slug": slug} for category_stats in project_stats.values(): for category, stats in category_stats.items(): for outcome, val in stats["outcomes"].items(): header_name = outcome + "_" + category + "s" if header_name in headers: row[header_name] = val else: row[header_name] = 0 for total, val in stats["totals"].items(): header_name = total + "_" + category + "s" if header_name in headers: row[header_name] = val else: row[header_name] = 0 formatted_row = [] for header in headers: if header in row: formatted_row.append(row[header]) else: formatted_row.append(0) csv_writer.writerow(formatted_row) return output.getvalue() @contextmanager def handle_query_errors(self): try: with handle_query_errors(): yield except (InvalidField, NoProjects, InvalidParams, InvalidQuery) as error: raise ParseError(detail=str(error))
OrganizationStatsSummaryEndpoint
python
kamyu104__LeetCode-Solutions
Python/maximum-balanced-shipments.py
{ "start": 38, "end": 368 }
class ____(object): def maxBalancedShipments(self, weight): """ :type weight: List[int] :rtype: int """ result = mx = 0 for x in weight: if x < mx: mx = 0 result += 1 else: mx = x return result
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI026.py
{ "start": 485, "end": 555 }
class ____(FooEnum): BAR = None VarAlias = str AliasFoo = Foo
BarEnum
python
huggingface__transformers
tests/test_sequence_feature_extraction_common.py
{ "start": 773, "end": 16592 }
class ____(FeatureExtractionSavingTestMixin): # to overwrite at feature extractactor specific tests feat_extract_tester = None feature_extraction_class = None @property def feat_extract_dict(self): return self.feat_extract_tester.prepare_feat_extract_dict() def test_feat_extract_common_properties(self): feat_extract = self.feature_extraction_class(**self.feat_extract_dict) self.assertTrue(hasattr(feat_extract, "feature_size")) self.assertTrue(hasattr(feat_extract, "sampling_rate")) self.assertTrue(hasattr(feat_extract, "padding_value")) def test_batch_feature(self): speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() feat_extract = self.feature_extraction_class(**self.feat_extract_dict) input_name = feat_extract.model_input_names[0] processed_features = BatchFeature({input_name: speech_inputs}) self.assertTrue(all(len(x) == len(y) for x, y in zip(speech_inputs, processed_features[input_name]))) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(equal_length=True) processed_features = BatchFeature({input_name: speech_inputs}, tensor_type="np") batch_features_input = processed_features[input_name] if len(batch_features_input.shape) < 3: batch_features_input = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size) ) @require_torch def test_batch_feature_pt(self): speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(equal_length=True) feat_extract = self.feature_extraction_class(**self.feat_extract_dict) input_name = feat_extract.model_input_names[0] processed_features = BatchFeature({input_name: speech_inputs}, tensor_type="pt") batch_features_input = processed_features[input_name] if len(batch_features_input.shape) < 3: batch_features_input = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size) ) def _check_padding(self, numpify=False): def _inputs_have_equal_length(input): length = len(input[0]) for input_slice in input[1:]: if len(input_slice) != length: return False return True def _inputs_are_equal(input_1, input_2): if len(input_1) != len(input_2): return False for input_slice_1, input_slice_2 in zip(input_1, input_2): if not np.allclose(np.asarray(input_slice_1), np.asarray(input_slice_2), atol=1e-3): return False return True feat_extract = self.feature_extraction_class(**self.feat_extract_dict) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(numpify=numpify) input_name = feat_extract.model_input_names[0] processed_features = BatchFeature({input_name: speech_inputs}) pad_diff = self.feat_extract_tester.seq_length_diff pad_max_length = self.feat_extract_tester.max_seq_length + pad_diff pad_min_length = self.feat_extract_tester.min_seq_length batch_size = self.feat_extract_tester.batch_size feature_size = self.feat_extract_tester.feature_size # test padding for list[int] + numpy input_1 = feat_extract.pad(processed_features, padding=False) input_1 = input_1[input_name] input_2 = feat_extract.pad(processed_features, padding="longest") input_2 = input_2[input_name] input_3 = feat_extract.pad(processed_features, padding="max_length", max_length=len(speech_inputs[-1])) input_3 = input_3[input_name] input_4 = feat_extract.pad(processed_features, padding="longest", return_tensors="np") input_4 = input_4[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(ValueError): feat_extract.pad(processed_features, padding="max_length")[input_name] input_5 = feat_extract.pad( processed_features, padding="max_length", max_length=pad_max_length, return_tensors="np" ) input_5 = input_5[input_name] self.assertFalse(_inputs_have_equal_length(input_1)) self.assertTrue(_inputs_have_equal_length(input_2)) self.assertTrue(_inputs_have_equal_length(input_3)) self.assertTrue(_inputs_are_equal(input_2, input_3)) self.assertTrue(len(input_1[0]) == pad_min_length) self.assertTrue(len(input_1[1]) == pad_min_length + pad_diff) self.assertTrue(input_4.shape[:2] == (batch_size, len(input_3[0]))) self.assertTrue(input_5.shape[:2] == (batch_size, pad_max_length)) if feature_size > 1: self.assertTrue(input_4.shape[2] == input_5.shape[2] == feature_size) # test padding for `pad_to_multiple_of` for list[int] + numpy input_6 = feat_extract.pad(processed_features, pad_to_multiple_of=10) input_6 = input_6[input_name] input_7 = feat_extract.pad(processed_features, padding="longest", pad_to_multiple_of=10) input_7 = input_7[input_name] input_8 = feat_extract.pad( processed_features, padding="max_length", pad_to_multiple_of=10, max_length=pad_max_length ) input_8 = input_8[input_name] input_9 = feat_extract.pad( processed_features, padding="max_length", pad_to_multiple_of=10, max_length=pad_max_length, return_tensors="np", ) input_9 = input_9[input_name] self.assertTrue(all(len(x) % 10 == 0 for x in input_6)) self.assertTrue(_inputs_are_equal(input_6, input_7)) expected_mult_pad_length = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(x) == expected_mult_pad_length for x in input_8)) self.assertEqual(input_9.shape[:2], (batch_size, expected_mult_pad_length)) if feature_size > 1: self.assertTrue(input_9.shape[2] == feature_size) # Check padding value is correct padding_vector_sum = (np.ones(self.feat_extract_tester.feature_size) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_2[0])[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)) < 1e-3 ) self.assertTrue( abs( np.asarray(input_2[1])[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_2[2])[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_5[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)) < 1e-3 ) self.assertTrue( abs(input_9[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length)) < 1e-3 ) def _check_truncation(self, numpify=False): def _inputs_have_equal_length(input): length = len(input[0]) for input_slice in input[1:]: if len(input_slice) != length: return False return True def _inputs_are_equal(input_1, input_2): if len(input_1) != len(input_2): return False for input_slice_1, input_slice_2 in zip(input_1, input_2): if not np.allclose(np.asarray(input_slice_1), np.asarray(input_slice_2), atol=1e-3): return False return True feat_extract = self.feature_extraction_class(**self.feat_extract_dict) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(numpify=numpify) input_name = feat_extract.model_input_names[0] processed_features = BatchFeature({input_name: speech_inputs}) # truncate to smallest input_1 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[0]), truncation=True ) input_1 = input_1[input_name] input_2 = feat_extract.pad(processed_features, padding="max_length", max_length=len(speech_inputs[0])) input_2 = input_2[input_name] self.assertTrue(_inputs_have_equal_length(input_1)) self.assertFalse(_inputs_have_equal_length(input_2)) # truncate to smallest with np input_3 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[0]), return_tensors="np", truncation=True, ) input_3 = input_3[input_name] input_4 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[0]), return_tensors="np" ) input_4 = input_4[input_name] self.assertTrue(_inputs_have_equal_length(input_3)) self.assertTrue(input_3.shape[1] == len(speech_inputs[0])) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(input_4)) # truncate to middle input_5 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[1]), truncation=True, return_tensors="np", ) input_5 = input_5[input_name] input_6 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[1]), truncation=True ) input_6 = input_6[input_name] input_7 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[1]), return_tensors="np" ) input_7 = input_7[input_name] self.assertTrue(input_5.shape[1] == len(speech_inputs[1])) self.assertTrue(_inputs_have_equal_length(input_5)) self.assertTrue(_inputs_have_equal_length(input_6)) self.assertTrue(_inputs_are_equal(input_5, input_6)) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(input_7)) self.assertTrue(len(input_7[-1]) == len(speech_inputs[-1])) # padding has to be max_length when setting `truncation=True` with self.assertRaises(ValueError): feat_extract.pad(processed_features, truncation=True)[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(ValueError): feat_extract.pad(processed_features, padding="longest", truncation=True)[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(ValueError): feat_extract.pad(processed_features, padding="longest", truncation=True)[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(ValueError): feat_extract.pad(processed_features, padding="max_length", truncation=True)[input_name] # test truncation for `pad_to_multiple_of` for list[int] + numpy pad_to_multiple_of = 12 input_8 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[0]), pad_to_multiple_of=pad_to_multiple_of, truncation=True, ) input_8 = input_8[input_name] input_9 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[0]), pad_to_multiple_of=pad_to_multiple_of, ) input_9 = input_9[input_name] # retrieve expected_length as multiple of pad_to_multiple_of expected_length = len(speech_inputs[0]) if expected_length % pad_to_multiple_of != 0: expected_length = ((len(speech_inputs[0]) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_8[0]) == expected_length) self.assertTrue(_inputs_have_equal_length(input_8)) self.assertFalse(_inputs_have_equal_length(input_9)) def test_padding_from_list(self): self._check_padding(numpify=False) def test_padding_from_array(self): self._check_padding(numpify=True) def test_truncation_from_list(self): self._check_truncation(numpify=False) def test_truncation_from_array(self): self._check_truncation(numpify=True) @require_torch def test_padding_accepts_tensors_pt(self): feat_extract = self.feature_extraction_class(**self.feat_extract_dict) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() input_name = feat_extract.model_input_names[0] processed_features = BatchFeature({input_name: speech_inputs}) input_np = feat_extract.pad(processed_features, padding="longest", return_tensors="np")[input_name] input_pt = feat_extract.pad(processed_features, padding="longest", return_tensors="pt")[input_name] self.assertTrue(abs(input_np.astype(np.float32).sum() - input_pt.numpy().astype(np.float32).sum()) < 1e-2) def test_attention_mask(self): feat_dict = self.feat_extract_dict feat_dict["return_attention_mask"] = True feat_extract = self.feature_extraction_class(**feat_dict) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() input_lengths = [len(x) for x in speech_inputs] input_name = feat_extract.model_input_names[0] processed = BatchFeature({input_name: speech_inputs}) processed = feat_extract.pad(processed, padding="longest", return_tensors="np") self.assertIn("attention_mask", processed) self.assertListEqual(list(processed.attention_mask.shape), list(processed[input_name].shape[:2])) self.assertListEqual(processed.attention_mask.sum(-1).tolist(), input_lengths) def test_attention_mask_with_truncation(self): feat_dict = self.feat_extract_dict feat_dict["return_attention_mask"] = True feat_extract = self.feature_extraction_class(**feat_dict) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() input_lengths = [len(x) for x in speech_inputs] input_name = feat_extract.model_input_names[0] processed = BatchFeature({input_name: speech_inputs}) max_length = min(input_lengths) processed_pad = feat_extract.pad( processed, padding="max_length", max_length=max_length, truncation=True, return_tensors="np" ) self.assertIn("attention_mask", processed_pad) self.assertListEqual( list(processed_pad.attention_mask.shape), [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1).tolist(), [max_length for x in speech_inputs] )
SequenceFeatureExtractionTestMixin
python
pypa__pipenv
pipenv/vendor/tomlkit/exceptions.py
{ "start": 3049, "end": 3301 }
class ____(ParseError): """ An empty table name was found during parsing. """ def __init__(self, line: int, col: int) -> None: message = "Empty table name" super().__init__(line, col, message=message)
EmptyTableNameError
python
modin-project__modin
modin/core/dataframe/base/interchange/dataframe_protocol/dataframe.py
{ "start": 1877, "end": 2227 }
class ____(TypedDict): # noqa: GL08 # whether the ordering of dictionary indices is semantically meaningful is_ordered: bool # whether a column-style mapping of categorical values to other objects exists is_dictionary: bool # None if not a column-style categorical. categories: Optional["ProtocolColumn"]
CategoricalDescription
python
matplotlib__matplotlib
galleries/tutorials/artists.py
{ "start": 2490, "end": 30284 }
class ____ the Matplotlib API, and the one you will be working with most of the time. This is because the ``Axes`` is the plotting area into which most of the objects go, and the ``Axes`` has many special helper methods (:meth:`~matplotlib.axes.Axes.plot`, :meth:`~matplotlib.axes.Axes.text`, :meth:`~matplotlib.axes.Axes.hist`, :meth:`~matplotlib.axes.Axes.imshow`) to create the most common graphics primitives (:class:`~matplotlib.lines.Line2D`, :class:`~matplotlib.text.Text`, :class:`~matplotlib.patches.Rectangle`, :class:`~matplotlib.image.AxesImage`, respectively). These helper methods will take your data (e.g., ``numpy`` arrays and strings) and create primitive ``Artist`` instances as needed (e.g., ``Line2D``), add them to the relevant containers, and draw them when requested. If you want to create an ``Axes`` at an arbitrary location, simply use the :meth:`~matplotlib.figure.Figure.add_axes` method which takes a list of ``[left, bottom, width, height]`` values in 0-1 relative figure coordinates:: fig2 = plt.figure() ax2 = fig2.add_axes((0.15, 0.1, 0.7, 0.3)) Continuing with our example:: import numpy as np t = np.arange(0.0, 1.0, 0.01) s = np.sin(2*np.pi*t) line, = ax.plot(t, s, color='blue', lw=2) In this example, ``ax`` is the ``Axes`` instance created by the ``fig.add_subplot`` call above and when you call ``ax.plot``, it creates a ``Line2D`` instance and adds it to the ``Axes``. In the interactive `IPython <https://ipython.org/>`_ session below, you can see that the ``Axes.lines`` list is length one and contains the same line that was returned by the ``line, = ax.plot...`` call: .. sourcecode:: ipython In [101]: ax.lines[0] Out[101]: <matplotlib.lines.Line2D at 0x19a95710> In [102]: line Out[102]: <matplotlib.lines.Line2D at 0x19a95710> If you make subsequent calls to ``ax.plot`` (and the hold state is "on" which is the default) then additional lines will be added to the list. You can remove a line later by calling its ``remove`` method:: line = ax.lines[0] line.remove() The Axes also has helper methods to configure and decorate the x-axis and y-axis tick, tick labels and axis labels:: xtext = ax.set_xlabel('my xdata') # returns a Text instance ytext = ax.set_ylabel('my ydata') When you call :meth:`ax.set_xlabel <matplotlib.axes.Axes.set_xlabel>`, it passes the information on the :class:`~matplotlib.text.Text` instance of the :class:`~matplotlib.axis.XAxis`. Each ``Axes`` instance contains an :class:`~matplotlib.axis.XAxis` and a :class:`~matplotlib.axis.YAxis` instance, which handle the layout and drawing of the ticks, tick labels and axis labels. Try creating the figure below. """ # sphinx_gallery_capture_repr = ('__repr__',) import matplotlib.pyplot as plt import numpy as np fig = plt.figure() fig.subplots_adjust(top=0.8) ax1 = fig.add_subplot(211) ax1.set_ylabel('Voltage [V]') ax1.set_title('A sine wave') t = np.arange(0.0, 1.0, 0.01) s = np.sin(2*np.pi*t) line, = ax1.plot(t, s, color='blue', lw=2) # Fixing random state for reproducibility np.random.seed(19680801) ax2 = fig.add_axes((0.15, 0.1, 0.7, 0.3)) n, bins, patches = ax2.hist(np.random.randn(1000), 50, facecolor='yellow', edgecolor='yellow') ax2.set_xlabel('Time [s]') plt.show() # %% # .. _customizing-artists: # # Customizing your objects # ======================== # # Every element in the figure is represented by a Matplotlib # :class:`~matplotlib.artist.Artist`, and each has an extensive list of # properties to configure its appearance. The figure itself contains a # :class:`~matplotlib.patches.Rectangle` exactly the size of the figure, # which you can use to set the background color and transparency of the # figures. Likewise, each :class:`~matplotlib.axes.Axes` bounding box # (the standard white box with black edges in the typical Matplotlib # plot, has a ``Rectangle`` instance that determines the color, # transparency, and other properties of the Axes. These instances are # stored as member variables :attr:`!Figure.patch` and :attr:`!Axes.patch` # ("Patch" is a name inherited from MATLAB, and is a 2D "patch" # of color on the figure, e.g., rectangles, circles and polygons). # Every Matplotlib ``Artist`` has the following properties # # ========== ================================================================= # Property Description # ========== ================================================================= # alpha The transparency - a scalar from 0-1 # animated A boolean that is used to facilitate animated drawing # axes The Axes that the Artist lives in, possibly None # clip_box The bounding box that clips the Artist # clip_on Whether clipping is enabled # clip_path The path the artist is clipped to # contains A picking function to test whether the artist contains the pick # point # figure The figure instance the artist lives in, possibly None # label A text label (e.g., for auto-labeling) # picker A python object that controls object picking # transform The transformation # visible A boolean whether the artist should be drawn # zorder A number which determines the drawing order # rasterized Boolean; Turns vectors into raster graphics (for compression & # EPS transparency) # ========== ================================================================= # # Each of the properties is accessed with an old-fashioned setter or # getter (yes we know this irritates Pythonistas and we plan to support # direct access via properties or traits but it hasn't been done yet). # For example, to multiply the current alpha by a half:: # # a = o.get_alpha() # o.set_alpha(0.5*a) # # If you want to set a number of properties at once, you can also use # the ``set`` method with keyword arguments. For example:: # # o.set(alpha=0.5, zorder=2) # # If you are working interactively at the python shell, a handy way to # inspect the ``Artist`` properties is to use the # :func:`matplotlib.artist.getp` function (simply # :func:`~matplotlib.pyplot.getp` in pyplot), which lists the properties # and their values. This works for classes derived from ``Artist`` as # well, e.g., ``Figure`` and ``Rectangle``. Here are the ``Figure`` rectangle # properties mentioned above: # # .. sourcecode:: ipython # # In [149]: matplotlib.artist.getp(fig.patch) # agg_filter = None # alpha = None # animated = False # antialiased or aa = False # bbox = Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0) # capstyle = butt # children = [] # clip_box = None # clip_on = True # clip_path = None # contains = None # data_transform = BboxTransformTo( TransformedBbox( Bbox... # edgecolor or ec = (1.0, 1.0, 1.0, 1.0) # extents = Bbox(x0=0.0, y0=0.0, x1=640.0, y1=480.0) # facecolor or fc = (1.0, 1.0, 1.0, 1.0) # figure = Figure(640x480) # fill = True # gid = None # hatch = None # height = 1 # in_layout = False # joinstyle = miter # label = # linestyle or ls = solid # linewidth or lw = 0.0 # patch_transform = CompositeGenericTransform( BboxTransformTo( ... # path = Path(array([[0., 0.], [1., 0.], [1.,... # path_effects = [] # picker = None # rasterized = None # sketch_params = None # snap = None # transform = CompositeGenericTransform( CompositeGenericTra... # transformed_clip_path_and_affine = (None, None) # url = None # verts = [[ 0. 0.] [640. 0.] [640. 480.] [ 0. 480.... # visible = True # width = 1 # window_extent = Bbox(x0=0.0, y0=0.0, x1=640.0, y1=480.0) # x = 0 # xy = (0, 0) # y = 0 # zorder = 1 # # The docstrings for all of the classes also contain the ``Artist`` # properties, so you can consult the interactive "help" or the # :ref:`artist-api` for a listing of properties for a given object. # # .. _object-containers: # # Object containers # ================= # # # Now that we know how to inspect and set the properties of a given # object we want to configure, we need to know how to get at that object. # As mentioned in the introduction, there are two kinds of objects: # primitives and containers. The primitives are usually the things you # want to configure (the font of a :class:`~matplotlib.text.Text` # instance, the width of a :class:`~matplotlib.lines.Line2D`) although # the containers also have some properties as well -- for example the # :class:`~matplotlib.axes.Axes` :class:`~matplotlib.artist.Artist` is a # container that contains many of the primitives in your plot, but it # also has properties like the ``xscale`` to control whether the xaxis # is 'linear' or 'log'. In this section we'll review where the various # container objects store the ``Artists`` that you want to get at. # # .. _figure-container: # # Figure container # ---------------- # # The top level container ``Artist`` is the # :class:`matplotlib.figure.Figure`, and it contains everything in the # figure. The background of the figure is a # :class:`~matplotlib.patches.Rectangle` which is stored in # :attr:`!Figure.patch`. As # you add subplots (:meth:`~matplotlib.figure.Figure.add_subplot`) and # Axes (:meth:`~matplotlib.figure.Figure.add_axes`) to the figure # these will be appended to the :attr:`Figure.axes # <matplotlib.figure.Figure.axes>`. These are also returned by the # methods that create them: # # .. sourcecode:: ipython # # In [156]: fig = plt.figure() # # In [157]: ax1 = fig.add_subplot(211) # # In [158]: ax2 = fig.add_axes((0.1, 0.1, 0.7, 0.3)) # # In [159]: ax1 # Out[159]: <Axes:> # # In [160]: print(fig.axes) # [<Axes:>, <matplotlib.axes._axes.Axes object at 0x7f0768702be0>] # # Because the figure maintains the concept of the "current Axes" (see # :meth:`Figure.gca <matplotlib.figure.Figure.gca>` and # :meth:`Figure.sca <matplotlib.figure.Figure.sca>`) to support the # pylab/pyplot state machine, you should not insert or remove Axes # directly from the Axes list, but rather use the # :meth:`~matplotlib.figure.Figure.add_subplot` and # :meth:`~matplotlib.figure.Figure.add_axes` methods to insert, and the # `Axes.remove <matplotlib.artist.Artist.remove>` method to delete. You are # free however, to iterate over the list of Axes or index into it to get # access to ``Axes`` instances you want to customize. Here is an # example which turns all the Axes grids on:: # # for ax in fig.axes: # ax.grid(True) # # # The figure also has its own ``images``, ``lines``, ``patches`` and ``text`` # attributes, which you can use to add primitives directly. When doing so, the # default coordinate system for the ``Figure`` will simply be in pixels (which # is not usually what you want). If you instead use Figure-level methods to add # Artists (e.g., using `.Figure.text` to add text), then the default coordinate # system will be "figure coordinates" where (0, 0) is the bottom-left of the # figure and (1, 1) is the top-right of the figure. # # As with all ``Artist``\s, you can control this coordinate system by setting # the transform property. You can explicitly use "figure coordinates" by # setting the ``Artist`` transform to :attr:`!fig.transFigure`: import matplotlib.lines as lines fig = plt.figure() l1 = lines.Line2D([0, 1], [0, 1], transform=fig.transFigure, figure=fig) l2 = lines.Line2D([0, 1], [1, 0], transform=fig.transFigure, figure=fig) fig.lines.extend([l1, l2]) plt.show() # %% # Here is a summary of the Artists the Figure contains # # ================ ============================================================ # Figure attribute Description # ================ ============================================================ # axes A list of `~.axes.Axes` instances # patch The `.Rectangle` background # images A list of `.FigureImage` patches - # useful for raw pixel display # legends A list of Figure `.Legend` instances # (different from ``Axes.get_legend()``) # lines A list of Figure `.Line2D` instances # (rarely used, see ``Axes.lines``) # patches A list of Figure `.Patch`\s # (rarely used, see ``Axes.patches``) # texts A list Figure `.Text` instances # ================ ============================================================ # # .. _axes-container: # # Axes container # -------------- # # The :class:`matplotlib.axes.Axes` is the center of the Matplotlib # universe -- it contains the vast majority of all the ``Artists`` used # in a figure with many helper methods to create and add these # ``Artists`` to itself, as well as helper methods to access and # customize the ``Artists`` it contains. Like the # :class:`~matplotlib.figure.Figure`, it contains a # :class:`~matplotlib.patches.Patch` # :attr:`!matplotlib.axes.Axes.patch` which is a # :class:`~matplotlib.patches.Rectangle` for Cartesian coordinates and a # :class:`~matplotlib.patches.Circle` for polar coordinates; this patch # determines the shape, background and border of the plotting region:: # # ax = fig.add_subplot() # rect = ax.patch # a Rectangle instance # rect.set_facecolor('green') # # When you call a plotting method, e.g., the canonical # `~matplotlib.axes.Axes.plot` and pass in arrays or lists of values, the # method will create a `matplotlib.lines.Line2D` instance, update the line with # all the ``Line2D`` properties passed as keyword arguments, add the line to # the ``Axes``, and return it to you: # # .. sourcecode:: ipython # # In [213]: x, y = np.random.rand(2, 100) # # In [214]: line, = ax.plot(x, y, '-', color='blue', linewidth=2) # # ``plot`` returns a list of lines because you can pass in multiple x, y # pairs to plot, and we are unpacking the first element of the length # one list into the line variable. The line has been added to the # ``Axes.lines`` list: # # .. sourcecode:: ipython # # In [229]: print(ax.lines) # [<matplotlib.lines.Line2D at 0xd378b0c>] # # Similarly, methods that create patches, like # :meth:`~matplotlib.axes.Axes.bar` creates a list of rectangles, will # add the patches to the :attr:`!Axes.patches` list: # # .. sourcecode:: ipython # # In [233]: n, bins, rectangles = ax.hist(np.random.randn(1000), 50) # # In [234]: rectangles # Out[234]: <BarContainer object of 50 artists> # # In [235]: print(len(ax.patches)) # Out[235]: 50 # # You should not add objects directly to the ``Axes.lines`` or ``Axes.patches`` # lists, because the ``Axes`` needs to do a few things when it creates and adds # an object: # # - It sets the ``figure`` and ``axes`` property of the ``Artist``; # - It sets the default ``Axes`` transformation (unless one is already set); # - It inspects the data contained in the ``Artist`` to update the data # structures controlling auto-scaling, so that the view limits can be # adjusted to contain the plotted data. # # You can, nonetheless, create objects yourself and add them directly to the # ``Axes`` using helper methods like `~matplotlib.axes.Axes.add_line` and # `~matplotlib.axes.Axes.add_patch`. Here is an annotated interactive session # illustrating what is going on: # # .. sourcecode:: ipython # # In [262]: fig, ax = plt.subplots() # # # create a rectangle instance # In [263]: rect = matplotlib.patches.Rectangle((1, 1), width=5, height=12) # # # by default the Axes instance is None # In [264]: print(rect.axes) # None # # # and the transformation instance is set to the "identity transform" # In [265]: print(rect.get_data_transform()) # IdentityTransform() # # # now we add the Rectangle to the Axes # In [266]: ax.add_patch(rect) # # # and notice that the ax.add_patch method has set the Axes # # instance # In [267]: print(rect.axes) # Axes(0.125,0.1;0.775x0.8) # # # and the transformation has been set too # In [268]: print(rect.get_data_transform()) # CompositeGenericTransform( # TransformWrapper( # BlendedAffine2D( # IdentityTransform(), # IdentityTransform())), # CompositeGenericTransform( # BboxTransformFrom( # TransformedBbox( # Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0), # TransformWrapper( # BlendedAffine2D( # IdentityTransform(), # IdentityTransform())))), # BboxTransformTo( # TransformedBbox( # Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88), # BboxTransformTo( # TransformedBbox( # Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8), # Affine2D( # [[100. 0. 0.] # [ 0. 100. 0.] # [ 0. 0. 1.]]))))))) # # # the default Axes transformation is ax.transData # In [269]: print(ax.transData) # CompositeGenericTransform( # TransformWrapper( # BlendedAffine2D( # IdentityTransform(), # IdentityTransform())), # CompositeGenericTransform( # BboxTransformFrom( # TransformedBbox( # Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0), # TransformWrapper( # BlendedAffine2D( # IdentityTransform(), # IdentityTransform())))), # BboxTransformTo( # TransformedBbox( # Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88), # BboxTransformTo( # TransformedBbox( # Bbox(x0=0.0, y0=0.0, x1=6.4, y1=4.8), # Affine2D( # [[100. 0. 0.] # [ 0. 100. 0.] # [ 0. 0. 1.]]))))))) # # # notice that the xlimits of the Axes have not been changed # In [270]: print(ax.get_xlim()) # (0.0, 1.0) # # # but the data limits have been updated to encompass the rectangle # In [271]: print(ax.dataLim.bounds) # (1.0, 1.0, 5.0, 12.0) # # # we can manually invoke the auto-scaling machinery # In [272]: ax.autoscale_view() # # # and now the xlim are updated to encompass the rectangle, plus margins # In [273]: print(ax.get_xlim()) # (0.75, 6.25) # # # we have to manually force a figure draw # In [274]: fig.canvas.draw() # # # There are many, many ``Axes`` helper methods for creating primitive # ``Artists`` and adding them to their respective containers. The table # below summarizes a small sampling of them, the kinds of ``Artist`` they # create, and where they store them # # ========================================= ================= =============== # Axes helper method Artist Container # ========================================= ================= =============== # `~.axes.Axes.annotate` - text annotations `.Annotation` ax.texts # `~.axes.Axes.bar` - bar charts `.Rectangle` ax.patches # `~.axes.Axes.errorbar` - error bar plots `.Line2D` and ax.lines and # `.Rectangle` ax.patches # `~.axes.Axes.fill` - shared area `.Polygon` ax.patches # `~.axes.Axes.hist` - histograms `.Rectangle` ax.patches # `~.axes.Axes.imshow` - image data `.AxesImage` ax.images # `~.axes.Axes.legend` - Axes legend `.Legend` ax.get_legend() # `~.axes.Axes.plot` - xy plots `.Line2D` ax.lines # `~.axes.Axes.scatter` - scatter charts `.PolyCollection` ax.collections # `~.axes.Axes.text` - text `.Text` ax.texts # ========================================= ================= =============== # # # In addition to all of these ``Artists``, the ``Axes`` contains two # important ``Artist`` containers: the :class:`~matplotlib.axis.XAxis` # and :class:`~matplotlib.axis.YAxis`, which handle the drawing of the # ticks and labels. These are stored as instance variables # :attr:`!matplotlib.axes.Axes.xaxis` and # :attr:`!matplotlib.axes.Axes.yaxis`. The ``XAxis`` and ``YAxis`` # containers will be detailed below, but note that the ``Axes`` contains # many helper methods which forward calls on to the # :class:`~matplotlib.axis.Axis` instances, so you often do not need to # work with them directly unless you want to. For example, you can set # the font color of the ``XAxis`` ticklabels using the ``Axes`` helper # method:: # # ax.tick_params(axis='x', labelcolor='orange') # # Below is a summary of the Artists that the `~.axes.Axes` contains # # ============== ========================================= # Axes attribute Description # ============== ========================================= # artists An `.ArtistList` of `.Artist` instances # patch `.Rectangle` instance for Axes background # collections An `.ArtistList` of `.Collection` instances # images An `.ArtistList` of `.AxesImage` # lines An `.ArtistList` of `.Line2D` instances # patches An `.ArtistList` of `.Patch` instances # texts An `.ArtistList` of `.Text` instances # xaxis A `matplotlib.axis.XAxis` instance # yaxis A `matplotlib.axis.YAxis` instance # ============== ========================================= # # The legend can be accessed by `~.axes.Axes.get_legend`, # # .. _axis-container: # # Axis containers # --------------- # # The :class:`matplotlib.axis.Axis` instances handle the drawing of the # tick lines, the grid lines, the tick labels and the axis label. You # can configure the left and right ticks separately for the y-axis, and # the upper and lower ticks separately for the x-axis. The ``Axis`` # also stores the data and view intervals used in auto-scaling, panning # and zooming, as well as the :class:`~matplotlib.ticker.Locator` and # :class:`~matplotlib.ticker.Formatter` instances which control where # the ticks are placed and how they are represented as strings. # # Each ``Axis`` object contains a :attr:`~matplotlib.axis.Axis.label` attribute # (this is what :mod:`.pyplot` modifies in calls to `~.pyplot.xlabel` and # `~.pyplot.ylabel`) as well as a list of major and minor ticks. The ticks are # `.axis.XTick` and `.axis.YTick` instances, which contain the actual line and # text primitives that render the ticks and ticklabels. Because the ticks are # dynamically created as needed (e.g., when panning and zooming), you should # access the lists of major and minor ticks through their accessor methods # `.axis.Axis.get_major_ticks` and `.axis.Axis.get_minor_ticks`. Although # the ticks contain all the primitives and will be covered below, ``Axis`` # instances have accessor methods that return the tick lines, tick labels, tick # locations etc.: fig, ax = plt.subplots() axis = ax.xaxis axis.get_ticklocs() # %% axis.get_ticklabels() # %% # note there are twice as many ticklines as labels because by default there are # tick lines at the top and bottom but only tick labels below the xaxis; # however, this can be customized. axis.get_ticklines() # %% # And with the above methods, you only get lists of major ticks back by # default, but you can also ask for the minor ticks: axis.get_ticklabels(minor=True) axis.get_ticklines(minor=True) # %% # Here is a summary of some of the useful accessor methods of the ``Axis`` # (these have corresponding setters where useful, such as # :meth:`~matplotlib.axis.Axis.set_major_formatter`.) # # ============================= ============================================== # Axis accessor method Description # ============================= ============================================== # `~.Axis.get_scale` The scale of the Axis, e.g., 'log' or 'linear' # `~.Axis.get_view_interval` The interval instance of the Axis view limits # `~.Axis.get_data_interval` The interval instance of the Axis data limits # `~.Axis.get_gridlines` A list of grid lines for the Axis # `~.Axis.get_label` The Axis label - a `.Text` instance # `~.Axis.get_offset_text` The Axis offset text - a `.Text` instance # `~.Axis.get_ticklabels` A list of `.Text` instances - # keyword minor=True|False # `~.Axis.get_ticklines` A list of `.Line2D` instances - # keyword minor=True|False # `~.Axis.get_ticklocs` A list of Tick locations - # keyword minor=True|False # `~.Axis.get_major_locator` The `.ticker.Locator` instance for major ticks # `~.Axis.get_major_formatter` The `.ticker.Formatter` instance for major # ticks # `~.Axis.get_minor_locator` The `.ticker.Locator` instance for minor ticks # `~.Axis.get_minor_formatter` The `.ticker.Formatter` instance for minor # ticks # `~.axis.Axis.get_major_ticks` A list of `.Tick` instances for major ticks # `~.axis.Axis.get_minor_ticks` A list of `.Tick` instances for minor ticks # `~.Axis.grid` Turn the grid on or off for the major or minor # ticks # ============================= ============================================== # # Here is an example, not recommended for its beauty, which customizes # the Axes and Tick properties. # plt.figure creates a matplotlib.figure.Figure instance fig = plt.figure() rect = fig.patch # a rectangle instance rect.set_facecolor('lightgoldenrodyellow') ax1 = fig.add_axes((0.1, 0.3, 0.4, 0.4)) rect = ax1.patch rect.set_facecolor('lightslategray') for label in ax1.xaxis.get_ticklabels(): # label is a Text instance label.set_color('red') label.set_rotation(45) label.set_fontsize(16) for line in ax1.yaxis.get_ticklines(): # line is a Line2D instance line.set_color('green') line.set_markersize(25) line.set_markeredgewidth(3) plt.show() # %% # .. _tick-container: # # Tick containers # --------------- # # The :class:`matplotlib.axis.Tick` is the final container object in our # descent from the :class:`~matplotlib.figure.Figure` to the # :class:`~matplotlib.axes.Axes` to the :class:`~matplotlib.axis.Axis` # to the :class:`~matplotlib.axis.Tick`. The ``Tick`` contains the tick # and grid line instances, as well as the label instances for the upper # and lower ticks. Each of these is accessible directly as an attribute # of the ``Tick``. # # ============== ========================================================== # Tick attribute Description # ============== ========================================================== # tick1line A `.Line2D` instance # tick2line A `.Line2D` instance # gridline A `.Line2D` instance # label1 A `.Text` instance # label2 A `.Text` instance # ============== ========================================================== # # Here is an example which sets the formatter for the right side ticks with # dollar signs and colors them green on the right side of the yaxis. # # # .. include:: ../gallery/ticks/dollar_ticks.rst # :start-after: .. redirect-from:: /gallery/pyplots/dollar_ticks # :end-before: .. admonition:: References
in
python
Textualize__textual
src/textual/css/_help_renderables.py
{ "start": 1828, "end": 2833 }
class ____: """Renderable for help text - the user is shown this when they encounter a style-related error (e.g. setting a style property to an invalid value). Attributes: summary: A succinct summary of the issue. bullets: Bullet points which provide additional context around the issue. These are rendered below the summary. """ def __init__( self, summary: str, *, bullets: Iterable[Bullet] | None = None ) -> None: self.summary: str = summary self.bullets: Iterable[Bullet] | None = bullets or [] def __str__(self) -> str: return self.summary def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: from rich.tree import Tree tree = Tree(_markup_and_highlight(f"[b blue]{self.summary}"), guide_style="dim") if self.bullets is not None: for bullet in self.bullets: tree.add(bullet) yield tree
HelpText
python
eventlet__eventlet
tests/greenthread_test.py
{ "start": 2887, "end": 3533 }
class ____(Spawn): def test_basic(self): gt = greenthread.spawn_after(0.1, passthru, 20) self.assertEqual(gt.wait(), ((20,), {})) def test_cancel(self): gt = greenthread.spawn_after(0.1, passthru, 21) gt.cancel() self.assert_dead(gt) def test_cancel_already_started(self): gt = greenthread.spawn_after(0, waiter, 22) greenthread.sleep(0) gt.cancel() self.assertEqual(gt.wait(), 22) def test_kill_already_started(self): gt = greenthread.spawn_after(0, waiter, 22) greenthread.sleep(0) gt.kill() self.assert_dead(gt)
SpawnAfter
python
pytorch__pytorch
test/dynamo/test_unittest.py
{ "start": 160, "end": 768 }
class ____(torch._dynamo.test_case.TestCase): def setUp(self): self._prev = torch._dynamo.config.enable_trace_unittest torch._dynamo.config.enable_trace_unittest = True def tearDown(self): torch._dynamo.config.enable_trace_unittest = self._prev @make_dynamo_test def test_SkipTest(self): z = 0 SkipTest = unittest.SkipTest try: raise SkipTest("abcd") except Exception: z = 1 self.assertEqual(z, 1) if __name__ == "__main__": from torch._dynamo.test_case import run_tests run_tests()
TestUnittest
python
ApeWorX__ape
tests/integration/cli/conftest.py
{ "start": 330, "end": 5277 }
class ____: """ A test module in 'tests.integration.cli'. """ def __init__(self, path: Path): self._path = path module = import_module(f"tests.integration.cli.{path.stem}") test_methods = [ getattr(module, t) for t in dir(module) if t.startswith("test_") and hasattr(t, "__name__") and hasattr(t, "__module__") ] self.tests = [NodeId(t) for t in test_methods] def __iter__(self): return iter(self.tests) @property def name(self) -> str: """ The name of the module. """ return self._path.stem # Loads the actual test modules / methods integration_tests = [ IntegrationTestModule(p) for p in Path(__file__).parent.iterdir() if p.suffix == ".py" and p.name.startswith("test_") ] @pytest.hookimpl(trylast=True) def pytest_collection_modifyitems(session, config, items): """ Filter out tests marked to be skipped using ``skip_projects`` and the ``skip_projects_except`` decorators. """ modified_items = [] for item in items: item_name_parts = item.name.split("[") item_name_parts = [p.strip("[]") for p in item_name_parts] module_full_name = getattr(item.module, "__name__", None) if not module_full_name: continue module_name = module_full_name.split(".")[-1] test_name = item_name_parts[0] # Handle if a parametrized test is on-top # of the project's parametrization. project_name = item_name_parts[-1] for proj_name in project_skipper: # Example: 'test_foo[project-name-fuzz-0]' matches 'project-name' if project_name.startswith(proj_name): project_name = proj_name break is_cli_integration_test = ( len(item_name_parts) == 2 and "integration.cli" in module_full_name ) if not is_cli_integration_test or not project_skipper.do_skip( project_name, module_name, test_name ): modified_items.append(item) items[:] = modified_items @pytest.fixture(autouse=True, scope="session") def project_dir_map(): """ Ensure only copying projects once to prevent `TooManyOpenFilesError`. """ class ProjectDirCache: project_map: dict[str, Path] = {} def load(self, name: str) -> Path: base_path = Path(__file__).parent / "projects" if name in self.project_map: res = self.project_map[name] if res.is_dir(): # Already copied and still exists! return res # Either re-copy or copy for the first time. project_source_dir = __projects_directory__ / name project_dest_dir = base_path / project_source_dir.name project_dest_dir.parent.mkdir(exist_ok=True, parents=True) if not project_dest_dir.is_dir(): copytree(project_source_dir, project_dest_dir) self.project_map[name] = project_dest_dir return self.project_map[name] return ProjectDirCache() @pytest.fixture(autouse=True, params=__project_names__) def integ_project(request, project_dir_map): project_dir = project_dir_map.load(request.param) if not project_dir.is_dir(): # Should not happen because of logic in fixture, # but just in case! pytest.fail("Setup failed - project dir not exists.") root_project = Project(project_dir) # Using tmp project so no .build folder get kept around. with root_project.isolate_in_tempdir(name=request.param) as tmp_project: assert tmp_project.path.is_dir(), "Setup failed - tmp-project dir not exists" yield tmp_project @pytest.fixture(scope="session") def ape_cli(): from ape._cli import cli return cli def assert_failure(result, expected_output): assert result.exit_code == 1 assert result.exception is not None assert "ERROR" in result.output assert expected_output in result.output @pytest.fixture def clean_cache(integ_project): """ Use this fixture to ensure a project does not have a cached compilation. """ integ_project.clean() yield integ_project.clean() @pytest.fixture(scope="session") def ape_plugins_runner(config): """ Use subprocess runner so can manipulate site packages and see results. """ class PluginSubprocessRunner(ApeSubprocessRunner): def __init__(self): super().__init__("plugins", data_folder=config.DATA_FOLDER) def invoke_list(self, arguments: Optional[list] = None): arguments = arguments or [] result = self.invoke("list", *arguments) assert result.exit_code == 0, result.output return ListResult.parse_output(result.output) return PluginSubprocessRunner()
IntegrationTestModule
python
cython__cython
tests/run/ext_auto_richcmp.py
{ "start": 4301, "end": 4925 }
class ____(ClassEqNeGe): """ >>> a = ClassRichcmpOverride(1) >>> b = ClassRichcmpOverride(1) >>> a == a True >>> a != a False >>> a != b if compiled else a == b # Python ignores __richcmp__() True >>> a == b if compiled else a != b # Python ignores __richcmp__() False >>> if not compiled: raise TypeError # doctest: +ELLIPSIS ... else: a >= b # should no longer work when __richcmp__ is overwritten Traceback (most recent call last): TypeError... """ def __richcmp__(self, other, op): return NotImplemented @cython.cclass
ClassRichcmpOverride
python
mlflow__mlflow
mlflow/tensorflow/callback.py
{ "start": 271, "end": 3966 }
class ____(keras.callbacks.Callback, metaclass=ExceptionSafeClass): """Callback for logging Tensorflow training metrics to MLflow. This callback logs model information at training start, and logs training metrics every epoch or every n steps (defined by the user) to MLflow. Args: log_every_epoch: bool, If True, log metrics every epoch. If False, log metrics every n steps. log_every_n_steps: int, log metrics every n steps. If None, log metrics every epoch. Must be `None` if `log_every_epoch=True`. .. code-block:: python :caption: Example from tensorflow import keras import mlflow import numpy as np # Prepare data for a 2-class classification. data = tf.random.uniform([8, 28, 28, 3]) label = tf.convert_to_tensor(np.random.randint(2, size=8)) model = keras.Sequential( [ keras.Input([28, 28, 3]), keras.layers.Flatten(), keras.layers.Dense(2), ] ) model.compile( loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=keras.optimizers.Adam(0.001), metrics=[keras.metrics.SparseCategoricalAccuracy()], ) with mlflow.start_run() as run: model.fit( data, label, batch_size=4, epochs=2, callbacks=[mlflow.keras.MlflowCallback(run)], ) """ def __init__(self, log_every_epoch=True, log_every_n_steps=None): self.log_every_epoch = log_every_epoch self.log_every_n_steps = log_every_n_steps if log_every_epoch and log_every_n_steps is not None: raise ValueError( "`log_every_n_steps` must be None if `log_every_epoch=True`, received " f"`log_every_epoch={log_every_epoch}` and `log_every_n_steps={log_every_n_steps}`." ) if not log_every_epoch and log_every_n_steps is None: raise ValueError( "`log_every_n_steps` must be specified if `log_every_epoch=False`, received" "`log_every_n_steps=False` and `log_every_n_steps=None`." ) def on_train_begin(self, logs=None): """Log model architecture and optimizer configuration when training begins.""" config = self.model.optimizer.get_config() log_params({f"opt_{k}": v for k, v in config.items()}) model_summary = [] def print_fn(line, *args, **kwargs): model_summary.append(line) self.model.summary(print_fn=print_fn) summary = "\n".join(model_summary) log_text(summary, artifact_file="model_summary.txt") def on_epoch_end(self, epoch, logs=None): """Log metrics at the end of each epoch.""" if not self.log_every_epoch or logs is None: return log_metrics(logs, step=epoch, synchronous=False) def on_batch_end(self, batch, logs=None): """Log metrics at the end of each batch with user specified frequency.""" if self.log_every_n_steps is None or logs is None: return current_iteration = int(self.model.optimizer.iterations.numpy()) if current_iteration % self.log_every_n_steps == 0: log_metrics(logs, step=current_iteration, synchronous=False) def on_test_end(self, logs=None): """Log validation metrics at validation end.""" if logs is None: return metrics = {"validation_" + k: v for k, v in logs.items()} log_metrics(metrics, synchronous=False)
MlflowCallback
python
pytorch__pytorch
test/distributed/_composable/test_replicate.py
{ "start": 2619, "end": 9232 }
class ____(MultiProcessTestCase): @property def world_size(self) -> int: return 2 def setUp(self) -> None: super().setUp() self._spawn_processes() def tearDown(self): super().tearDown() try: os.remove(self.file_name) except OSError: pass def _init_pg(self): dist.init_process_group( backend="gloo", rank=self.rank, world_size=self.world_size, store=dist.FileStore(self.file_name, self.world_size), ) def _compare_module(self, mod, replicate_mod): local_batch_size = 1 global_batch_size = self.world_size * local_batch_size input = torch.randn(global_batch_size, 2) target = torch.randn(global_batch_size, 2) def step_model(model, input, target): model.train() output = model(input) loss = F.mse_loss(output, target.to(output.device)) loss.backward() for param in model.parameters(): with torch.no_grad(): param -= param.grad param.grad = None for iteration in range(2): step_model(mod, input, target) step_model( replicate_mod, input[ self.rank * local_batch_size : (self.rank + 1) * local_batch_size ], target[ self.rank * local_batch_size : (self.rank + 1) * local_batch_size ], ) self.assertEqual( len(list(mod.parameters())), len(list(replicate_mod.parameters())), ) for i, j in zip(mod.parameters(), replicate_mod.parameters()): self.assertEqual(i, j, rtol=1.3e-06, atol=5e-5) # Shuffle the input so that DDP input is different torch.manual_seed(iteration) input = input[torch.randperm(global_batch_size)] def test_replicate_single_module(self): self._init_pg() model = Net() replicate_model = replicate(deepcopy(model)) self._compare_module(model, replicate_model) @skip_if_lt_x_gpu(2) @unittest.skipIf(TEST_XPU, "XPU does not support gloo backend") def test_replicate_move_args_kwargs_to_device(self): class MyNet(nn.Module): def __init__(self) -> None: super().__init__() self.a = nn.Linear(2, 2) def forward(self, inp, *, kwarg=None): if kwarg is not None: inp = inp @ kwarg return self.a(inp) self._init_pg() torch.accelerator.set_device_index(self.rank) model = MyNet().to(device_type) replicate(model, device_id=torch.accelerator.current_device_index()) # CPU input ensures replicate can move arg and kwargs to device. a, b = torch.randn(2, 2), torch.randn(2, 2) model(a, kwarg=b).sum().backward() @skip_if_lt_x_gpu(2) @unittest.skipIf(TEST_XPU, "XPU does not support gloo backend") def test_replicate_ignore_module(self): self._init_pg() torch.accelerator.set_device_index(self.rank) # Seed ensures diff input and thus different local grads across ranks. torch.manual_seed(self.rank) device_module.manual_seed(self.rank) model = Net().to(device_type) replicate(model, ignored_modules=[model.fc1]) # CPU input ensures that replicate can move input to GPU as DDP does. inp = torch.randn(5, 2, device=device_type) * (self.rank + 1) out = model(inp) * 10 out.sum().backward() # FC1 grads should not be synchronized, FC2 and 3 should be. fc1_grad = model.fc1.weight.grad tensor_list = [torch.zeros_like(fc1_grad) for _ in range(dist.get_world_size())] dist.all_gather(tensor_list, fc1_grad) grad, rest = tensor_list[0], tensor_list[1:] for g in rest: self.assertNotEqual(grad, g) for dp_grad in [model.fc2.weight.grad, model.fc3.weight.grad]: tensor_list = [ torch.zeros_like(dp_grad) for _ in range(dist.get_world_size()) ] dist.all_gather(tensor_list, dp_grad) grad, rest = tensor_list[0], tensor_list[1:] for g in rest: self.assertEqual(grad, g) def test_replicate_multi_module(self): self._init_pg() model = Net() replicate_model = deepcopy(model) replicate(replicate_model.fc1) replicate(replicate_model.fc2) replicate(replicate_model.fc3) self._compare_module(model, replicate_model) def test_replicate_with_kwargs(self): self._init_pg() model = Net() replicate_model = replicate( deepcopy(model), bucket_cap_mb=1, gradient_as_bucket_view=True ) self._compare_module(model, replicate_model) @skip_if_lt_x_gpu(2) @unittest.skipIf(TEST_XPU, "XPU does not support gloo backend") def test_replicate_device_id(self): self._init_pg() model = Net() model_cuda = deepcopy(model).to(device_type) model_cuda2 = deepcopy(model_cuda) replicate(model, device_id=torch.device("cpu")) # DDP instance is attached in first pre forward model(torch.randn(2, 2)) replicate_ddp_weakref = replicate.state(model)._ddp_weakref() # Should be None for CPU training self.assertEqual(None, replicate_ddp_weakref.device_ids) replicate( model_cuda, device_id=torch.device(torch.accelerator.current_device_index()) ) # DDP instance is attached in first pre forward model_cuda(torch.randn(2, 2)) replicate_ddp_weakref = replicate.state(model_cuda)._ddp_weakref() self.assertEqual([0], replicate_ddp_weakref.device_ids) # Pass in int as device_id replicate(model_cuda2, device_id=int(torch.accelerator.current_device_index())) # DDP instance is attached in first pre forward model_cuda2(torch.randn(2, 2)) replicate_ddp_weakref = replicate.state(model_cuda2)._ddp_weakref() self.assertEqual([0], replicate_ddp_weakref.device_ids) def test_replicate_wrong_device_id_type(self): self._init_pg() model = Net() with self.assertRaisesRegex( RuntimeError, "Expected device_id to be int or torch.device" ): replicate(model, device_id=[torch.device("cpu")])
ReplicateTest
python
scrapy__scrapy
tests/spiders.py
{ "start": 3734, "end": 3924 }
class ____(SimpleSpider): name = "asyncdef" async def parse(self, response): await defer.succeed(42) self.logger.info(f"Got response {response.status}")
AsyncDefSpider
python
dask__distributed
distributed/recreate_tasks.py
{ "start": 1276, "end": 7061 }
class ____: """ A plugin for the client allowing replay of remote tasks locally Adds the following methods to the given client: - ``recreate_error_locally``: main user method for replaying failed tasks - ``recreate_task_locally``: main user method for replaying any task """ def __init__(self, client): self.client = client self.client.extensions["replay-tasks"] = self # monkey patch self.client._get_raw_components_from_future = self._get_task_runspec self.client._prepare_raw_components = self._get_dependencies self.client._get_components_from_future = self._get_components_from_future self.client._get_errored_future = self._get_errored_future self.client.recreate_task_locally = self.recreate_task_locally self.client.recreate_error_locally = self.recreate_error_locally @property def scheduler(self): return self.client.scheduler async def _get_task_runspec(self, future): """ For a given future return the func, args and kwargs and future deps that would be executed remotely. """ if isinstance(future, Future): await wait(future) key = future.key else: validate_key(future) key = future run_spec = await self.scheduler.get_runspec(key=key) return run_spec async def _get_dependencies(self, dependencies): """ Take raw components and resolve future dependencies. """ futures = self.client._graph_to_futures({}, dependencies, span_metadata={}) data = await self.client._gather(futures) return data async def _get_components_from_future(self, future): """ For a given future return the func, args and kwargs that would be executed remotely. Any args/kwargs that are themselves futures will be resolved to the return value of those futures. """ runspec = await self._get_task_runspec(future) return runspec, await self._get_dependencies(runspec.dependencies) def recreate_task_locally(self, future): """ For any calculation, whether it succeeded or failed, perform the task locally for debugging. This operation should be performed after a future (result of ``gather``, ``compute``, etc) comes back with a status other than "pending". Cases where you might want to debug a successfully completed future could include a calculation that returns an unexpected results. A common debugging process might include running the task locally in debug mode, with `pdb.runcall`. Examples -------- >>> import pdb # doctest: +SKIP >>> future = c.submit(div, 1, 1) # doctest: +SKIP >>> future.status # doctest: +SKIP 'finished' >>> pdb.runcall(c.recreate_task_locally, future) # doctest: +SKIP Parameters ---------- future : future The same thing as was given to ``gather``. Returns ------- Any; will return the result of the task future. """ runspec, dependencies = sync( self.client.loop, self._get_components_from_future, future ) return runspec(dependencies) async def _get_errored_future(self, future): """ For a given future collection, return the first future that raised an error. """ await wait(future) futures = [f.key for f in futures_of(future) if f.status == "error"] if not futures: raise ValueError("No errored futures passed") cause_key = await self.scheduler.get_error_cause(keys=futures) return cause_key def recreate_error_locally(self, future): """ For a failed calculation, perform the blamed task locally for debugging. This operation should be performed after a future (result of ``gather``, ``compute``, etc) comes back with a status of "error", if the stack- trace is not informative enough to diagnose the problem. The specific task (part of the graph pointing to the future) responsible for the error will be fetched from the scheduler, together with the values of its inputs. The function will then be executed, so that ``pdb`` can be used for debugging. Examples -------- >>> future = c.submit(div, 1, 0) # doctest: +SKIP >>> future.status # doctest: +SKIP 'error' >>> c.recreate_error_locally(future) # doctest: +SKIP ZeroDivisionError: division by zero If you're in IPython you might take this opportunity to use pdb >>> %pdb # doctest: +SKIP Automatic pdb calling has been turned ON >>> c.recreate_error_locally(future) # doctest: +SKIP ZeroDivisionError: division by zero 1 def div(x, y): ----> 2 return x / y ipdb> Parameters ---------- future : future or collection that failed The same thing as was given to ``gather``, but came back with an exception/stack-trace. Can also be a (persisted) dask collection containing any errored futures. Returns ------- Nothing; the function runs and should raise an exception, allowing the debugger to run. """ errored_future_key = sync(self.client.loop, self._get_errored_future, future) return self.recreate_task_locally(errored_future_key)
ReplayTaskClient
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 916265, "end": 916635 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("Ref", graphql_name="node") """The item at the end of the edge."""
RefEdge
python
ray-project__ray
python/ray/data/aggregate.py
{ "start": 34968, "end": 42380 }
class ____(AggregateFnV2): """Counts the number of times each value appears in a column. This aggregation computes value counts for a specified column, similar to pandas' `value_counts()` method. It returns a dictionary with two lists: "values" containing the unique values found in the column, and "counts" containing the corresponding count for each value. Example: .. testcode:: import ray from ray.data.aggregate import ValueCounter # Create a dataset with repeated values ds = ray.data.from_items([ {"category": "A"}, {"category": "B"}, {"category": "A"}, {"category": "C"}, {"category": "A"}, {"category": "B"} ]) # Count occurrences of each category result = ds.aggregate(ValueCounter(on="category")) # result: {'value_counter(category)': {'values': ['A', 'B', 'C'], 'counts': [3, 2, 1]}} # Using with groupby ds = ray.data.from_items([ {"group": "X", "category": "A"}, {"group": "X", "category": "B"}, {"group": "Y", "category": "A"}, {"group": "Y", "category": "A"} ]) result = ds.groupby("group").aggregate(ValueCounter(on="category")).take_all() # result: [{'group': 'X', 'value_counter(category)': {'values': ['A', 'B'], 'counts': [1, 1]}}, # {'group': 'Y', 'value_counter(category)': {'values': ['A'], 'counts': [2]}}] Args: on: The name of the column to count values in. Must be provided. alias_name: Optional name for the resulting column. If not provided, defaults to "value_counter({column_name})". """ def __init__( self, on: str, alias_name: Optional[str] = None, ): super().__init__( alias_name if alias_name else f"value_counter({str(on)})", on=on, ignore_nulls=True, zero_factory=lambda: {"values": [], "counts": []}, ) def aggregate_block(self, block: Block) -> Dict[str, List]: col_accessor = BlockColumnAccessor.for_column(block[self._target_col_name]) return col_accessor.value_counts() def combine( self, current_accumulator: Dict[str, List], new_accumulator: Dict[str, List], ) -> Dict[str, List]: values = current_accumulator["values"] counts = current_accumulator["counts"] # Build a value → index map once (avoid repeated lookups) value_to_index = {v: i for i, v in enumerate(values)} for v_new, c_new in zip(new_accumulator["values"], new_accumulator["counts"]): if v_new in value_to_index: idx = value_to_index[v_new] counts[idx] += c_new else: value_to_index[v_new] = len(values) values.append(v_new) counts.append(c_new) return current_accumulator def _null_safe_zero_factory(zero_factory, ignore_nulls: bool): """NOTE: PLEASE READ CAREFULLY BEFORE CHANGING Null-safe zero factory is crucial for implementing proper aggregation protocol (monoid) w/o the need for additional containers. Main hurdle for implementing proper aggregation semantic is to be able to encode semantic of an "empty accumulator" and be able to tell it from the case when accumulator is actually holding null value: - Empty container can be overridden with any value - Container holding null can't be overridden if ignore_nulls=False However, it's possible for us to exploit asymmetry in cases of ignore_nulls being True or False: - Case of ignore_nulls=False entails that if there's any "null" in the sequence, aggregation is undefined and correspondingly expected to return null - Case of ignore_nulls=True in turn, entails that if aggregation returns "null" if and only if the sequence does NOT have any non-null value Therefore, we apply this difference in semantic to zero-factory to make sure that our aggregation protocol is adherent to that definition: - If ignore_nulls=True, zero-factory returns null, therefore encoding empty container - If ignore_nulls=False, couldn't return null as aggregation will incorrectly prioritize it, and instead it returns true zero value for the aggregation (ie 0 for count/sum, -inf for max, etc). """ if ignore_nulls: def _safe_zero_factory(_): return None else: def _safe_zero_factory(_): return zero_factory() return _safe_zero_factory def _null_safe_aggregate( aggregate: Callable[[Block], AccumulatorType], ignore_nulls: bool, ) -> Callable[[Block], Optional[AccumulatorType]]: def _safe_aggregate(block: Block) -> Optional[AccumulatorType]: result = aggregate(block) # NOTE: If `ignore_nulls=True`, aggregation will only be returning # null if the block does NOT contain any non-null elements if is_null(result) and ignore_nulls: return None return result return _safe_aggregate def _null_safe_finalize( finalize: Callable[[AccumulatorType], AccumulatorType], ) -> Callable[[Optional[AccumulatorType]], AccumulatorType]: def _safe_finalize(acc: Optional[AccumulatorType]) -> AccumulatorType: # If accumulator container is not null, finalize. # Otherwise, return as is. return acc if is_null(acc) else finalize(acc) return _safe_finalize def _null_safe_combine( combine: Callable[[AccumulatorType, AccumulatorType], AccumulatorType], ignore_nulls: bool, ) -> Callable[ [Optional[AccumulatorType], Optional[AccumulatorType]], Optional[AccumulatorType] ]: """Null-safe combination have to be an associative operation with an identity element (zero) or in other words implement a monoid. To achieve that in the presence of null values following semantic is established: - Case of ignore_nulls=True: - If current accumulator is null (ie empty), return new accumulator - If new accumulator is null (ie empty), return cur - Otherwise combine (current and new) - Case of ignore_nulls=False: - If new accumulator is null (ie has null in the sequence, b/c we're NOT ignoring nulls), return it - If current accumulator is null (ie had null in the prior sequence, b/c we're NOT ignoring nulls), return it - Otherwise combine (current and new) """ if ignore_nulls: def _safe_combine( cur: Optional[AccumulatorType], new: Optional[AccumulatorType] ) -> Optional[AccumulatorType]: if is_null(cur): return new elif is_null(new): return cur else: return combine(cur, new) else: def _safe_combine( cur: Optional[AccumulatorType], new: Optional[AccumulatorType] ) -> Optional[AccumulatorType]: if is_null(new): return new elif is_null(cur): return cur else: return combine(cur, new) return _safe_combine @PublicAPI(stability="alpha")
ValueCounter
python
numpy__numpy
numpy/lib/tests/test_type_check.py
{ "start": 14458, "end": 14796 }
class ____: def test_basic(self): a = np.random.rand(10) b = real_if_close(a + 1e-15j) assert_all(isrealobj(b)) assert_array_equal(a, b) b = real_if_close(a + 1e-7j) assert_all(iscomplexobj(b)) b = real_if_close(a + 1e-7j, tol=1e-6) assert_all(isrealobj(b))
TestRealIfClose
python
kamyu104__LeetCode-Solutions
Python/manhattan-distances-of-all-arrangements-of-pieces.py
{ "start": 508, "end": 975 }
class ____(object): def distanceSum(self, m, n, k): """ :type m: int :type n: int :type k: int :rtype: int """ def sum_n(n): return (n+1)*n//2 def sum_n_square(n): return n*(n+1)*(2*n+1)//6 def f(n): # sum((d*(n-d) for d in xrange(1, n))) return (n*sum_n(n-1)-sum_n_square(n-1)) return (f(n)*m*m+f(m)*n*n)*nCr(m*n-2, k-2)%MOD
Solution
python
huggingface__transformers
src/transformers/quantizers/quantizer_fp_quant.py
{ "start": 1072, "end": 7664 }
class ____(HfQuantizer): """ Quantizer for the FP-Quant method. Enables the loading of prequantized models and in-flight quantization of full-precision models. """ requires_calibration = False requires_parameters_quantization = True is_qat_trainable = True required_packages = ["fp_quant"] def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs): super().__init__(quantization_config, **kwargs) self.quantization_config = quantization_config def validate_environment(self, device_map, **kwargs): if not torch.cuda.is_available() and not is_torch_xpu_available(): raise NotImplementedError( "FPQuant quantization is only supported on GPU or Intel XPU. Please use a different quantizer." ) if not is_qutlass_available() and not self.quantization_config.pseudoquantization: raise ImportError( "Using `fp_quant` with real quantization requires a **Blackwell GPU** and qutlass: `git clone https://github.com/IST-DASLab/qutlass.git && cd qutlass && pip install --no-build-isolation .`. You can use `FPQuantConfig(pseudoquantization=True, ...)` to use Triton-based pseudo-quantization. It doesn't provide any speedups but emulates the quantization behavior of the real quantization." ) if self.quantization_config.pseudoquantization: logger.warning( "Using pseudo-quantization for FP-Quant. This doesn't provide any speedups but emulates the quantization behavior of the real quantization." ) if not is_fp_quant_available(): raise ImportError("Using `fp_quant` quantization requires fp_quant: `pip install fp_quant`") if device_map is None and not self.quantization_config.pseudoquantization: raise ValueError( "You are attempting to load a FPQuant model without setting device_map." " Please set device_map comprised of 'cuda' devices." ) elif ( isinstance(device_map, dict) and ("cpu" in device_map.values() or "disk" in device_map.values()) and not self.quantization_config.pseudoquantization ): raise ValueError( "You are attempting to load a FPQuant model with a device_map that contains a CPU or disk device." " This is not supported. Please remove the CPU or disk device from the device_map." ) def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype": if dtype is None: logger.info("`dtype` is None. Setting `dtype=torch.bfloat16` for qutlass compatibility.") dtype = torch.bfloat16 elif dtype != torch.bfloat16: raise ValueError(f"Invalid `dtype` {dtype}. fp_quant quantization only supports `dtype=torch.bfloat16`.") return dtype def create_quantized_param( self, model: "PreTrainedModel", param_value: "torch.Tensor", param_name: str, target_device: "torch.device", **kwargs, ): module, _ = get_module_from_name(model, param_name) if target_device == "cpu" and param_name.endswith("weight"): # Works agains hard-coded missing key dispatch to CPU return # The module holds either: # * `weight` when `store_master_weights=True` # * `qweight` and `scales` when `store_master_weights=False` and `pseudoquantization=False` # * `dqweight` when `store_master_weights=False` and `pseudoquantization=True` if param_name.endswith(".qweight"): # Loading a real quantized checkpoint without master weights module.qweight = torch.nn.Parameter( param_value.to(target_device), requires_grad=False, ) module.weight = None module.dqweight = None return if param_name.endswith(".dqweight"): # Loading a pseudo-quantized checkpoint without master weights module.dqweight = torch.nn.Parameter(param_value.to(target_device)) module.weight = None module.qweight = None module.scales = None return # Loading master weights or an unquantized checkpoint module.weight = torch.nn.Parameter(param_value.to(target_device)) # Let pre-forward handle the quantization and set None where necessary module.pre_forward() def _process_model_before_weight_loading( self, model: "PreTrainedModel", **kwargs, ): from fp_quant import replace_with_fp_quant_linear from ..integrations.fp_quant import adapt_fp_quant_config replace_with_fp_quant_linear( model, fp_quant_linear_config=adapt_fp_quant_config(self.quantization_config), ) model.config.quantization_config = self.quantization_config def update_missing_keys(self, model, missing_keys: list[str], prefix: str) -> list[str]: from fp_quant import FPQuantLinear fp_quant_names = {name for name, module in model.named_modules() if isinstance(module, FPQuantLinear)} def should_exclude(key: str) -> bool: if key.endswith(".weight") or key.endswith(".bias"): return False full_key = f"{prefix}.{key}" return any(name in key or name in full_key for name in fp_quant_names) return [key for key in missing_keys if not should_exclude(key)] @property def is_trainable(self, model: Optional["PreTrainedModel"] = None): trainable = self.quantization_config.store_master_weights if not trainable: logger.warning( "You are attempting to train a model with FPQuant quantization. This is only supported when `store_master_weights=True`. Please set `store_master_weights=True` to train the model." ) return trainable def is_serializable(self, safe_serialization=None): return True def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool: from fp_quant import FPQuantLinear module, tensor_name = get_module_from_name(model, param_name) if isinstance(module, FPQuantLinear) and tensor_name in ["weight", "qweight", "dqweight"]: # Only quantize weights of FPQuantLinear modules that are not already quantized return True else: return False
FPQuantHfQuantizer
python
django__django
tests/admin_scripts/tests.py
{ "start": 16627, "end": 20145 }
class ____(AdminScriptTestCase): """ A series of tests for django-admin when using a settings.py file that doesn't contain the test application. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) def test_builtin_command(self): """ minimal: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ minimal: django-admin builtin commands fail if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): """ minimal: django-admin builtin commands fail if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): """ minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ minimal: django-admin can't execute user commands unless settings are provided """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ minimal: django-admin can't execute user commands, even if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): """ minimal: django-admin can't execute user commands, even if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'")
DjangoAdminMinimalSettings
python
huggingface__transformers
src/transformers/models/edgetam/modeling_edgetam.py
{ "start": 21559, "end": 22729 }
class ____(nn.Module): def __init__(self, config: EdgeTamPromptEncoderConfig): super().__init__() self.scale = config.scale positional_embedding = self.scale * torch.randn((2, config.hidden_size // 2)) self.register_buffer("positional_embedding", positional_embedding) def forward(self, input_coords, input_shape=None): """Positionally encode points that are normalized to [0,1].""" coordinates = input_coords.clone() if input_shape is not None: coordinates[:, :, :, 0] = coordinates[:, :, :, 0] / input_shape[1] coordinates[:, :, :, 1] = coordinates[:, :, :, 1] / input_shape[0] coordinates.to(torch.float32) # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape coordinates = 2 * coordinates - 1 coordinates = coordinates.to(self.positional_embedding.dtype) coordinates = coordinates @ self.positional_embedding coordinates = 2 * np.pi * coordinates # outputs d_1 x ... x d_n x channel shape return torch.cat([torch.sin(coordinates), torch.cos(coordinates)], dim=-1)
EdgeTamPositionalEmbedding
python
getsentry__sentry
tests/sentry/plugins/test_config.py
{ "start": 171, "end": 515 }
class ____(forms.Form): text = forms.CharField(help_text="text field") textarea = forms.CharField(widget=forms.Textarea, required=False) password = forms.CharField(label="A Password", widget=forms.PasswordInput) choice = forms.ChoiceField(choices=((1, "one"), (2, "two"))) url = forms.URLField(assume_scheme="https")
DummyForm
python
pallets__jinja
src/jinja2/exceptions.py
{ "start": 4742, "end": 4885 }
class ____(TemplateRuntimeError): """Raised if a template tries to do something insecure if the sandbox is enabled. """
SecurityError
python
getsentry__sentry
src/sentry/models/grouphashmetadata.py
{ "start": 1310, "end": 3065 }
class ____(models.TextChoices): # Message logged by `capture_message`, or exception type and value (when there's no stack or # when all frames have been ruled out by stacktrace rules) MESSAGE = "message" # Either in-app or full stacktrace STACKTRACE = "stacktrace" # Custom fingerprint set by the client, by custom server-side rules, or by built-in server-side # rules. Does NOT include hybrid fingerprints, which are classified by their `{{ default }}` # half, i.e., the grouping method used before consideration of the custom value FINGERPRINT = "fingerprint" # Browser-reported security violation (CSP, expect-ct, expect-staple, HPKP), which is grouped # by the type of rule which was violated and the domain which violated it SECURITY_VIOLATION = "violation" # Error thrown when rendering templates # # TODO: This feature seems unique to the Django integration, the relay event schema contains a # note saying the `template` entry in events is deprecated, and the python SDK doesn't send # anything under that key - all of which suggests this may be vestigal. Once we have metrics on # how often we use each of these, it's possible this could go away. TEMPLATE = "template" # Legacy-legacy grouping method, wherein the client sets the hash directly, under the key `checksum` # # TODO: This, too, may or may not still be operative. CHECKSUM = "checksum" # A single bucket in each project where we throw events which can't be grouped any other way FALLBACK = "fallback" # Not a real variant category. If any records show up with this value, it means there's a bug in # our categorization logic. UNKNOWN = "unknown" @region_silo_model
HashBasis
python
astropy__astropy
astropy/cosmology/_src/flrw/w0cdm.py
{ "start": 7892, "end": 13358 }
class ____(FlatFLRWMixin, wCDM): """FLRW cosmology with a constant dark energy EoS and no spatial curvature. This has one additional attribute beyond those of FLRW. Parameters ---------- H0 : float or scalar quantity-like ['frequency'] Hubble constant at z = 0. If a float, must be in [km/sec/Mpc]. Om0 : float Omega matter: density of non-relativistic matter in units of the critical density at z=0. w0 : float, optional Dark energy equation of state at all redshifts. This is pressure/density for dark energy in units where c=1. A cosmological constant has w0=-1.0. Tcmb0 : float or scalar quantity-like ['temperature'], optional Temperature of the CMB z=0. If a float, must be in [K]. Default: 0 [K]. Setting this to zero will turn off both photons and neutrinos (even massive ones). Neff : float, optional Effective number of Neutrino species. Default 3.04. m_nu : quantity-like ['energy', 'mass'] or array-like, optional Mass of each neutrino species in [eV] (mass-energy equivalency enabled). If this is a scalar Quantity, then all neutrino species are assumed to have that mass. Otherwise, the mass of each species. The actual number of neutrino species (and hence the number of elements of m_nu if it is not scalar) must be the floor of Neff. Typically this means you should provide three neutrino masses unless you are considering something like a sterile neutrino. Ob0 : float, optional Omega baryons: density of baryonic matter in units of the critical density at z=0. name : str or None (optional, keyword-only) Name for this cosmological object. meta : mapping or None (optional, keyword-only) Metadata for the cosmology, e.g., a reference. Examples -------- >>> from astropy.cosmology import FlatwCDM >>> cosmo = FlatwCDM(H0=70, Om0=0.3, w0=-0.9) The comoving distance in Mpc at redshift z: >>> z = 0.5 >>> dc = cosmo.comoving_distance(z) To get an equivalent cosmology, but of type `astropy.cosmology.wCDM`, use :attr:`astropy.cosmology.FlatFLRWMixin.nonflat`. >>> print(cosmo.nonflat) wCDM(H0=70.0 km / (Mpc s), Om0=0.3, Ode0=0.7, ... """ def __post_init__(self) -> None: super().__post_init__() # Please see :ref:`astropy-cosmology-fast-integrals` for discussion # about what is being done here. if self.Tcmb0.value == 0: inv_efunc_scalar = scalar_inv_efuncs.fwcdm_inv_efunc_norel inv_efunc_scalar_args = (self.Om0, self.Ode0, self.w0) elif not self._nu_info.has_massive_nu: inv_efunc_scalar = scalar_inv_efuncs.fwcdm_inv_efunc_nomnu inv_efunc_scalar_args = ( self.Om0, self.Ode0, self.Ogamma0 + self.Onu0, self.w0, ) else: inv_efunc_scalar = scalar_inv_efuncs.fwcdm_inv_efunc inv_efunc_scalar_args = ( self.Om0, self.Ode0, self.Ogamma0, self._nu_info.neff_per_nu, self._nu_info.n_massless_nu, self._nu_info.nu_y_list, self.w0, ) object.__setattr__(self, "_inv_efunc_scalar", inv_efunc_scalar) object.__setattr__(self, "_inv_efunc_scalar_args", inv_efunc_scalar_args) def efunc(self, z: Quantity | ArrayLike, /) -> FArray: """Function used to calculate H(z), the Hubble parameter. Parameters ---------- z : Quantity-like ['redshift'], array-like Input redshift. .. versionchanged:: 7.0 Passing z as a keyword argument is deprecated. .. versionchanged:: 8.0 z must be a positional argument. Returns ------- E : ndarray The redshift scaling of the Hubble constant. Defined such that :math:`H(z) = H_0 E(z)`. """ Or = self.Ogamma0 + ( self.Onu0 if not self._nu_info.has_massive_nu else self.Ogamma0 * self.nu_relative_density(z) ) zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless]) return sqrt( zp1**3 * (Or * zp1 + self.Om0) + self.Ode0 * zp1 ** (3.0 * (1 + self.w0)) ) def inv_efunc(self, z: Quantity | ArrayLike, /) -> FArray: r"""Function used to calculate :math:`\frac{1}{H_z}`. Parameters ---------- z : Quantity-like ['redshift'], array-like Input redshift. .. versionchanged:: 7.0 Passing z as a keyword argument is deprecated. .. versionchanged:: 8.0 z must be a positional argument. Returns ------- E : ndarray The inverse redshift scaling of the Hubble constant. Defined such that :math:`H(z) = H_0 E(z)`. """ Or = self.Ogamma0 + ( self.Onu0 if not self._nu_info.has_massive_nu else self.Ogamma0 * self.nu_relative_density(z) ) zp1 = aszarr(z) + 1.0 # (converts z [unit] -> z [dimensionless]) return ( zp1**3 * (Or * zp1 + self.Om0) + self.Ode0 * zp1 ** (3.0 * (1.0 + self.w0)) ) ** (-0.5)
FlatwCDM
python
huggingface__transformers
src/transformers/models/albert/modeling_albert.py
{ "start": 13032, "end": 14032 }
class ____(ModelOutput): r""" loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`): Total loss as the sum of the masked language modeling loss and the next sequence prediction (classification) loss. prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). sop_logits (`torch.FloatTensor` of shape `(batch_size, 2)`): Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation before SoftMax). """ loss: Optional[torch.FloatTensor] = None prediction_logits: Optional[torch.FloatTensor] = None sop_logits: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor]] = None attentions: Optional[tuple[torch.FloatTensor]] = None @auto_docstring
AlbertForPreTrainingOutput
python
ray-project__ray
python/ray/dashboard/modules/aggregator/publisher/async_publisher_client.py
{ "start": 987, "end": 1782 }
class ____(ABC): """Abstract interface for publishing Ray event batches to external destinations. Implementations should handle the actual publishing logic, filtering, and format conversion appropriate for their specific destination type. """ def count_num_events_in_batch(self, batch: PublishBatch) -> int: """Count the number of events in a given batch.""" return len(batch.events) @abstractmethod async def publish(self, batch: PublishBatch) -> PublishStats: """Publish a batch of events to the destination.""" pass @abstractmethod async def close(self) -> None: """Clean up any resources used by this client. Should be called when the publisherClient is no longer required""" pass
PublisherClientInterface
python
coleifer__peewee
tests/sql.py
{ "start": 48287, "end": 52069 }
class ____(BaseTestCase): def test_update_query(self): query = (User .update({ User.c.username: 'nuggie', User.c.admin: False, User.c.counter: User.c.counter + 1}) .where(User.c.username == 'nugz')) self.assertSQL(query, ( 'UPDATE "users" SET ' '"admin" = ?, ' '"counter" = ("users"."counter" + ?), ' '"username" = ? ' 'WHERE ("users"."username" = ?)'), [False, 1, 'nuggie', 'nugz']) def test_update_subquery(self): count = fn.COUNT(Tweet.c.id).alias('ct') subquery = (User .select(User.c.id, count) .join(Tweet, on=(Tweet.c.user_id == User.c.id)) .group_by(User.c.id) .having(count > 100)) query = (User .update({ User.c.muted: True, User.c.counter: 0}) .where(User.c.id << subquery)) self.assertSQL(query, ( 'UPDATE "users" SET ' '"counter" = ?, ' '"muted" = ? ' 'WHERE ("users"."id" IN (' 'SELECT "users"."id", COUNT("t1"."id") AS "ct" ' 'FROM "users" AS "users" ' 'INNER JOIN "tweets" AS "t1" ' 'ON ("t1"."user_id" = "users"."id") ' 'GROUP BY "users"."id" ' 'HAVING ("ct" > ?)))'), [0, True, 100]) def test_update_value_subquery(self): subquery = (Tweet .select(fn.MAX(Tweet.c.id)) .where(Tweet.c.user_id == User.c.id)) query = (User .update({User.c.last_tweet_id: subquery}) .where(User.c.last_tweet_id.is_null(True))) self.assertSQL(query, ( 'UPDATE "users" SET ' '"last_tweet_id" = (SELECT MAX("t1"."id") FROM "tweets" AS "t1" ' 'WHERE ("t1"."user_id" = "users"."id")) ' 'WHERE ("users"."last_tweet_id" IS NULL)'), []) def test_update_from(self): data = [(1, 'u1-x'), (2, 'u2-x')] vl = ValuesList(data, columns=('id', 'username'), alias='tmp') query = (User .update(username=vl.c.username) .from_(vl) .where(User.c.id == vl.c.id)) self.assertSQL(query, ( 'UPDATE "users" SET "username" = "tmp"."username" ' 'FROM (VALUES (?, ?), (?, ?)) AS "tmp"("id", "username") ' 'WHERE ("users"."id" = "tmp"."id")'), [1, 'u1-x', 2, 'u2-x']) subq = vl.select(vl.c.id, vl.c.username) query = (User .update({User.c.username: subq.c.username}) .from_(subq) .where(User.c.id == subq.c.id)) self.assertSQL(query, ( 'UPDATE "users" SET "username" = "t1"."username" FROM (' 'SELECT "tmp"."id", "tmp"."username" ' 'FROM (VALUES (?, ?), (?, ?)) AS "tmp"("id", "username")) AS "t1" ' 'WHERE ("users"."id" = "t1"."id")'), [1, 'u1-x', 2, 'u2-x']) def test_update_returning(self): query = (User .update({User.c.is_admin: True}) .where(User.c.username == 'charlie') .returning(User.c.id)) self.assertSQL(query, ( 'UPDATE "users" SET "is_admin" = ? WHERE ("users"."username" = ?) ' 'RETURNING "users"."id"'), [True, 'charlie']) query = query.returning(User.c.is_admin.alias('new_is_admin')) self.assertSQL(query, ( 'UPDATE "users" SET "is_admin" = ? WHERE ("users"."username" = ?) ' 'RETURNING "users"."is_admin" AS "new_is_admin"'), [True, 'charlie'])
TestUpdateQuery
python
tensorflow__tensorflow
tensorflow/python/distribute/integration_test/saved_model_test.py
{ "start": 2571, "end": 3893 }
class ____(test.TestCase, parameterized.TestCase): def test_read_sync_on_read_variable(self, strategy): # TODO(b/178943315): Enable test when the design in b/17894331 is # implemented. self.skipTest( "This test fails today due to issue in multiple workers trying to write" " to same file location: b/178943315") class Model(tf.Module): def __init__(self): self.v = tf.Variable( 0., synchronization=tf.VariableSynchronization.ON_READ, aggregation=tf.VariableAggregation.SUM) @tf.function(input_signature=[]) def __call__(self): return self.v.read_value() export_dir = os.path.join(self._get_tempdir_path_test(), "test-file-failure") with strategy.scope(): m = Model() m.v.assign(1.) # This fails when multiple workers try to write to the same file location. # b/178943315 for tracking this bug. tf.saved_model.save(m, export_dir) @combinations.generate( combinations.combine( strategy=[ strategy_combinations.mirrored_strategy_with_two_cpus, strategy_combinations.mirrored_strategy_with_two_gpus, strategy_combinations.tpu_strategy, ], mode="eager", ))
SaveModelForMultipleWorkers
python
getsentry__sentry
src/sentry/monitors/system_incidents.py
{ "start": 12264, "end": 13371 }
class ____(StrEnum): ABNORMALITY_STARTED = "abnormality_started" """ An abnormality has been detected during normal operations. We may transition into a complete system incident, or the abnormality may recover to normal. """ ABNORMALITY_RECOVERED = "abnormality_recovered" """ An abnormality has recovered back to a normal status. """ INCIDENT_STARTED = "incident_started" """ A system incident has been detected based on the historic check-in volume. We are no longer able to reliably know that we are receving all check-ins. """ INCIDENT_RECOVERING = "incident_recovering" """ An incident has begun to recover. After this transition we will either re-enter the incident va INCIDENT_STARTED or fully recover via INCIDENT_RECOVERED. """ INCIDENT_RECOVERY_FAILED = "incident_recovery_failed" """ An incident failed to recover and has re-entered the incident state. """ INCIDENT_RECOVERED = "incident_recovered" """ An incident has recovered back to normal. """ @dataclass
AnomalyTransition
python
spack__spack
lib/spack/spack/vendor/attr/_make.py
{ "start": 20051, "end": 82281 }
class ____: """ Iteratively build *one* class. """ __slots__ = ( "_attr_names", "_attrs", "_base_attr_map", "_base_names", "_cache_hash", "_cls", "_cls_dict", "_delete_attribs", "_frozen", "_has_pre_init", "_has_post_init", "_is_exc", "_on_setattr", "_slots", "_weakref_slot", "_wrote_own_setattr", "_has_custom_setattr", ) def __init__( self, cls, these, slots, frozen, weakref_slot, getstate_setstate, auto_attribs, kw_only, cache_hash, is_exc, collect_by_mro, on_setattr, has_custom_setattr, field_transformer, ): attrs, base_attrs, base_map = _transform_attrs( cls, these, auto_attribs, kw_only, collect_by_mro, field_transformer, ) self._cls = cls self._cls_dict = dict(cls.__dict__) if slots else {} self._attrs = attrs self._base_names = {a.name for a in base_attrs} self._base_attr_map = base_map self._attr_names = tuple(a.name for a in attrs) self._slots = slots self._frozen = frozen self._weakref_slot = weakref_slot self._cache_hash = cache_hash self._has_pre_init = bool(getattr(cls, "__attrs_pre_init__", False)) self._has_post_init = bool(getattr(cls, "__attrs_post_init__", False)) self._delete_attribs = not bool(these) self._is_exc = is_exc self._on_setattr = on_setattr self._has_custom_setattr = has_custom_setattr self._wrote_own_setattr = False self._cls_dict["__attrs_attrs__"] = self._attrs if frozen: self._cls_dict["__setattr__"] = _frozen_setattrs self._cls_dict["__delattr__"] = _frozen_delattrs self._wrote_own_setattr = True elif on_setattr in ( _ng_default_on_setattr, setters.validate, setters.convert, ): has_validator = has_converter = False for a in attrs: if a.validator is not None: has_validator = True if a.converter is not None: has_converter = True if has_validator and has_converter: break if ( ( on_setattr == _ng_default_on_setattr and not (has_validator or has_converter) ) or (on_setattr == setters.validate and not has_validator) or (on_setattr == setters.convert and not has_converter) ): # If class-level on_setattr is set to convert + validate, but # there's no field to convert or validate, pretend like there's # no on_setattr. self._on_setattr = None if getstate_setstate: ( self._cls_dict["__getstate__"], self._cls_dict["__setstate__"], ) = self._make_getstate_setstate() def __repr__(self): return "<_ClassBuilder(cls={cls})>".format(cls=self._cls.__name__) def build_class(self): """ Finalize class based on the accumulated configuration. Builder cannot be used after calling this method. """ if self._slots is True: return self._create_slots_class() else: return self._patch_original_class() def _patch_original_class(self): """ Apply accumulated methods and return the class. """ cls = self._cls base_names = self._base_names # Clean class of attribute definitions (`attr.ib()`s). if self._delete_attribs: for name in self._attr_names: if ( name not in base_names and getattr(cls, name, _sentinel) is not _sentinel ): try: delattr(cls, name) except AttributeError: # This can happen if a base class defines a class # variable and we want to set an attribute with the # same name by using only a type annotation. pass # Attach our dunder methods. for name, value in self._cls_dict.items(): setattr(cls, name, value) # If we've inherited an attrs __setattr__ and don't write our own, # reset it to object's. if not self._wrote_own_setattr and getattr( cls, "__attrs_own_setattr__", False ): cls.__attrs_own_setattr__ = False if not self._has_custom_setattr: cls.__setattr__ = _obj_setattr return cls def _create_slots_class(self): """ Build and return a new class with a `__slots__` attribute. """ cd = { k: v for k, v in self._cls_dict.items() if k not in tuple(self._attr_names) + ("__dict__", "__weakref__") } # If our class doesn't have its own implementation of __setattr__ # (either from the user or by us), check the bases, if one of them has # an attrs-made __setattr__, that needs to be reset. We don't walk the # MRO because we only care about our immediate base classes. # XXX: This can be confused by subclassing a slotted attrs class with # XXX: a non-attrs class and subclass the resulting class with an attrs # XXX: class. See `test_slotted_confused` for details. For now that's # XXX: OK with us. if not self._wrote_own_setattr: cd["__attrs_own_setattr__"] = False if not self._has_custom_setattr: for base_cls in self._cls.__bases__: if base_cls.__dict__.get("__attrs_own_setattr__", False): cd["__setattr__"] = _obj_setattr break # Traverse the MRO to collect existing slots # and check for an existing __weakref__. existing_slots = dict() weakref_inherited = False for base_cls in self._cls.__mro__[1:-1]: if base_cls.__dict__.get("__weakref__", None) is not None: weakref_inherited = True existing_slots.update( { name: getattr(base_cls, name) for name in getattr(base_cls, "__slots__", []) } ) base_names = set(self._base_names) names = self._attr_names if ( self._weakref_slot and "__weakref__" not in getattr(self._cls, "__slots__", ()) and "__weakref__" not in names and not weakref_inherited ): names += ("__weakref__",) # We only add the names of attributes that aren't inherited. # Setting __slots__ to inherited attributes wastes memory. slot_names = [name for name in names if name not in base_names] # There are slots for attributes from current class # that are defined in parent classes. # As their descriptors may be overridden by a child class, # we collect them here and update the class dict reused_slots = { slot: slot_descriptor for slot, slot_descriptor in existing_slots.items() if slot in slot_names } slot_names = [name for name in slot_names if name not in reused_slots] cd.update(reused_slots) if self._cache_hash: slot_names.append(_hash_cache_field) cd["__slots__"] = tuple(slot_names) cd["__qualname__"] = self._cls.__qualname__ # Create new class based on old class and our methods. cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd) # The following is a fix for # <https://github.com/python-attrs/attrs/issues/102>. On Python 3, # if a method mentions `__class__` or uses the no-arg super(), the # compiler will bake a reference to the class in the method itself # as `method.__closure__`. Since we replace the class with a # clone, we rewrite these references so it keeps working. for item in cls.__dict__.values(): if isinstance(item, (classmethod, staticmethod)): # Class- and staticmethods hide their functions inside. # These might need to be rewritten as well. closure_cells = getattr(item.__func__, "__closure__", None) elif isinstance(item, property): # Workaround for property `super()` shortcut (PY3-only). # There is no universal way for other descriptors. closure_cells = getattr(item.fget, "__closure__", None) else: closure_cells = getattr(item, "__closure__", None) if not closure_cells: # Catch None or the empty list. continue for cell in closure_cells: try: match = cell.cell_contents is self._cls except ValueError: # ValueError: Cell is empty pass else: if match: set_closure_cell(cell, cls) return cls def add_repr(self, ns): self._cls_dict["__repr__"] = self._add_method_dunders( _make_repr(self._attrs, ns, self._cls) ) return self def add_str(self): repr = self._cls_dict.get("__repr__") if repr is None: raise ValueError( "__str__ can only be generated if a __repr__ exists." ) def __str__(self): return self.__repr__() self._cls_dict["__str__"] = self._add_method_dunders(__str__) return self def _make_getstate_setstate(self): """ Create custom __setstate__ and __getstate__ methods. """ # __weakref__ is not writable. state_attr_names = tuple( an for an in self._attr_names if an != "__weakref__" ) def slots_getstate(self): """ Automatically created by attrs. """ return tuple(getattr(self, name) for name in state_attr_names) hash_caching_enabled = self._cache_hash def slots_setstate(self, state): """ Automatically created by attrs. """ __bound_setattr = _obj_setattr.__get__(self, Attribute) for name, value in zip(state_attr_names, state): __bound_setattr(name, value) # The hash code cache is not included when the object is # serialized, but it still needs to be initialized to None to # indicate that the first call to __hash__ should be a cache # miss. if hash_caching_enabled: __bound_setattr(_hash_cache_field, None) return slots_getstate, slots_setstate def make_unhashable(self): self._cls_dict["__hash__"] = None return self def add_hash(self): self._cls_dict["__hash__"] = self._add_method_dunders( _make_hash( self._cls, self._attrs, frozen=self._frozen, cache_hash=self._cache_hash, ) ) return self def add_init(self): self._cls_dict["__init__"] = self._add_method_dunders( _make_init( self._cls, self._attrs, self._has_pre_init, self._has_post_init, self._frozen, self._slots, self._cache_hash, self._base_attr_map, self._is_exc, self._on_setattr, attrs_init=False, ) ) return self def add_match_args(self): self._cls_dict["__match_args__"] = tuple( field.name for field in self._attrs if field.init and not field.kw_only ) def add_attrs_init(self): self._cls_dict["__attrs_init__"] = self._add_method_dunders( _make_init( self._cls, self._attrs, self._has_pre_init, self._has_post_init, self._frozen, self._slots, self._cache_hash, self._base_attr_map, self._is_exc, self._on_setattr, attrs_init=True, ) ) return self def add_eq(self): cd = self._cls_dict cd["__eq__"] = self._add_method_dunders( _make_eq(self._cls, self._attrs) ) cd["__ne__"] = self._add_method_dunders(_make_ne()) return self def add_order(self): cd = self._cls_dict cd["__lt__"], cd["__le__"], cd["__gt__"], cd["__ge__"] = ( self._add_method_dunders(meth) for meth in _make_order(self._cls, self._attrs) ) return self def add_setattr(self): if self._frozen: return self sa_attrs = {} for a in self._attrs: on_setattr = a.on_setattr or self._on_setattr if on_setattr and on_setattr is not setters.NO_OP: sa_attrs[a.name] = a, on_setattr if not sa_attrs: return self if self._has_custom_setattr: # We need to write a __setattr__ but there already is one! raise ValueError( "Can't combine custom __setattr__ with on_setattr hooks." ) # docstring comes from _add_method_dunders def __setattr__(self, name, val): try: a, hook = sa_attrs[name] except KeyError: nval = val else: nval = hook(self, a, val) _obj_setattr(self, name, nval) self._cls_dict["__attrs_own_setattr__"] = True self._cls_dict["__setattr__"] = self._add_method_dunders(__setattr__) self._wrote_own_setattr = True return self def _add_method_dunders(self, method): """ Add __module__ and __qualname__ to a *method* if possible. """ try: method.__module__ = self._cls.__module__ except AttributeError: pass try: method.__qualname__ = ".".join( (self._cls.__qualname__, method.__name__) ) except AttributeError: pass try: method.__doc__ = "Method generated by attrs for class %s." % ( self._cls.__qualname__, ) except AttributeError: pass return method def _determine_attrs_eq_order(cmp, eq, order, default_eq): """ Validate the combination of *cmp*, *eq*, and *order*. Derive the effective values of eq and order. If *eq* is None, set it to *default_eq*. """ if cmp is not None and any((eq is not None, order is not None)): raise ValueError("Don't mix `cmp` with `eq' and `order`.") # cmp takes precedence due to bw-compatibility. if cmp is not None: return cmp, cmp # If left None, equality is set to the specified default and ordering # mirrors equality. if eq is None: eq = default_eq if order is None: order = eq if eq is False and order is True: raise ValueError("`order` can only be True if `eq` is True too.") return eq, order def _determine_attrib_eq_order(cmp, eq, order, default_eq): """ Validate the combination of *cmp*, *eq*, and *order*. Derive the effective values of eq and order. If *eq* is None, set it to *default_eq*. """ if cmp is not None and any((eq is not None, order is not None)): raise ValueError("Don't mix `cmp` with `eq' and `order`.") def decide_callable_or_boolean(value): """ Decide whether a key function is used. """ if callable(value): value, key = True, value else: key = None return value, key # cmp takes precedence due to bw-compatibility. if cmp is not None: cmp, cmp_key = decide_callable_or_boolean(cmp) return cmp, cmp_key, cmp, cmp_key # If left None, equality is set to the specified default and ordering # mirrors equality. if eq is None: eq, eq_key = default_eq, None else: eq, eq_key = decide_callable_or_boolean(eq) if order is None: order, order_key = eq, eq_key else: order, order_key = decide_callable_or_boolean(order) if eq is False and order is True: raise ValueError("`order` can only be True if `eq` is True too.") return eq, eq_key, order, order_key def _determine_whether_to_implement( cls, flag, auto_detect, dunders, default=True ): """ Check whether we should implement a set of methods for *cls*. *flag* is the argument passed into @attr.s like 'init', *auto_detect* the same as passed into @attr.s and *dunders* is a tuple of attribute names whose presence signal that the user has implemented it themselves. Return *default* if no reason for either for or against is found. """ if flag is True or flag is False: return flag if flag is None and auto_detect is False: return default # Logically, flag is None and auto_detect is True here. for dunder in dunders: if _has_own_attribute(cls, dunder): return False return default def attrs( maybe_cls=None, these=None, repr_ns=None, repr=None, cmp=None, hash=None, init=None, slots=False, frozen=False, weakref_slot=True, str=False, auto_attribs=False, kw_only=False, cache_hash=False, auto_exc=False, eq=None, order=None, auto_detect=False, collect_by_mro=False, getstate_setstate=None, on_setattr=None, field_transformer=None, match_args=True, ): r""" A class decorator that adds `dunder <https://wiki.python.org/moin/DunderAlias>`_\ -methods according to the specified attributes using `attr.ib` or the *these* argument. :param these: A dictionary of name to `attr.ib` mappings. This is useful to avoid the definition of your attributes within the class body because you can't (e.g. if you want to add ``__repr__`` methods to Django models) or don't want to. If *these* is not ``None``, ``attrs`` will *not* search the class body for attributes and will *not* remove any attributes from it. If *these* is an ordered dict (`dict` on Python 3.6+, `collections.OrderedDict` otherwise), the order is deduced from the order of the attributes inside *these*. Otherwise the order of the definition of the attributes is used. :type these: `dict` of `str` to `attr.ib` :param str repr_ns: When using nested classes, there's no way in Python 2 to automatically detect that. Therefore it's possible to set the namespace explicitly for a more meaningful ``repr`` output. :param bool auto_detect: Instead of setting the *init*, *repr*, *eq*, *order*, and *hash* arguments explicitly, assume they are set to ``True`` **unless any** of the involved methods for one of the arguments is implemented in the *current* class (i.e. it is *not* inherited from some base class). So for example by implementing ``__eq__`` on a class yourself, ``attrs`` will deduce ``eq=False`` and will create *neither* ``__eq__`` *nor* ``__ne__`` (but Python classes come with a sensible ``__ne__`` by default, so it *should* be enough to only implement ``__eq__`` in most cases). .. warning:: If you prevent ``attrs`` from creating the ordering methods for you (``order=False``, e.g. by implementing ``__le__``), it becomes *your* responsibility to make sure its ordering is sound. The best way is to use the `functools.total_ordering` decorator. Passing ``True`` or ``False`` to *init*, *repr*, *eq*, *order*, *cmp*, or *hash* overrides whatever *auto_detect* would determine. *auto_detect* requires Python 3. Setting it ``True`` on Python 2 raises an `attrs.exceptions.PythonTooOldError`. :param bool repr: Create a ``__repr__`` method with a human readable representation of ``attrs`` attributes.. :param bool str: Create a ``__str__`` method that is identical to ``__repr__``. This is usually not necessary except for `Exception`\ s. :param Optional[bool] eq: If ``True`` or ``None`` (default), add ``__eq__`` and ``__ne__`` methods that check two instances for equality. They compare the instances as if they were tuples of their ``attrs`` attributes if and only if the types of both classes are *identical*! :param Optional[bool] order: If ``True``, add ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` methods that behave like *eq* above and allow instances to be ordered. If ``None`` (default) mirror value of *eq*. :param Optional[bool] cmp: Setting *cmp* is equivalent to setting *eq* and *order* to the same value. Must not be mixed with *eq* or *order*. :param Optional[bool] hash: If ``None`` (default), the ``__hash__`` method is generated according how *eq* and *frozen* are set. 1. If *both* are True, ``attrs`` will generate a ``__hash__`` for you. 2. If *eq* is True and *frozen* is False, ``__hash__`` will be set to None, marking it unhashable (which it is). 3. If *eq* is False, ``__hash__`` will be left untouched meaning the ``__hash__`` method of the base class will be used (if base class is ``object``, this means it will fall back to id-based hashing.). Although not recommended, you can decide for yourself and force ``attrs`` to create one (e.g. if the class is immutable even though you didn't freeze it programmatically) by passing ``True`` or not. Both of these cases are rather special and should be used carefully. See our documentation on `hashing`, Python's documentation on `object.__hash__`, and the `GitHub issue that led to the default \ behavior <https://github.com/python-attrs/attrs/issues/136>`_ for more details. :param bool init: Create a ``__init__`` method that initializes the ``attrs`` attributes. Leading underscores are stripped for the argument name. If a ``__attrs_pre_init__`` method exists on the class, it will be called before the class is initialized. If a ``__attrs_post_init__`` method exists on the class, it will be called after the class is fully initialized. If ``init`` is ``False``, an ``__attrs_init__`` method will be injected instead. This allows you to define a custom ``__init__`` method that can do pre-init work such as ``super().__init__()``, and then call ``__attrs_init__()`` and ``__attrs_post_init__()``. :param bool slots: Create a `slotted class <slotted classes>` that's more memory-efficient. Slotted classes are generally superior to the default dict classes, but have some gotchas you should know about, so we encourage you to read the `glossary entry <slotted classes>`. :param bool frozen: Make instances immutable after initialization. If someone attempts to modify a frozen instance, `attr.exceptions.FrozenInstanceError` is raised. .. note:: 1. This is achieved by installing a custom ``__setattr__`` method on your class, so you can't implement your own. 2. True immutability is impossible in Python. 3. This *does* have a minor a runtime performance `impact <how-frozen>` when initializing new instances. In other words: ``__init__`` is slightly slower with ``frozen=True``. 4. If a class is frozen, you cannot modify ``self`` in ``__attrs_post_init__`` or a self-written ``__init__``. You can circumvent that limitation by using ``object.__setattr__(self, "attribute_name", value)``. 5. Subclasses of a frozen class are frozen too. :param bool weakref_slot: Make instances weak-referenceable. This has no effect unless ``slots`` is also enabled. :param bool auto_attribs: If ``True``, collect :pep:`526`-annotated attributes (Python 3.6 and later only) from the class body. In this case, you **must** annotate every field. If ``attrs`` encounters a field that is set to an `attr.ib` but lacks a type annotation, an `attr.exceptions.UnannotatedAttributeError` is raised. Use ``field_name: typing.Any = attr.ib(...)`` if you don't want to set a type. If you assign a value to those attributes (e.g. ``x: int = 42``), that value becomes the default value like if it were passed using ``attr.ib(default=42)``. Passing an instance of `attrs.Factory` also works as expected in most cases (see warning below). Attributes annotated as `typing.ClassVar`, and attributes that are neither annotated nor set to an `attr.ib` are **ignored**. .. warning:: For features that use the attribute name to create decorators (e.g. `validators <validators>`), you still *must* assign `attr.ib` to them. Otherwise Python will either not find the name or try to use the default value to call e.g. ``validator`` on it. These errors can be quite confusing and probably the most common bug report on our bug tracker. :param bool kw_only: Make all attributes keyword-only (Python 3+) in the generated ``__init__`` (if ``init`` is ``False``, this parameter is ignored). :param bool cache_hash: Ensure that the object's hash code is computed only once and stored on the object. If this is set to ``True``, hashing must be either explicitly or implicitly enabled for this class. If the hash code is cached, avoid any reassignments of fields involved in hash code computation or mutations of the objects those fields point to after object creation. If such changes occur, the behavior of the object's hash code is undefined. :param bool auto_exc: If the class subclasses `BaseException` (which implicitly includes any subclass of any exception), the following happens to behave like a well-behaved Python exceptions class: - the values for *eq*, *order*, and *hash* are ignored and the instances compare and hash by the instance's ids (N.B. ``attrs`` will *not* remove existing implementations of ``__hash__`` or the equality methods. It just won't add own ones.), - all attributes that are either passed into ``__init__`` or have a default value are additionally available as a tuple in the ``args`` attribute, - the value of *str* is ignored leaving ``__str__`` to base classes. :param bool collect_by_mro: Setting this to `True` fixes the way ``attrs`` collects attributes from base classes. The default behavior is incorrect in certain cases of multiple inheritance. It should be on by default but is kept off for backward-compatibility. See issue `#428 <https://github.com/python-attrs/attrs/issues/428>`_ for more details. :param Optional[bool] getstate_setstate: .. note:: This is usually only interesting for slotted classes and you should probably just set *auto_detect* to `True`. If `True`, ``__getstate__`` and ``__setstate__`` are generated and attached to the class. This is necessary for slotted classes to be pickleable. If left `None`, it's `True` by default for slotted classes and ``False`` for dict classes. If *auto_detect* is `True`, and *getstate_setstate* is left `None`, and **either** ``__getstate__`` or ``__setstate__`` is detected directly on the class (i.e. not inherited), it is set to `False` (this is usually what you want). :param on_setattr: A callable that is run whenever the user attempts to set an attribute (either by assignment like ``i.x = 42`` or by using `setattr` like ``setattr(i, "x", 42)``). It receives the same arguments as validators: the instance, the attribute that is being modified, and the new value. If no exception is raised, the attribute is set to the return value of the callable. If a list of callables is passed, they're automatically wrapped in an `attrs.setters.pipe`. :type on_setattr: `callable`, or a list of callables, or `None`, or `attrs.setters.NO_OP` :param Optional[callable] field_transformer: A function that is called with the original class object and all fields right before ``attrs`` finalizes the class. You can use this, e.g., to automatically add converters or validators to fields based on their types. See `transform-fields` for more details. :param bool match_args: If `True` (default), set ``__match_args__`` on the class to support :pep:`634` (Structural Pattern Matching). It is a tuple of all non-keyword-only ``__init__`` parameter names on Python 3.10 and later. Ignored on older Python versions. .. versionadded:: 16.0.0 *slots* .. versionadded:: 16.1.0 *frozen* .. versionadded:: 16.3.0 *str* .. versionadded:: 16.3.0 Support for ``__attrs_post_init__``. .. versionchanged:: 17.1.0 *hash* supports ``None`` as value which is also the default now. .. versionadded:: 17.3.0 *auto_attribs* .. versionchanged:: 18.1.0 If *these* is passed, no attributes are deleted from the class body. .. versionchanged:: 18.1.0 If *these* is ordered, the order is retained. .. versionadded:: 18.2.0 *weakref_slot* .. deprecated:: 18.2.0 ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a `DeprecationWarning` if the classes compared are subclasses of each other. ``__eq`` and ``__ne__`` never tried to compared subclasses to each other. .. versionchanged:: 19.2.0 ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now do not consider subclasses comparable anymore. .. versionadded:: 18.2.0 *kw_only* .. versionadded:: 18.2.0 *cache_hash* .. versionadded:: 19.1.0 *auto_exc* .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. .. versionadded:: 19.2.0 *eq* and *order* .. versionadded:: 20.1.0 *auto_detect* .. versionadded:: 20.1.0 *collect_by_mro* .. versionadded:: 20.1.0 *getstate_setstate* .. versionadded:: 20.1.0 *on_setattr* .. versionadded:: 20.3.0 *field_transformer* .. versionchanged:: 21.1.0 ``init=False`` injects ``__attrs_init__`` .. versionchanged:: 21.1.0 Support for ``__attrs_pre_init__`` .. versionchanged:: 21.1.0 *cmp* undeprecated .. versionadded:: 21.3.0 *match_args* """ eq_, order_ = _determine_attrs_eq_order(cmp, eq, order, None) hash_ = hash # work around the lack of nonlocal if isinstance(on_setattr, (list, tuple)): on_setattr = setters.pipe(*on_setattr) def wrap(cls): is_frozen = frozen or _has_frozen_base_class(cls) is_exc = auto_exc is True and issubclass(cls, BaseException) has_own_setattr = auto_detect and _has_own_attribute( cls, "__setattr__" ) if has_own_setattr and is_frozen: raise ValueError("Can't freeze a class with a custom __setattr__.") builder = _ClassBuilder( cls, these, slots, is_frozen, weakref_slot, _determine_whether_to_implement( cls, getstate_setstate, auto_detect, ("__getstate__", "__setstate__"), default=slots, ), auto_attribs, kw_only, cache_hash, is_exc, collect_by_mro, on_setattr, has_own_setattr, field_transformer, ) if _determine_whether_to_implement( cls, repr, auto_detect, ("__repr__",) ): builder.add_repr(repr_ns) if str is True: builder.add_str() eq = _determine_whether_to_implement( cls, eq_, auto_detect, ("__eq__", "__ne__") ) if not is_exc and eq is True: builder.add_eq() if not is_exc and _determine_whether_to_implement( cls, order_, auto_detect, ("__lt__", "__le__", "__gt__", "__ge__") ): builder.add_order() builder.add_setattr() if ( hash_ is None and auto_detect is True and _has_own_attribute(cls, "__hash__") ): hash = False else: hash = hash_ if hash is not True and hash is not False and hash is not None: # Can't use `hash in` because 1 == True for example. raise TypeError( "Invalid value for hash. Must be True, False, or None." ) elif hash is False or (hash is None and eq is False) or is_exc: # Don't do anything. Should fall back to __object__'s __hash__ # which is by id. if cache_hash: raise TypeError( "Invalid value for cache_hash. To use hash caching," " hashing must be either explicitly or implicitly " "enabled." ) elif hash is True or ( hash is None and eq is True and is_frozen is True ): # Build a __hash__ if told so, or if it's safe. builder.add_hash() else: # Raise TypeError on attempts to hash. if cache_hash: raise TypeError( "Invalid value for cache_hash. To use hash caching," " hashing must be either explicitly or implicitly " "enabled." ) builder.make_unhashable() if _determine_whether_to_implement( cls, init, auto_detect, ("__init__",) ): builder.add_init() else: builder.add_attrs_init() if cache_hash: raise TypeError( "Invalid value for cache_hash. To use hash caching," " init must be True." ) if ( PY310 and match_args and not _has_own_attribute(cls, "__match_args__") ): builder.add_match_args() return builder.build_class() # maybe_cls's type depends on the usage of the decorator. It's a class # if it's used as `@attrs` but ``None`` if used as `@attrs()`. if maybe_cls is None: return wrap else: return wrap(maybe_cls) _attrs = attrs """ Internal alias so we can use it in functions that take an argument called *attrs*. """ def _has_frozen_base_class(cls): """ Check whether *cls* has a frozen ancestor by looking at its __setattr__. """ return cls.__setattr__ is _frozen_setattrs def _generate_unique_filename(cls, func_name): """ Create a "filename" suitable for a function being generated. """ unique_filename = "<attrs generated {} {}.{}>".format( func_name, cls.__module__, getattr(cls, "__qualname__", cls.__name__), ) return unique_filename def _make_hash(cls, attrs, frozen, cache_hash): attrs = tuple( a for a in attrs if a.hash is True or (a.hash is None and a.eq is True) ) tab = " " unique_filename = _generate_unique_filename(cls, "hash") type_hash = hash(unique_filename) # If eq is custom generated, we need to include the functions in globs globs = {} hash_def = "def __hash__(self" hash_func = "hash((" closing_braces = "))" if not cache_hash: hash_def += "):" else: hash_def += ", *" hash_def += ( ", _cache_wrapper=" + "__import__('attr._make')._make._CacheHashWrapper):" ) hash_func = "_cache_wrapper(" + hash_func closing_braces += ")" method_lines = [hash_def] def append_hash_computation_lines(prefix, indent): """ Generate the code for actually computing the hash code. Below this will either be returned directly or used to compute a value which is then cached, depending on the value of cache_hash """ method_lines.extend( [ indent + prefix + hash_func, indent + " %d," % (type_hash,), ] ) for a in attrs: if a.eq_key: cmp_name = "_%s_key" % (a.name,) globs[cmp_name] = a.eq_key method_lines.append( indent + " %s(self.%s)," % (cmp_name, a.name) ) else: method_lines.append(indent + " self.%s," % a.name) method_lines.append(indent + " " + closing_braces) if cache_hash: method_lines.append(tab + "if self.%s is None:" % _hash_cache_field) if frozen: append_hash_computation_lines( "object.__setattr__(self, '%s', " % _hash_cache_field, tab * 2 ) method_lines.append(tab * 2 + ")") # close __setattr__ else: append_hash_computation_lines( "self.%s = " % _hash_cache_field, tab * 2 ) method_lines.append(tab + "return self.%s" % _hash_cache_field) else: append_hash_computation_lines("return ", tab) script = "\n".join(method_lines) return _make_method("__hash__", script, unique_filename, globs) def _add_hash(cls, attrs): """ Add a hash method to *cls*. """ cls.__hash__ = _make_hash(cls, attrs, frozen=False, cache_hash=False) return cls def _make_ne(): """ Create __ne__ method. """ def __ne__(self, other): """ Check equality and either forward a NotImplemented or return the result negated. """ result = self.__eq__(other) if result is NotImplemented: return NotImplemented return not result return __ne__ def _make_eq(cls, attrs): """ Create __eq__ method for *cls* with *attrs*. """ attrs = [a for a in attrs if a.eq] unique_filename = _generate_unique_filename(cls, "eq") lines = [ "def __eq__(self, other):", " if other.__class__ is not self.__class__:", " return NotImplemented", ] # We can't just do a big self.x = other.x and... clause due to # irregularities like nan == nan is false but (nan,) == (nan,) is true. globs = {} if attrs: lines.append(" return (") others = [" ) == ("] for a in attrs: if a.eq_key: cmp_name = "_%s_key" % (a.name,) # Add the key function to the global namespace # of the evaluated function. globs[cmp_name] = a.eq_key lines.append( " %s(self.%s)," % ( cmp_name, a.name, ) ) others.append( " %s(other.%s)," % ( cmp_name, a.name, ) ) else: lines.append(" self.%s," % (a.name,)) others.append(" other.%s," % (a.name,)) lines += others + [" )"] else: lines.append(" return True") script = "\n".join(lines) return _make_method("__eq__", script, unique_filename, globs) def _make_order(cls, attrs): """ Create ordering methods for *cls* with *attrs*. """ attrs = [a for a in attrs if a.order] def attrs_to_tuple(obj): """ Save us some typing. """ return tuple( key(value) if key else value for value, key in ( (getattr(obj, a.name), a.order_key) for a in attrs ) ) def __lt__(self, other): """ Automatically created by attrs. """ if other.__class__ is self.__class__: return attrs_to_tuple(self) < attrs_to_tuple(other) return NotImplemented def __le__(self, other): """ Automatically created by attrs. """ if other.__class__ is self.__class__: return attrs_to_tuple(self) <= attrs_to_tuple(other) return NotImplemented def __gt__(self, other): """ Automatically created by attrs. """ if other.__class__ is self.__class__: return attrs_to_tuple(self) > attrs_to_tuple(other) return NotImplemented def __ge__(self, other): """ Automatically created by attrs. """ if other.__class__ is self.__class__: return attrs_to_tuple(self) >= attrs_to_tuple(other) return NotImplemented return __lt__, __le__, __gt__, __ge__ def _add_eq(cls, attrs=None): """ Add equality methods to *cls* with *attrs*. """ if attrs is None: attrs = cls.__attrs_attrs__ cls.__eq__ = _make_eq(cls, attrs) cls.__ne__ = _make_ne() return cls if HAS_F_STRINGS: def _make_repr(attrs, ns, cls): unique_filename = _generate_unique_filename(cls, "repr") # Figure out which attributes to include, and which function to use to # format them. The a.repr value can be either bool or a custom # callable. attr_names_with_reprs = tuple( (a.name, (repr if a.repr is True else a.repr), a.init) for a in attrs if a.repr is not False ) globs = { name + "_repr": r for name, r, _ in attr_names_with_reprs if r != repr } globs["_compat"] = _compat globs["AttributeError"] = AttributeError globs["NOTHING"] = NOTHING attribute_fragments = [] for name, r, i in attr_names_with_reprs: accessor = ( "self." + name if i else 'getattr(self, "' + name + '", NOTHING)' ) fragment = ( "%s={%s!r}" % (name, accessor) if r == repr else "%s={%s_repr(%s)}" % (name, name, accessor) ) attribute_fragments.append(fragment) repr_fragment = ", ".join(attribute_fragments) if ns is None: cls_name_fragment = ( '{self.__class__.__qualname__.rsplit(">.", 1)[-1]}' ) else: cls_name_fragment = ns + ".{self.__class__.__name__}" lines = [ "def __repr__(self):", " try:", " already_repring = _compat.repr_context.already_repring", " except AttributeError:", " already_repring = {id(self),}", " _compat.repr_context.already_repring = already_repring", " else:", " if id(self) in already_repring:", " return '...'", " else:", " already_repring.add(id(self))", " try:", " return f'%s(%s)'" % (cls_name_fragment, repr_fragment), " finally:", " already_repring.remove(id(self))", ] return _make_method( "__repr__", "\n".join(lines), unique_filename, globs=globs ) else: def _make_repr(attrs, ns, _): """ Make a repr method that includes relevant *attrs*, adding *ns* to the full name. """ # Figure out which attributes to include, and which function to use to # format them. The a.repr value can be either bool or a custom # callable. attr_names_with_reprs = tuple( (a.name, repr if a.repr is True else a.repr) for a in attrs if a.repr is not False ) def __repr__(self): """ Automatically created by attrs. """ try: already_repring = _compat.repr_context.already_repring except AttributeError: already_repring = set() _compat.repr_context.already_repring = already_repring if id(self) in already_repring: return "..." real_cls = self.__class__ if ns is None: class_name = real_cls.__qualname__.rsplit(">.", 1)[-1] else: class_name = ns + "." + real_cls.__name__ # Since 'self' remains on the stack (i.e.: strongly referenced) # for the duration of this call, it's safe to depend on id(...) # stability, and not need to track the instance and therefore # worry about properties like weakref- or hash-ability. already_repring.add(id(self)) try: result = [class_name, "("] first = True for name, attr_repr in attr_names_with_reprs: if first: first = False else: result.append(", ") result.extend( (name, "=", attr_repr(getattr(self, name, NOTHING))) ) return "".join(result) + ")" finally: already_repring.remove(id(self)) return __repr__ def _add_repr(cls, ns=None, attrs=None): """ Add a repr method to *cls*. """ if attrs is None: attrs = cls.__attrs_attrs__ cls.__repr__ = _make_repr(attrs, ns, cls) return cls def fields(cls): """ Return the tuple of ``attrs`` attributes for a class. The tuple also allows accessing the fields by their names (see below for examples). :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. :rtype: tuple (with name accessors) of `attrs.Attribute` .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields by name. """ if not isinstance(cls, type): raise TypeError("Passed object must be a class.") attrs = getattr(cls, "__attrs_attrs__", None) if attrs is None: raise NotAnAttrsClassError( "{cls!r} is not an attrs-decorated class.".format(cls=cls) ) return attrs def fields_dict(cls): """ Return an ordered dictionary of ``attrs`` attributes for a class, whose keys are the attribute names. :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. :rtype: an ordered dict where keys are attribute names and values are `attrs.Attribute`\\ s. This will be a `dict` if it's naturally ordered like on Python 3.6+ or an :class:`~collections.OrderedDict` otherwise. .. versionadded:: 18.1.0 """ if not isinstance(cls, type): raise TypeError("Passed object must be a class.") attrs = getattr(cls, "__attrs_attrs__", None) if attrs is None: raise NotAnAttrsClassError( "{cls!r} is not an attrs-decorated class.".format(cls=cls) ) return ordered_dict((a.name, a) for a in attrs) def validate(inst): """ Validate all attributes on *inst* that have a validator. Leaves all exceptions through. :param inst: Instance of a class with ``attrs`` attributes. """ if _config._run_validators is False: return for a in fields(inst.__class__): v = a.validator if v is not None: v(inst, a, getattr(inst, a.name)) def _is_slot_cls(cls): return "__slots__" in cls.__dict__ def _is_slot_attr(a_name, base_attr_map): """ Check if the attribute name comes from a slot class. """ return a_name in base_attr_map and _is_slot_cls(base_attr_map[a_name]) def _make_init( cls, attrs, pre_init, post_init, frozen, slots, cache_hash, base_attr_map, is_exc, cls_on_setattr, attrs_init, ): has_cls_on_setattr = ( cls_on_setattr is not None and cls_on_setattr is not setters.NO_OP ) if frozen and has_cls_on_setattr: raise ValueError("Frozen classes can't use on_setattr.") needs_cached_setattr = cache_hash or frozen filtered_attrs = [] attr_dict = {} for a in attrs: if not a.init and a.default is NOTHING: continue filtered_attrs.append(a) attr_dict[a.name] = a if a.on_setattr is not None: if frozen is True: raise ValueError("Frozen classes can't use on_setattr.") needs_cached_setattr = True elif has_cls_on_setattr and a.on_setattr is not setters.NO_OP: needs_cached_setattr = True unique_filename = _generate_unique_filename(cls, "init") script, globs, annotations = _attrs_to_init_script( filtered_attrs, frozen, slots, pre_init, post_init, cache_hash, base_attr_map, is_exc, has_cls_on_setattr, attrs_init, ) if cls.__module__ in sys.modules: # This makes typing.get_type_hints(CLS.__init__) resolve string types. globs.update(sys.modules[cls.__module__].__dict__) globs.update({"NOTHING": NOTHING, "attr_dict": attr_dict}) if needs_cached_setattr: # Save the lookup overhead in __init__ if we need to circumvent # setattr hooks. globs["_setattr"] = _obj_setattr init = _make_method( "__attrs_init__" if attrs_init else "__init__", script, unique_filename, globs, ) init.__annotations__ = annotations return init def _setattr(attr_name, value_var, has_on_setattr): """ Use the cached object.setattr to set *attr_name* to *value_var*. """ return "_setattr(self, '%s', %s)" % (attr_name, value_var) def _setattr_with_converter(attr_name, value_var, has_on_setattr): """ Use the cached object.setattr to set *attr_name* to *value_var*, but run its converter first. """ return "_setattr(self, '%s', %s(%s))" % ( attr_name, _init_converter_pat % (attr_name,), value_var, ) def _assign(attr_name, value, has_on_setattr): """ Unless *attr_name* has an on_setattr hook, use normal assignment. Otherwise relegate to _setattr. """ if has_on_setattr: return _setattr(attr_name, value, True) return "self.%s = %s" % (attr_name, value) def _assign_with_converter(attr_name, value_var, has_on_setattr): """ Unless *attr_name* has an on_setattr hook, use normal assignment after conversion. Otherwise relegate to _setattr_with_converter. """ if has_on_setattr: return _setattr_with_converter(attr_name, value_var, True) return "self.%s = %s(%s)" % ( attr_name, _init_converter_pat % (attr_name,), value_var, ) def _attrs_to_init_script( attrs, frozen, slots, pre_init, post_init, cache_hash, base_attr_map, is_exc, has_cls_on_setattr, attrs_init, ): """ Return a script of an initializer for *attrs* and a dict of globals. The globals are expected by the generated script. If *frozen* is True, we cannot set the attributes directly so we use a cached ``object.__setattr__``. """ lines = [] if pre_init: lines.append("self.__attrs_pre_init__()") if frozen is True: if slots is True: fmt_setter = _setattr fmt_setter_with_converter = _setattr_with_converter else: # Dict frozen classes assign directly to __dict__. # But only if the attribute doesn't come from an ancestor slot # class. # Note _inst_dict will be used again below if cache_hash is True lines.append("_inst_dict = self.__dict__") def fmt_setter(attr_name, value_var, has_on_setattr): if _is_slot_attr(attr_name, base_attr_map): return _setattr(attr_name, value_var, has_on_setattr) return "_inst_dict['%s'] = %s" % (attr_name, value_var) def fmt_setter_with_converter( attr_name, value_var, has_on_setattr ): if has_on_setattr or _is_slot_attr(attr_name, base_attr_map): return _setattr_with_converter( attr_name, value_var, has_on_setattr ) return "_inst_dict['%s'] = %s(%s)" % ( attr_name, _init_converter_pat % (attr_name,), value_var, ) else: # Not frozen. fmt_setter = _assign fmt_setter_with_converter = _assign_with_converter args = [] kw_only_args = [] attrs_to_validate = [] # This is a dictionary of names to validator and converter callables. # Injecting this into __init__ globals lets us avoid lookups. names_for_globals = {} annotations = {"return": None} for a in attrs: if a.validator: attrs_to_validate.append(a) attr_name = a.name has_on_setattr = a.on_setattr is not None or ( a.on_setattr is not setters.NO_OP and has_cls_on_setattr ) arg_name = a.name.lstrip("_") has_factory = isinstance(a.default, Factory) if has_factory and a.default.takes_self: maybe_self = "self" else: maybe_self = "" if a.init is False: if has_factory: init_factory_name = _init_factory_pat.format(a.name) if a.converter is not None: lines.append( fmt_setter_with_converter( attr_name, init_factory_name + "(%s)" % (maybe_self,), has_on_setattr, ) ) conv_name = _init_converter_pat % (a.name,) names_for_globals[conv_name] = a.converter else: lines.append( fmt_setter( attr_name, init_factory_name + "(%s)" % (maybe_self,), has_on_setattr, ) ) names_for_globals[init_factory_name] = a.default.factory else: if a.converter is not None: lines.append( fmt_setter_with_converter( attr_name, "attr_dict['%s'].default" % (attr_name,), has_on_setattr, ) ) conv_name = _init_converter_pat % (a.name,) names_for_globals[conv_name] = a.converter else: lines.append( fmt_setter( attr_name, "attr_dict['%s'].default" % (attr_name,), has_on_setattr, ) ) elif a.default is not NOTHING and not has_factory: arg = "%s=attr_dict['%s'].default" % (arg_name, attr_name) if a.kw_only: kw_only_args.append(arg) else: args.append(arg) if a.converter is not None: lines.append( fmt_setter_with_converter( attr_name, arg_name, has_on_setattr ) ) names_for_globals[ _init_converter_pat % (a.name,) ] = a.converter else: lines.append(fmt_setter(attr_name, arg_name, has_on_setattr)) elif has_factory: arg = "%s=NOTHING" % (arg_name,) if a.kw_only: kw_only_args.append(arg) else: args.append(arg) lines.append("if %s is not NOTHING:" % (arg_name,)) init_factory_name = _init_factory_pat.format(a.name) if a.converter is not None: lines.append( " " + fmt_setter_with_converter( attr_name, arg_name, has_on_setattr ) ) lines.append("else:") lines.append( " " + fmt_setter_with_converter( attr_name, init_factory_name + "(" + maybe_self + ")", has_on_setattr, ) ) names_for_globals[ _init_converter_pat % (a.name,) ] = a.converter else: lines.append( " " + fmt_setter(attr_name, arg_name, has_on_setattr) ) lines.append("else:") lines.append( " " + fmt_setter( attr_name, init_factory_name + "(" + maybe_self + ")", has_on_setattr, ) ) names_for_globals[init_factory_name] = a.default.factory else: if a.kw_only: kw_only_args.append(arg_name) else: args.append(arg_name) if a.converter is not None: lines.append( fmt_setter_with_converter( attr_name, arg_name, has_on_setattr ) ) names_for_globals[ _init_converter_pat % (a.name,) ] = a.converter else: lines.append(fmt_setter(attr_name, arg_name, has_on_setattr)) if a.init is True: if a.type is not None and a.converter is None: annotations[arg_name] = a.type elif a.converter is not None: # Try to get the type from the converter. t = _AnnotationExtractor(a.converter).get_first_param_type() if t: annotations[arg_name] = t if attrs_to_validate: # we can skip this if there are no validators. names_for_globals["_config"] = _config lines.append("if _config._run_validators is True:") for a in attrs_to_validate: val_name = "__attr_validator_" + a.name attr_name = "__attr_" + a.name lines.append( " %s(self, %s, self.%s)" % (val_name, attr_name, a.name) ) names_for_globals[val_name] = a.validator names_for_globals[attr_name] = a if post_init: lines.append("self.__attrs_post_init__()") # because this is set only after __attrs_post_init__ is called, a crash # will result if post-init tries to access the hash code. This seemed # preferable to setting this beforehand, in which case alteration to # field values during post-init combined with post-init accessing the # hash code would result in silent bugs. if cache_hash: if frozen: if slots: # if frozen and slots, then _setattr defined above init_hash_cache = "_setattr(self, '%s', %s)" else: # if frozen and not slots, then _inst_dict defined above init_hash_cache = "_inst_dict['%s'] = %s" else: init_hash_cache = "self.%s = %s" lines.append(init_hash_cache % (_hash_cache_field, "None")) # For exceptions we rely on BaseException.__init__ for proper # initialization. if is_exc: vals = ",".join("self." + a.name for a in attrs if a.init) lines.append("BaseException.__init__(self, %s)" % (vals,)) args = ", ".join(args) if kw_only_args: args += "%s*, %s" % ( ", " if args else "", # leading comma ", ".join(kw_only_args), # kw_only args ) return ( """\ def {init_name}(self, {args}): {lines} """.format( init_name=("__attrs_init__" if attrs_init else "__init__"), args=args, lines="\n ".join(lines) if lines else "pass", ), names_for_globals, annotations, )
_ClassBuilder
python
anthropics__anthropic-sdk-python
src/anthropic/types/citation_char_location.py
{ "start": 224, "end": 473 }
class ____(BaseModel): cited_text: str document_index: int document_title: Optional[str] = None end_char_index: int file_id: Optional[str] = None start_char_index: int type: Literal["char_location"]
CitationCharLocation
python
great-expectations__great_expectations
great_expectations/expectations/core/expect_column_pair_values_to_be_in_set.py
{ "start": 1382, "end": 10151 }
class ____(ColumnPairMapExpectation): __doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION} ExpectColumnPairValuesToBeInSet is a \ Column Pair Map Expectation. Column Pair Map Expectations are evaluated for a pair of columns and ask a yes/no question about the row-wise relationship between those two columns. Based on the result, they then calculate the percentage of rows that gave a positive answer. If the percentage is high enough, the Expectation considers that data valid. Args: column_A (str): {COLUMN_A_DESCRIPTION} column_B (str): {COLUMN_B_DESCRIPTION} value_pairs_set (list of tuples): {VALUE_PAIRS_SET_DESCRIPTION} Other Parameters: ignore_row_if (str): \ "both_values_are_missing", "either_value_is_missing", "neither" \ If specified, sets the condition on which a given row is to be ignored. Default "neither". mostly (None or a float between 0 and 1): \ {MOSTLY_DESCRIPTION} \ For more detail, see [mostly](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#mostly). Default 1. result_format (str or None): \ Which output mode to use: BOOLEAN_ONLY, BASIC, COMPLETE, or SUMMARY. \ For more detail, see [result_format](https://docs.greatexpectations.io/docs/reference/expectations/result_format). catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see [catch_exceptions](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#catch_exceptions). meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \ For more detail, see [meta](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#meta). severity (str or None): \ {FAILURE_SEVERITY_DESCRIPTION} \ For more detail, see [failure severity](https://docs.greatexpectations.io/docs/cloud/expectations/expectations_overview/#failure-severity). Returns: An [ExpectationSuiteValidationResult](https://docs.greatexpectations.io/docs/terms/validation_result) Exact fields vary depending on the values passed to result_format, catch_exceptions, and meta. Supported Data Sources: [{SUPPORTED_DATA_SOURCES[0]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[1]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[2]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[3]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[4]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[5]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[6]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[7]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[8]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[9]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[10]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[11]}](https://docs.greatexpectations.io/docs/application_integration_support/) Data Quality Issues: {DATA_QUALITY_ISSUES[0]} Example Data: test test2 0 1 1 1 2 1 2 4 1 Code Examples: Passing Case: Input: ExpectColumnPairValuesToBeInSet( column_A="test", column_B="test2", value_pairs_set=[(2,1), (1,1)], mostly=.5 ) Output: {{ "exception_info": {{ "raised_exception": false, "exception_traceback": null, "exception_message": null }}, "result": {{ "element_count": 3, "unexpected_count": 1, "unexpected_percent": 33.33333333333333, "partial_unexpected_list": [ [ 4, 1 ] ], "missing_count": 0, "missing_percent": 0.0, "unexpected_percent_total": 33.33333333333333, "unexpected_percent_nonmissing": 33.33333333333333 }}, "meta": {{}}, "success": true }} Failing Case: Input: ExpectColumnPairValuesToBeInSet( column_A="test", column_B="test2", value_pairs_set=[(1,2) (4,1)], ) Output: {{ "exception_info": {{ "raised_exception": false, "exception_traceback": null, "exception_message": null }}, "result": {{ "element_count": 3, "unexpected_count": 2, "unexpected_percent": 66.66666666666666, "partial_unexpected_list": [ [ 1, 1 ], [ 2, 1 ] ], "missing_count": 0, "missing_percent": 0.0, "unexpected_percent_total": 66.66666666666666, "unexpected_percent_nonmissing": 66.66666666666666 }}, "meta": {{}}, "success": false }} """ # noqa: E501 # FIXME CoP value_pairs_set: Union[List[Tuple[Any, Any]], SuiteParameterDict] ignore_row_if: Union[ Literal["both_values_are_missing", "either_value_is_missing", "neither"], SuiteParameterDict, ] = "both_values_are_missing" # This dictionary contains metadata for display in the public gallery library_metadata: ClassVar[Dict[str, Union[str, list, bool]]] = { "maturity": "production", "tags": [ "core expectation", "column pair map expectation", ], "contributors": ["@great_expectations"], "requirements": [], "has_full_test_suite": True, "manually_reviewed_code": True, } _library_metadata = library_metadata map_metric = "column_pair_values.in_set" success_keys: ClassVar[Tuple[str, ...]] = ( "value_pairs_set", "ignore_row_if", "mostly", ) args_keys = ( "column_A", "column_B", "value_pairs_set", ) class Config: title = "Expect column pair values to be in set" @staticmethod def schema_extra( schema: Dict[str, Any], model: Type[ExpectColumnPairValuesToBeInSet] ) -> None: ColumnPairMapExpectation.Config.schema_extra(schema, model) schema["properties"]["metadata"]["properties"].update( { "data_quality_issues": { "title": "Data Quality Issues", "type": "array", "const": DATA_QUALITY_ISSUES, }, "library_metadata": { "title": "Library Metadata", "type": "object", "const": model._library_metadata, }, "short_description": { "title": "Short Description", "type": "string", "const": EXPECTATION_SHORT_DESCRIPTION, }, "supported_data_sources": { "title": "Supported Data Sources", "type": "array", "const": SUPPORTED_DATA_SOURCES, }, } )
ExpectColumnPairValuesToBeInSet
python
gevent__gevent
src/gevent/tests/test__socket_send_memoryview.py
{ "start": 659, "end": 779 }
class ____(unittest.TestCase): def test_send(self): import socket _send(socket)
TestSendBuiltinSocket
python
PrefectHQ__prefect
src/prefect/client/schemas/actions.py
{ "start": 23657, "end": 24111 }
class ____(ActionBaseModel): """Data used by the Prefect REST API to update a block type.""" logo_url: Optional[objects.HttpUrl] = Field(default=None) documentation_url: Optional[objects.HttpUrl] = Field(default=None) description: Optional[str] = Field(default=None) code_example: Optional[str] = Field(default=None) @classmethod def updatable_fields(cls) -> set[str]: return get_class_fields_only(cls)
BlockTypeUpdate
python
pytorch__pytorch
test/onnx/model_defs/squeezenet.py
{ "start": 968, "end": 3497 }
class ____(nn.Module): def __init__(self, version=1.0, num_classes=1000, ceil_mode=False): super().__init__() if version not in [1.0, 1.1]: raise ValueError( f"Unsupported SqueezeNet version {version}:1.0 or 1.1 expected" ) self.num_classes = num_classes if version == 1.0: self.features = nn.Sequential( nn.Conv2d(3, 96, kernel_size=7, stride=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=ceil_mode), Fire(96, 16, 64, 64), Fire(128, 16, 64, 64), Fire(128, 32, 128, 128), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=ceil_mode), Fire(256, 32, 128, 128), Fire(256, 48, 192, 192), Fire(384, 48, 192, 192), Fire(384, 64, 256, 256), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=ceil_mode), Fire(512, 64, 256, 256), ) else: self.features = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3, stride=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=ceil_mode), Fire(64, 16, 64, 64), Fire(128, 16, 64, 64), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=ceil_mode), Fire(128, 32, 128, 128), Fire(256, 32, 128, 128), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=ceil_mode), Fire(256, 48, 192, 192), Fire(384, 48, 192, 192), Fire(384, 64, 256, 256), Fire(512, 64, 256, 256), ) # Final convolution is initialized differently from the rest final_conv = nn.Conv2d(512, self.num_classes, kernel_size=1) self.classifier = nn.Sequential( nn.Dropout(p=0.5), final_conv, nn.ReLU(inplace=True), nn.AvgPool2d(13) ) for m in self.modules(): if isinstance(m, nn.Conv2d): if m is final_conv: init.normal_(m.weight.data, mean=0.0, std=0.01) else: init.kaiming_uniform_(m.weight.data) if m.bias is not None: m.bias.data.zero_() def forward(self, x): x = self.features(x) x = self.classifier(x) return x.view(x.size(0), self.num_classes)
SqueezeNet
python
cython__cython
Cython/Compiler/TypeSlots.py
{ "start": 25444, "end": 26007 }
class ____(SlotDescriptor): # Slot descriptor for the base class slot. def __init__(self, name): SlotDescriptor.__init__(self, name, dynamic=True) def generate_dynamic_init_code(self, scope, code): base_type = scope.parent_type.base_type if base_type: base_typeptr_cname = code.typeptr_cname_in_module_state(base_type) code.putln("%s->%s = %s;" % ( code.typeptr_cname_in_module_state(scope.parent_type), self.slot_name, base_typeptr_cname))
BaseClassSlot
python
apache__airflow
task-sdk/src/airflow/sdk/api/datamodels/_generated.py
{ "start": 1437, "end": 2230 }
class ____(BaseModel): """ Profile of an asset-like object. Asset will have name, uri defined, with type set to 'Asset'. AssetNameRef will have name defined, type set to 'AssetNameRef'. AssetUriRef will have uri defined, type set to 'AssetUriRef'. AssetAlias will have name defined, type set to 'AssetAlias'. Note that 'type' here is distinct from 'asset_type' the user declares on an Asset (or subclass). This field is for distinguishing between different asset-related types (Asset, AssetRef, or AssetAlias). """ model_config = ConfigDict( extra="forbid", ) name: Annotated[str | None, Field(title="Name")] = None uri: Annotated[str | None, Field(title="Uri")] = None type: Annotated[str, Field(title="Type")]
AssetProfile
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_translate.py
{ "start": 18372, "end": 20669 }
class ____: @mock.patch("airflow.providers.google.cloud.links.translate.TranslationModelsListLink.persist") @mock.patch("airflow.providers.google.cloud.operators.translate.TranslateHook") def test_minimal_green_path(self, mock_hook, mock_link_persist): MODEL_ID_1 = "sample_model_1" MODEL_ID_2 = "sample_model_2" model_result_1 = automl_translation.Model( dict( display_name="model_1_display_name", name=f"projects/{PROJECT_ID}/locations/{LOCATION}/models/{MODEL_ID_1}", dataset=f"projects/{PROJECT_ID}/locations/{LOCATION}/datasets/ds_for_model_1", source_language_code="en", target_language_code="es", ) ) model_result_2 = automl_translation.Model( dict( display_name="model_2_display_name", name=f"projects/{PROJECT_ID}/locations/{LOCATION}/models/{MODEL_ID_2}", dataset=f"projects/{PROJECT_ID}/locations/{LOCATION}/datasets/ds_for_model_2", source_language_code="uk", target_language_code="en", ) ) mock_hook.return_value.list_models.return_value = [model_result_1, model_result_2] mock_hook.return_value.extract_object_id = TranslateHook.extract_object_id op = TranslateModelsListOperator( task_id="task_id", project_id=PROJECT_ID, location=LOCATION, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, timeout=TIMEOUT_VALUE, retry=DEFAULT, ) context = mock.MagicMock() result = op.execute(context=context) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.list_models.assert_called_once_with( project_id=PROJECT_ID, location=LOCATION, timeout=TIMEOUT_VALUE, retry=DEFAULT, metadata=(), ) assert result == [MODEL_ID_1, MODEL_ID_2] mock_link_persist.assert_called_once_with( context=context, project_id=PROJECT_ID, )
TestTranslateListModels
python
gevent__gevent
src/gevent/tests/test__socket_dns.py
{ "start": 22689, "end": 23951 }
class ____(HostsFile): def iter_all_host_addr_pairs(self): for name, addr in super(SanitizedHostsFile, self).iter_all_host_addr_pairs(): if (RESOLVER_NOT_SYSTEM and (name.endswith('local') # ignore bonjour, ares can't find them # ignore common aliases that ares can't find or addr == '255.255.255.255' or name == 'broadcasthost' # We get extra results from some impls, like OS X # it returns DGRAM results or name == 'localhost')): continue # pragma: no cover if name.endswith('local'): # These can only be found if bonjour is running, # and are very slow to do so with the system resolver on OS X continue yield name, addr @greentest.skipIf(greentest.RUNNING_ON_CI, "This sometimes randomly fails on Travis with ares and on appveyor, beginning Feb 13, 2018") # Probably due to round-robin DNS, # since this is not actually the system's etc hosts file. # TODO: Rethink this. We need something reliable. Go back to using # the system's etc hosts?
SanitizedHostsFile
python
ray-project__ray
python/ray/train/_internal/accelerator.py
{ "start": 13, "end": 107 }
class ____(abc.ABC): """A utility that contains methods to accelerate training."""
Accelerator
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 955895, "end": 957297 }
class ____(sgqlc.types.Type): """Autogenerated return type of RevokeEnterpriseOrganizationsMigratorRole """ __schema__ = github_schema __field_names__ = ("client_mutation_id", "organizations") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""" organizations = sgqlc.types.Field( OrganizationConnection, graphql_name="organizations", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ("before", sgqlc.types.Arg(String, graphql_name="before", default=None)), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ) ), ) """The organizations that had the migrator role revoked for the given user. Arguments: * `after` (`String`): Returns the elements in the list that come after the specified cursor. * `before` (`String`): Returns the elements in the list that come before the specified cursor. * `first` (`Int`): Returns the first _n_ elements from the list. * `last` (`Int`): Returns the last _n_ elements from the list. """
RevokeEnterpriseOrganizationsMigratorRolePayload
python
astral-sh__uv
python/uv/_find_uv.py
{ "start": 76, "end": 3139 }
class ____(FileNotFoundError): ... def find_uv_bin() -> str: """Return the uv binary path.""" uv_exe = "uv" + sysconfig.get_config_var("EXE") targets = [ # The scripts directory for the current Python sysconfig.get_path("scripts"), # The scripts directory for the base prefix sysconfig.get_path("scripts", vars={"base": sys.base_prefix}), # Above the package root, e.g., from `pip install --prefix` or `uv run --with` ( # On Windows, with module path `<prefix>/Lib/site-packages/uv` _join(_matching_parents(_module_path(), "Lib/site-packages/uv"), "Scripts") if sys.platform == "win32" # On Unix, with module path `<prefix>/lib/python3.13/site-packages/uv` else _join( _matching_parents(_module_path(), "lib/python*/site-packages/uv"), "bin" ) ), # Adjacent to the package root, e.g., from `pip install --target` # with module path `<target>/uv` _join(_matching_parents(_module_path(), "uv"), "bin"), # The user scheme scripts directory, e.g., `~/.local/bin` sysconfig.get_path("scripts", scheme=_user_scheme()), ] seen = [] for target in targets: if not target: continue if target in seen: continue seen.append(target) path = os.path.join(target, uv_exe) if os.path.isfile(path): return path locations = "\n".join(f" - {target}" for target in seen) raise UvNotFound( f"Could not find the uv binary in any of the following locations:\n{locations}\n" ) def _module_path() -> str | None: path = os.path.dirname(__file__) return path def _matching_parents(path: str | None, match: str) -> str | None: """ Return the parent directory of `path` after trimming a `match` from the end. The match is expected to contain `/` as a path separator, while the `path` is expected to use the platform's path separator (e.g., `os.sep`). The path components are compared case-insensitively and a `*` wildcard can be used in the `match`. """ from fnmatch import fnmatch if not path: return None parts = path.split(os.sep) match_parts = match.split("/") if len(parts) < len(match_parts): return None if not all( fnmatch(part, match_part) for part, match_part in zip(reversed(parts), reversed(match_parts)) ): return None return os.sep.join(parts[: -len(match_parts)]) def _join(path: str | None, *parts: str) -> str | None: if not path: return None return os.path.join(path, *parts) def _user_scheme() -> str: if sys.version_info >= (3, 10): user_scheme = sysconfig.get_preferred_scheme("user") elif os.name == "nt": user_scheme = "nt_user" elif sys.platform == "darwin" and sys._framework: user_scheme = "osx_framework_user" else: user_scheme = "posix_user" return user_scheme
UvNotFound
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 473919, "end": 475542 }
class ____(sgqlc.types.Type): """Represents an auto-merge request for a pull request""" __schema__ = github_schema __field_names__ = ("author_email", "commit_body", "commit_headline", "enabled_at", "enabled_by", "merge_method", "pull_request") author_email = sgqlc.types.Field(String, graphql_name="authorEmail") """The email address of the author of this auto-merge request.""" commit_body = sgqlc.types.Field(String, graphql_name="commitBody") """The commit message of the auto-merge request. If a merge queue is required by the base branch, this value will be set by the merge queue when merging. """ commit_headline = sgqlc.types.Field(String, graphql_name="commitHeadline") """The commit title of the auto-merge request. If a merge queue is required by the base branch, this value will be set by the merge queue when merging """ enabled_at = sgqlc.types.Field(DateTime, graphql_name="enabledAt") """When was this auto-merge request was enabled.""" enabled_by = sgqlc.types.Field(Actor, graphql_name="enabledBy") """The actor who created the auto-merge request.""" merge_method = sgqlc.types.Field(sgqlc.types.non_null(PullRequestMergeMethod), graphql_name="mergeMethod") """The merge method of the auto-merge request. If a merge queue is required by the base branch, this value will be set by the merge queue when merging. """ pull_request = sgqlc.types.Field(sgqlc.types.non_null("PullRequest"), graphql_name="pullRequest") """The pull request that this auto-merge request is set against."""
AutoMergeRequest
python
rq__rq
rq/logutils.py
{ "start": 2153, "end": 4994 }
class ____(logging.StreamHandler): levels = { logging.WARNING: yellow, logging.ERROR: red, logging.CRITICAL: red, } def __init__(self, exclude=None, *args, **kwargs): self.exclude = exclude super().__init__(*args, **kwargs) @property def is_tty(self): isatty = getattr(self.stream, 'isatty', None) return isatty and isatty() def format(self, record): message = logging.StreamHandler.format(self, record) if self.is_tty: # Don't colorize any traceback parts = message.split('\n', 1) parts[0] = ' '.join([parts[0].split(' ', 1)[0], parts[0].split(' ', 1)[1]]) message = '\n'.join(parts) return message def setup_loghandlers( level: Union[int, str, None] = None, date_format: str = DEFAULT_LOGGING_DATE_FORMAT, log_format: str = DEFAULT_LOGGING_FORMAT, name: str = 'rq.worker', ): """Sets up a log handler. Args: level (Union[int, str, None], optional): The log level. Access an integer level (10-50) or a string level ("info", "debug" etc). Defaults to None. date_format (str, optional): The date format to use. Defaults to DEFAULT_LOGGING_DATE_FORMAT ('%H:%M:%S'). log_format (str, optional): The log format to use. Defaults to DEFAULT_LOGGING_FORMAT ('%(asctime)s %(message)s'). name (str, optional): The logger name. Defaults to 'rq.worker'. """ logger = logging.getLogger(name) if not _has_effective_handler(logger): formatter = logging.Formatter(fmt=log_format, datefmt=date_format) handler = ColorizingStreamHandler(stream=sys.stdout) handler.setFormatter(formatter) handler.addFilter(lambda record: record.levelno < logging.ERROR) error_handler = ColorizingStreamHandler(stream=sys.stderr) error_handler.setFormatter(formatter) error_handler.addFilter(lambda record: record.levelno >= logging.ERROR) logger.addHandler(handler) logger.addHandler(error_handler) if level is not None: # The level may be a numeric value (e.g. when using the logging module constants) # Or a string representation of the logging level logger.setLevel(level if isinstance(level, int) else level.upper()) def _has_effective_handler(logger) -> bool: """ Checks if a logger has a handler that will catch its messages in its logger hierarchy. Args: logger (logging.Logger): The logger to be checked. Returns: is_configured (bool): True if a handler is found for the logger, False otherwise. """ while True: if logger.handlers: return True if not logger.parent: return False logger = logger.parent
ColorizingStreamHandler
python
optuna__optuna
optuna/distributions.py
{ "start": 7933, "end": 8916 }
class ____(FloatDistribution): """A uniform distribution in the log domain. This object is instantiated by :func:`~optuna.trial.Trial.suggest_float` with ``log=True``, and passed to :mod:`~optuna.samplers` in general. Attributes: low: Lower endpoint of the range of the distribution. ``low`` is included in the range. ``low`` must be larger than 0. ``low`` must be less than or equal to ``high``. high: Upper endpoint of the range of the distribution. ``high`` is included in the range. ``high`` must be greater than or equal to ``low``. """ def __init__(self, low: float, high: float) -> None: super().__init__(low=low, high=high, log=True, step=None) def _asdict(self) -> dict: d = copy.deepcopy(self.__dict__) d.pop("log") d.pop("step") return d @deprecated_class("3.0.0", "6.0.0", text=_float_distribution_deprecated_msg)
LogUniformDistribution
python
rapidsai__cudf
python/cudf/cudf/core/dtypes.py
{ "start": 12720, "end": 18492 }
class ____(_BaseDtype): """ Type to represent list data. Parameters ---------- element_type : object A dtype with which represents the element types in the list. Attributes ---------- element_type leaf_type Methods ------- from_arrow to_arrow Examples -------- >>> import cudf >>> list_dtype = cudf.ListDtype("int32") >>> list_dtype ListDtype(int32) A nested list dtype can be created by: >>> nested_list_dtype = cudf.ListDtype(list_dtype) >>> nested_list_dtype ListDtype(ListDtype(int32)) """ name: str = "list" def __init__(self, element_type: Dtype) -> None: self._element_type = cudf.dtype(element_type) @cached_property def element_type(self) -> DtypeObj: """ Returns the element type of the ``ListDtype``. Returns ------- Dtype Examples -------- >>> import cudf >>> deep_nested_type = cudf.ListDtype(cudf.ListDtype(cudf.ListDtype("float32"))) >>> deep_nested_type ListDtype(ListDtype(ListDtype(float32))) >>> deep_nested_type.element_type ListDtype(ListDtype(float32)) >>> deep_nested_type.element_type.element_type ListDtype(float32) >>> deep_nested_type.element_type.element_type.element_type # doctest: +SKIP 'float32' """ return self._element_type @cached_property def leaf_type(self) -> DtypeObj: """ Returns the type of the leaf values. Examples -------- >>> import cudf >>> deep_nested_type = cudf.ListDtype(cudf.ListDtype(cudf.ListDtype("float32"))) >>> deep_nested_type ListDtype(ListDtype(ListDtype(float32))) >>> deep_nested_type.leaf_type # doctest: +SKIP 'float32' """ if isinstance(self.element_type, ListDtype): return self.element_type.leaf_type else: return self.element_type @property def type(self): # TODO: we should change this to return something like a # ListDtypeType, once we figure out what that should look like return pa.array @classmethod def from_arrow(cls, typ: pa.ListType) -> Self: """ Creates a ``ListDtype`` from ``pyarrow.ListType``. Parameters ---------- typ : pyarrow.ListType A ``pyarrow.ListType`` that has to be converted to ``ListDtype``. Returns ------- obj : ``ListDtype`` Examples -------- >>> import cudf >>> import pyarrow as pa >>> arrow_type = pa.infer_type([[1]]) >>> arrow_type ListType(list<item: int64>) >>> list_dtype = cudf.ListDtype.from_arrow(arrow_type) >>> list_dtype ListDtype(int64) """ return cls(cudf_dtype_from_pa_type(typ.value_type)) def to_arrow(self) -> pa.ListType: """ Convert to a ``pyarrow.ListType`` Examples -------- >>> import cudf >>> list_dtype = cudf.ListDtype(cudf.ListDtype("float32")) >>> list_dtype ListDtype(ListDtype(float32)) >>> list_dtype.to_arrow() ListType(list<item: list<item: float>>) """ return pa.list_(cudf_dtype_to_pa_type(self.element_type)) def __eq__(self, other) -> bool: if isinstance(other, str): return other == self.name if not isinstance(other, ListDtype): return False return self.element_type == other.element_type def __repr__(self) -> str: if isinstance(self.element_type, (ListDtype, StructDtype)): return f"{type(self).__name__}({self.element_type!r})" else: return f"{type(self).__name__}({self.element_type})" def __hash__(self) -> int: return hash(self.to_arrow()) def serialize(self) -> tuple[dict, list]: header: dict[str, Dtype] = {} frames = [] if isinstance(self.element_type, _BaseDtype): header["element-type"], frames = ( self.element_type.device_serialize() ) else: header["element-type"] = getattr( self.element_type, "name", self.element_type ) header["frame_count"] = len(frames) return header, frames @classmethod def deserialize(cls, header: dict, frames: list) -> Self: _check_type(cls, header, frames) if isinstance(header["element-type"], dict): element_type = Serializable.device_deserialize( header["element-type"], frames ) else: element_type = header["element-type"] return cls(element_type=element_type) @cached_property def itemsize(self) -> int: return self.element_type.itemsize def _recursively_replace_fields(self, result: list) -> list: """ Return a new list result but with the keys of dict element by the keys in StructDtype.fields.keys(). Intended when result comes from pylibcudf without preserved nested field names. """ if isinstance(self.element_type, StructDtype): return [ self.element_type._recursively_replace_fields(res) if isinstance(res, dict) else res for res in result ] elif isinstance(self.element_type, ListDtype): return [ self.element_type._recursively_replace_fields(res) if isinstance(res, list) else res for res in result ] return result
ListDtype