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 | Pylons__pyramid | docs/quick_tutorial/views/tutorial/tests.py | {
"start": 673,
"end": 1126
} | class ____(unittest.TestCase):
def setUp(self):
from tutorial import main
app = main({})
from webtest import TestApp
self.testapp = TestApp(app)
def test_home(self):
res = self.testapp.get('/', status=200)
self.assertIn(b'<body>Visit', res.body)
def test_hello(self):
res = self.testapp.get('/howdy', status=200)
self.assertIn(b'<body>Go back', res.body)
| TutorialFunctionalTests |
python | huggingface__transformers | tests/models/seggpt/test_image_processing_seggpt.py | {
"start": 3543,
"end": 13419
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = SegGptImageProcessor if is_vision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester = SegGptImageProcessingTester(self)
@property
def image_processor_dict(self):
return self.image_processor_tester.prepare_image_processor_dict()
def test_image_processor_properties(self):
image_processing = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(image_processing, "image_mean"))
self.assertTrue(hasattr(image_processing, "image_std"))
self.assertTrue(hasattr(image_processing, "do_normalize"))
self.assertTrue(hasattr(image_processing, "do_resize"))
self.assertTrue(hasattr(image_processing, "size"))
def test_image_processor_from_dict_with_kwargs(self):
image_processor = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size, {"height": 18, "width": 18})
image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42)
self.assertEqual(image_processor.size, {"height": 42, "width": 42})
def test_image_processor_palette(self):
num_labels = 3
image_processing = self.image_processing_class(**self.image_processor_dict)
palette = image_processing.get_palette(num_labels)
self.assertEqual(len(palette), num_labels + 1)
self.assertEqual(palette[0], (0, 0, 0))
def test_mask_equivalence(self):
image_processor = SegGptImageProcessor()
mask_binary = prepare_mask()
mask_rgb = mask_binary.convert("RGB")
inputs_binary = image_processor(images=None, prompt_masks=mask_binary, return_tensors="pt")
inputs_rgb = image_processor(images=None, prompt_masks=mask_rgb, return_tensors="pt", do_convert_rgb=False)
self.assertTrue((inputs_binary["prompt_masks"] == inputs_rgb["prompt_masks"]).all().item())
def test_mask_to_rgb(self):
image_processing = self.image_processing_class(**self.image_processor_dict)
mask = prepare_mask()
mask = np.array(mask)
mask = (mask > 0).astype(np.uint8)
def check_two_colors(image, color1=(0, 0, 0), color2=(255, 255, 255)):
pixels = image.transpose(1, 2, 0).reshape(-1, 3)
unique_colors = np.unique(pixels, axis=0)
if len(unique_colors) == 2 and (color1 in unique_colors) and (color2 in unique_colors):
return True
else:
return False
num_labels = 1
palette = image_processing.get_palette(num_labels)
# Should only duplicate repeat class indices map, hence only (0,0,0) and (1,1,1)
mask_duplicated = image_processing.mask_to_rgb(mask)
# Mask using palette, since only 1 class is present we have colors (0,0,0) and (255,255,255)
mask_painted = image_processing.mask_to_rgb(mask, palette=palette)
self.assertTrue(check_two_colors(mask_duplicated, color2=(1, 1, 1)))
self.assertTrue(check_two_colors(mask_painted, color2=(255, 255, 255)))
def test_post_processing_semantic_segmentation(self):
image_processor = self.image_processing_class(**self.image_processor_dict)
outputs = self.image_processor_tester.get_fake_image_segmentation_output()
post_processed = image_processor.post_process_semantic_segmentation(outputs)
self.assertEqual(len(post_processed), self.image_processor_tester.batch_size)
expected_semantic_map_shape = self.image_processor_tester.expected_post_processed_shape()
self.assertEqual(post_processed[0].shape, expected_semantic_map_shape)
@slow
def test_pixel_values(self):
images, masks = prepare_img()
input_image = images[1]
prompt_image = images[0]
prompt_mask = masks[0]
image_processor = SegGptImageProcessor.from_pretrained("BAAI/seggpt-vit-large")
inputs = image_processor(
images=input_image,
prompt_images=prompt_image,
prompt_masks=prompt_mask,
return_tensors="pt",
do_convert_rgb=False,
)
# Verify pixel values
expected_prompt_pixel_values = torch.tensor(
[
[[-0.6965, -0.6965, -0.6965], [-0.6965, -0.6965, -0.6965], [-0.6965, -0.6965, -0.6965]],
[[1.6583, 1.6583, 1.6583], [1.6583, 1.6583, 1.6583], [1.6583, 1.6583, 1.6583]],
[[2.3088, 2.3088, 2.3088], [2.3088, 2.3088, 2.3088], [2.3088, 2.3088, 2.3088]],
]
)
expected_pixel_values = torch.tensor(
[
[[1.6324, 1.6153, 1.5810], [1.6153, 1.5982, 1.5810], [1.5810, 1.5639, 1.5639]],
[[1.2731, 1.2556, 1.2206], [1.2556, 1.2381, 1.2031], [1.2206, 1.2031, 1.1681]],
[[1.6465, 1.6465, 1.6465], [1.6465, 1.6465, 1.6465], [1.6291, 1.6291, 1.6291]],
]
)
expected_prompt_masks = torch.tensor(
[
[[-2.1179, -2.1179, -2.1179], [-2.1179, -2.1179, -2.1179], [-2.1179, -2.1179, -2.1179]],
[[-2.0357, -2.0357, -2.0357], [-2.0357, -2.0357, -2.0357], [-2.0357, -2.0357, -2.0357]],
[[-1.8044, -1.8044, -1.8044], [-1.8044, -1.8044, -1.8044], [-1.8044, -1.8044, -1.8044]],
]
)
torch.testing.assert_close(inputs.pixel_values[0, :, :3, :3], expected_pixel_values, rtol=1e-4, atol=1e-4)
torch.testing.assert_close(
inputs.prompt_pixel_values[0, :, :3, :3], expected_prompt_pixel_values, rtol=1e-4, atol=1e-4
)
torch.testing.assert_close(inputs.prompt_masks[0, :, :3, :3], expected_prompt_masks, rtol=1e-4, atol=1e-4)
def test_prompt_mask_equivalence(self):
image_processor = self.image_processing_class(**self.image_processor_dict)
image_size = self.image_processor_tester.image_size
# Single Mask Examples
expected_single_shape = [1, 3, image_size, image_size]
# Single Semantic Map (2D)
image_np_2d = np.ones((image_size, image_size))
image_pt_2d = torch.ones((image_size, image_size))
image_pil_2d = Image.fromarray(image_np_2d)
inputs_np_2d = image_processor(images=None, prompt_masks=image_np_2d, return_tensors="pt")
inputs_pt_2d = image_processor(images=None, prompt_masks=image_pt_2d, return_tensors="pt")
inputs_pil_2d = image_processor(images=None, prompt_masks=image_pil_2d, return_tensors="pt")
self.assertTrue((inputs_np_2d["prompt_masks"] == inputs_pt_2d["prompt_masks"]).all().item())
self.assertTrue((inputs_np_2d["prompt_masks"] == inputs_pil_2d["prompt_masks"]).all().item())
self.assertEqual(list(inputs_np_2d["prompt_masks"].shape), expected_single_shape)
# Single RGB Images (3D)
image_np_3d = np.ones((3, image_size, image_size))
image_pt_3d = torch.ones((3, image_size, image_size))
image_pil_3d = Image.fromarray(image_np_3d.transpose(1, 2, 0).astype(np.uint8))
inputs_np_3d = image_processor(
images=None, prompt_masks=image_np_3d, return_tensors="pt", do_convert_rgb=False
)
inputs_pt_3d = image_processor(
images=None, prompt_masks=image_pt_3d, return_tensors="pt", do_convert_rgb=False
)
inputs_pil_3d = image_processor(
images=None, prompt_masks=image_pil_3d, return_tensors="pt", do_convert_rgb=False
)
self.assertTrue((inputs_np_3d["prompt_masks"] == inputs_pt_3d["prompt_masks"]).all().item())
self.assertTrue((inputs_np_3d["prompt_masks"] == inputs_pil_3d["prompt_masks"]).all().item())
self.assertEqual(list(inputs_np_3d["prompt_masks"].shape), expected_single_shape)
# Batched Examples
expected_batched_shape = [2, 3, image_size, image_size]
# Batched Semantic Maps (3D)
image_np_2d_batched = np.ones((2, image_size, image_size))
image_pt_2d_batched = torch.ones((2, image_size, image_size))
inputs_np_2d_batched = image_processor(images=None, prompt_masks=image_np_2d_batched, return_tensors="pt")
inputs_pt_2d_batched = image_processor(images=None, prompt_masks=image_pt_2d_batched, return_tensors="pt")
self.assertTrue((inputs_np_2d_batched["prompt_masks"] == inputs_pt_2d_batched["prompt_masks"]).all().item())
self.assertEqual(list(inputs_np_2d_batched["prompt_masks"].shape), expected_batched_shape)
# Batched RGB images
image_np_4d = np.ones((2, 3, image_size, image_size))
image_pt_4d = torch.ones((2, 3, image_size, image_size))
inputs_np_4d = image_processor(
images=None, prompt_masks=image_np_4d, return_tensors="pt", do_convert_rgb=False
)
inputs_pt_4d = image_processor(
images=None, prompt_masks=image_pt_4d, return_tensors="pt", do_convert_rgb=False
)
self.assertTrue((inputs_np_4d["prompt_masks"] == inputs_pt_4d["prompt_masks"]).all().item())
self.assertEqual(list(inputs_np_4d["prompt_masks"].shape), expected_batched_shape)
# Comparing Single and Batched Examples
self.assertTrue((inputs_np_2d["prompt_masks"][0] == inputs_np_3d["prompt_masks"][0]).all().item())
self.assertTrue((inputs_np_2d_batched["prompt_masks"][0] == inputs_np_2d["prompt_masks"][0]).all().item())
self.assertTrue((inputs_np_2d_batched["prompt_masks"][0] == inputs_np_3d["prompt_masks"][0]).all().item())
self.assertTrue((inputs_np_2d_batched["prompt_masks"][0] == inputs_np_4d["prompt_masks"][0]).all().item())
self.assertTrue((inputs_np_2d_batched["prompt_masks"][0] == inputs_np_3d["prompt_masks"][0]).all().item())
| SegGptImageProcessingTest |
python | Delgan__loguru | loguru/_logger.py | {
"start": 8531,
"end": 102542
} | class ____:
"""An object to dispatch logging messages to configured handlers.
The |Logger| is the core object of ``loguru``, every logging configuration and usage pass
through a call to one of its methods. There is only one logger, so there is no need to retrieve
one before usage.
Once the ``logger`` is imported, it can be used to write messages about events happening in your
code. By reading the output logs of your application, you gain a better understanding of the
flow of your program and you more easily track and debug unexpected behaviors.
Handlers to which the logger sends log messages are added using the |add| method. Note that you
can use the |Logger| right after import as it comes pre-configured (logs are emitted to
|sys.stderr| by default). Messages can be logged with different severity levels and they can be
formatted using curly braces (it uses |str.format| under the hood).
When a message is logged, a "record" is associated with it. This record is a dict which contains
information about the logging context: time, function, file, line, thread, level... It also
contains the ``__name__`` of the module, this is why you don't need named loggers.
You should not instantiate a |Logger| by yourself, use ``from loguru import logger`` instead.
"""
def __init__(self, core, exception, depth, record, lazy, colors, raw, capture, patchers, extra):
self._core = core
self._options = (exception, depth, record, lazy, colors, raw, capture, patchers, extra)
def __repr__(self):
return "<loguru.logger handlers=%r>" % list(self._core.handlers.values())
def add(
self,
sink,
*,
level=_defaults.LOGURU_LEVEL,
format=_defaults.LOGURU_FORMAT,
filter=_defaults.LOGURU_FILTER,
colorize=_defaults.LOGURU_COLORIZE,
serialize=_defaults.LOGURU_SERIALIZE,
backtrace=_defaults.LOGURU_BACKTRACE,
diagnose=_defaults.LOGURU_DIAGNOSE,
enqueue=_defaults.LOGURU_ENQUEUE,
context=_defaults.LOGURU_CONTEXT,
catch=_defaults.LOGURU_CATCH,
**kwargs
):
r"""Add a handler sending log messages to a sink adequately configured.
Parameters
----------
sink : |file-like object|_, |str|, |Path|, |callable|_, |coroutine function|_ or |Handler|
An object in charge of receiving formatted logging messages and propagating them to an
appropriate endpoint.
level : |int| or |str|, optional
The minimum severity level from which logged messages should be sent to the sink.
format : |str| or |callable|_, optional
The template used to format logged messages before being sent to the sink. Such template
can be dynamically generated by a function taking the log record as parameter.
filter : |callable|_, |str| or |dict|, optional
A directive optionally used to decide for each logged message whether it should be sent
to the sink or not.
colorize : |bool|, optional
Whether the color markups contained in the formatted message should be converted to ansi
codes for terminal coloration, or stripped otherwise. If ``None``, the choice is
automatically made based on the sink being a tty or not.
serialize : |bool|, optional
Whether the logged message and its records should be first converted to a JSON string
before being sent to the sink.
backtrace : |bool|, optional
Whether the exception trace formatted should be extended upward, beyond the catching
point, to show the full stacktrace which generated the error.
diagnose : |bool|, optional
Whether the exception trace should display the variables values to ease the debugging.
This should be set to ``False`` in production to avoid leaking sensitive data.
enqueue : |bool|, optional
Whether the messages to be logged should first pass through a multiprocessing-safe queue
before reaching the sink. This is useful while logging to a file through multiple
processes. This also has the advantage of making logging calls non-blocking.
context : |multiprocessing.Context| or |str|, optional
A context object or name that will be used for all tasks involving internally the
|multiprocessing| module, in particular when ``enqueue=True``. If ``None``, the default
context is used.
catch : |bool|, optional
Whether errors occurring while sink handles logs messages should be automatically
caught. If ``True``, an exception message is displayed on |sys.stderr| but the exception
is not propagated to the caller, preventing your app to crash.
**kwargs
Additional parameters that are only valid to configure a coroutine or file sink (see
below).
If and only if the sink is a coroutine function, the following parameter applies:
Parameters
----------
loop : |AbstractEventLoop|, optional
The event loop in which the asynchronous logging task will be scheduled and executed. If
``None``, the loop used is the one returned by |asyncio.get_running_loop| at the time of
the logging call (task is discarded if there is no loop currently running).
If and only if the sink is a file path, the following parameters apply:
Parameters
----------
rotation : |str|, |int|, |time|, |timedelta|, |callable|_, or |list| of any of those
types, optional
Condition(s) indicating whenever the current logged file should be closed and a
new one started. If a list of conditions are provided, the current file is rotated
if any condition is true.
retention : |str|, |int|, |timedelta| or |callable|_, optional
A directive filtering old files that should be removed during rotation or end of
program.
compression : |str| or |callable|_, optional
A compression or archive format to which log files should be converted at closure.
delay : |bool|, optional
Whether the file should be created as soon as the sink is configured, or delayed until
first logged message. It defaults to ``False``.
watch : |bool|, optional
Whether or not the file should be watched and re-opened when deleted or changed (based
on its device and inode properties) by an external program. It defaults to ``False``.
mode : |str|, optional
The opening mode as for built-in |open| function. It defaults to ``"a"`` (open the
file in appending mode).
buffering : |int|, optional
The buffering policy as for built-in |open| function. It defaults to ``1`` (line
buffered file).
encoding : |str|, optional
The file encoding as for built-in |open| function. It defaults to ``"utf8"``.
**kwargs
Others parameters are passed to the built-in |open| function.
Returns
-------
:class:`int`
An identifier associated with the added sink and which should be used to
|remove| it.
Raises
------
ValueError
If any of the arguments passed to configure the sink is invalid.
Notes
-----
Extended summary follows.
.. _sink:
.. rubric:: The sink parameter
The ``sink`` handles incoming log messages and proceed to their writing somewhere and
somehow. A sink can take many forms:
- A |file-like object|_ like ``sys.stderr`` or ``open("file.log", "w")``. Anything with
a ``.write()`` method is considered as a file-like object. Custom handlers may also
implement ``flush()`` (called after each logged message), ``stop()`` (called at sink
termination) and ``complete()`` (awaited by the eponymous method).
- A file path as |str| or |Path|. It can be parametrized with some additional parameters,
see below.
- A |callable|_ (such as a simple function) like ``lambda msg: print(msg)``. This
allows for logging procedure entirely defined by user preferences and needs.
- A asynchronous |coroutine function|_ defined with the ``async def`` statement. The
coroutine object returned by such function will be added to the event loop using
|loop.create_task|. The tasks should be awaited before ending the loop by using
|complete|.
- A built-in |Handler| like ``logging.StreamHandler``. In such a case, the `Loguru` records
are automatically converted to the structure expected by the |logging| module.
Note that the logging functions are not `reentrant`_. This means you should avoid using
the ``logger`` inside any of your sinks or from within |signal| handlers. Otherwise, you
may face deadlock if the module's sink was not explicitly disabled.
.. _message:
.. rubric:: The logged message
The logged message passed to all added sinks is nothing more than a string of the
formatted log, to which a special attribute is associated: the ``.record`` which is a dict
containing all contextual information possibly needed (see below).
Logged messages are formatted according to the ``format`` of the added sink. This format
is usually a string containing braces fields to display attributes from the record dict.
If fine-grained control is needed, the ``format`` can also be a function which takes the
record as parameter and must return the unformatted template string. It is critical that
this string has not been pre-formatted, as Loguru will handle the actual formatting later.
Returning an already formatted log message would break internal mechanisms and lead to
runtime errors. Note that when using a function, you are also responsible for appending the
line ending and the exception field, whereas ``"\n{exception}"`` is automatically appended
for convenience when the ``format`` is a string.
The ``filter`` attribute can be used to control which messages are effectively passed to the
sink and which one are ignored. A function can be used, accepting the record as an
argument, and returning ``True`` if the message should be logged, ``False`` otherwise. If
a string is used, only the records with the same ``name`` and its children will be allowed.
One can also pass a ``dict`` mapping module names to minimum required level. In such case,
each log record will search for it's closest parent in the ``dict`` and use the associated
level as the filter. The ``dict`` values can be ``int`` severity, ``str`` level name or
``True`` and ``False`` to respectively authorize and discard all module logs
unconditionally. In order to set a default level, the ``""`` module name should be used as
it is the parent of all modules (it does not suppress global ``level`` threshold, though).
Note that while calling a logging method, the keyword arguments (if any) are automatically
added to the ``extra`` dict for convenient contextualization (in addition to being used for
formatting).
.. _levels:
.. rubric:: The severity levels
Each logged message is associated with a severity level. These levels make it possible to
prioritize messages and to choose the verbosity of the logs according to usages. For
example, it allows to display some debugging information to a developer, while hiding it to
the end user running the application.
The ``level`` attribute of every added sink controls the minimum threshold from which log
messages are allowed to be emitted. While using the ``logger``, you are in charge of
configuring the appropriate granularity of your logs. It is possible to add even more custom
levels by using the |level| method.
Here are the standard levels with their default severity value, each one is associated with
a logging method of the same name:
+----------------------+------------------------+------------------------+
| Level name | Severity value | Logger method |
+======================+========================+========================+
| ``TRACE`` | 5 | |logger.trace| |
+----------------------+------------------------+------------------------+
| ``DEBUG`` | 10 | |logger.debug| |
+----------------------+------------------------+------------------------+
| ``INFO`` | 20 | |logger.info| |
+----------------------+------------------------+------------------------+
| ``SUCCESS`` | 25 | |logger.success| |
+----------------------+------------------------+------------------------+
| ``WARNING`` | 30 | |logger.warning| |
+----------------------+------------------------+------------------------+
| ``ERROR`` | 40 | |logger.error| |
+----------------------+------------------------+------------------------+
| ``CRITICAL`` | 50 | |logger.critical| |
+----------------------+------------------------+------------------------+
.. _record:
.. rubric:: The record dict
The record is just a Python dict, accessible from sinks by ``message.record``. It contains
all contextual information of the logging call (time, function, file, line, level, etc.).
Each of the record keys can be used in the handler's ``format`` so the corresponding value
is properly displayed in the logged message (e.g. ``"{level}"`` will return ``"INFO"``).
Some records' values are objects with two or more attributes. These can be formatted with
``"{key.attr}"`` (``"{key}"`` would display one by default).
Note that you can use any `formatting directives`_ available in Python's ``str.format()``
method (e.g. ``"{key: >3}"`` will right-align and pad to a width of 3 characters). This is
particularly useful for time formatting (see below).
+------------+---------------------------------+----------------------------+
| Key | Description | Attributes |
+============+=================================+============================+
| elapsed | The time elapsed since the | See |timedelta| |
| | start of the program | |
+------------+---------------------------------+----------------------------+
| exception | The formatted exception if any, | ``type``, ``value``, |
| | ``None`` otherwise | ``traceback`` |
+------------+---------------------------------+----------------------------+
| extra | The dict of attributes | None |
| | bound by the user (see |bind|) | |
+------------+---------------------------------+----------------------------+
| file | The file where the logging call | ``name`` (default), |
| | was made | ``path`` |
+------------+---------------------------------+----------------------------+
| function | The function from which the | None |
| | logging call was made | |
+------------+---------------------------------+----------------------------+
| level | The severity used to log the | ``name`` (default), |
| | message | ``no``, ``icon`` |
+------------+---------------------------------+----------------------------+
| line | The line number in the source | None |
| | code | |
+------------+---------------------------------+----------------------------+
| message | The logged message (not yet | None |
| | formatted) | |
+------------+---------------------------------+----------------------------+
| module | The module where the logging | None |
| | call was made | |
+------------+---------------------------------+----------------------------+
| name | The ``__name__`` where the | None |
| | logging call was made | |
+------------+---------------------------------+----------------------------+
| process | The process in which the | ``name``, ``id`` (default) |
| | logging call was made | |
+------------+---------------------------------+----------------------------+
| thread | The thread in which the | ``name``, ``id`` (default) |
| | logging call was made | |
+------------+---------------------------------+----------------------------+
| time | The aware local time when the | See |datetime| |
| | logging call was made | |
+------------+---------------------------------+----------------------------+
.. _time:
.. rubric:: The time formatting
To use your favorite time representation, you can set it directly in the time formatter
specifier of your handler format, like for example ``format="{time:HH:mm:ss} {message}"``.
Note that this datetime represents your local time, and it is also made timezone-aware,
so you can display the UTC offset to avoid ambiguities.
The time field can be formatted using more human-friendly tokens. These constitute a subset
of the one used by the `Pendulum`_ library of `@sdispater`_. To escape a token, just add
square brackets around it, for example ``"[YY]"`` would display literally ``"YY"``.
If you prefer to display UTC rather than local time, you can add ``"!UTC"`` at the very end
of the time format, like ``{time:HH:mm:ss!UTC}``. Doing so will convert the ``datetime``
to UTC before formatting.
If no time formatter specifier is used, like for example if ``format="{time} {message}"``,
the default one will use ISO 8601.
+------------------------+---------+----------------------------------------+
| | Token | Output |
+========================+=========+========================================+
| Year | YYYY | 2000, 2001, 2002 ... 2012, 2013 |
| +---------+----------------------------------------+
| | YY | 00, 01, 02 ... 12, 13 |
+------------------------+---------+----------------------------------------+
| Quarter | Q | 1 2 3 4 |
+------------------------+---------+----------------------------------------+
| Month | MMMM | January, February, March ... |
| +---------+----------------------------------------+
| | MMM | Jan, Feb, Mar ... |
| +---------+----------------------------------------+
| | MM | 01, 02, 03 ... 11, 12 |
| +---------+----------------------------------------+
| | M | 1, 2, 3 ... 11, 12 |
+------------------------+---------+----------------------------------------+
| Day of Year | DDDD | 001, 002, 003 ... 364, 365 |
| +---------+----------------------------------------+
| | DDD | 1, 2, 3 ... 364, 365 |
+------------------------+---------+----------------------------------------+
| Day of Month | DD | 01, 02, 03 ... 30, 31 |
| +---------+----------------------------------------+
| | D | 1, 2, 3 ... 30, 31 |
+------------------------+---------+----------------------------------------+
| Day of Week | dddd | Monday, Tuesday, Wednesday ... |
| +---------+----------------------------------------+
| | ddd | Mon, Tue, Wed ... |
| +---------+----------------------------------------+
| | d | 0, 1, 2 ... 6 |
+------------------------+---------+----------------------------------------+
| Days of ISO Week | E | 1, 2, 3 ... 7 |
+------------------------+---------+----------------------------------------+
| Hour | HH | 00, 01, 02 ... 23, 24 |
| +---------+----------------------------------------+
| | H | 0, 1, 2 ... 23, 24 |
| +---------+----------------------------------------+
| | hh | 01, 02, 03 ... 11, 12 |
| +---------+----------------------------------------+
| | h | 1, 2, 3 ... 11, 12 |
+------------------------+---------+----------------------------------------+
| Minute | mm | 00, 01, 02 ... 58, 59 |
| +---------+----------------------------------------+
| | m | 0, 1, 2 ... 58, 59 |
+------------------------+---------+----------------------------------------+
| Second | ss | 00, 01, 02 ... 58, 59 |
| +---------+----------------------------------------+
| | s | 0, 1, 2 ... 58, 59 |
+------------------------+---------+----------------------------------------+
| Fractional Second | S | 0 1 ... 8 9 |
| +---------+----------------------------------------+
| | SS | 00, 01, 02 ... 98, 99 |
| +---------+----------------------------------------+
| | SSS | 000 001 ... 998 999 |
| +---------+----------------------------------------+
| | SSSS... | 000[0..] 001[0..] ... 998[0..] 999[0..]|
| +---------+----------------------------------------+
| | SSSSSS | 000000 000001 ... 999998 999999 |
+------------------------+---------+----------------------------------------+
| AM / PM | A | AM, PM |
+------------------------+---------+----------------------------------------+
| Timezone | Z | -07:00, -06:00 ... +06:00, +07:00 |
| +---------+----------------------------------------+
| | ZZ | -0700, -0600 ... +0600, +0700 |
| +---------+----------------------------------------+
| | zz | EST CST ... MST PST |
+------------------------+---------+----------------------------------------+
| Seconds timestamp | X | 1381685817, 1234567890.123 |
+------------------------+---------+----------------------------------------+
| Microseconds timestamp | x | 1234567890123 |
+------------------------+---------+----------------------------------------+
.. _file:
.. rubric:: The file sinks
If the sink is a |str| or a |Path|, the corresponding file will be opened for writing logs.
The path can also contain a special ``"{time}"`` field that will be formatted with the
current date at file creation. The file is closed at sink stop, i.e. when the application
ends or the handler is removed.
The ``rotation`` check is made before logging each message. If there is already an existing
file with the same name that the file to be created, then the existing file is renamed by
appending the date to its basename to prevent file overwriting. This parameter accepts:
- an |int| which corresponds to the maximum file size in bytes before that the current
logged file is closed and a new one started over.
- a |timedelta| which indicates the frequency of each new rotation.
- a |time| which specifies the hour when the daily rotation should occur.
- a |str| for human-friendly parametrization of one of the previously enumerated types.
Examples: ``"100 MB"``, ``"0.5 GB"``, ``"1 month 2 weeks"``, ``"4 days"``, ``"10h"``,
``"monthly"``, ``"18:00"``, ``"sunday"``, ``"w0"``, ``"monday at 12:00"``, ...
- a |callable|_ which will be invoked before logging. It should accept two arguments: the
logged message and the file object, and it should return ``True`` if the rotation should
happen now, ``False`` otherwise.
The ``retention`` occurs at rotation or at sink stop if rotation is ``None``. Files
resulting from previous sessions or rotations are automatically collected from disk. A file
is selected if it matches the pattern ``"root(.*).ext(.*)"``, where ``root`` and ``ext`` are
derived from ``os.path.splitext()`` applied to the configured sink path (possible time
fields are beforehand replaced with ``.*``). Afterwards, the list is processed to determine
files to be retained. This parameter accepts:
- an |int| which indicates the number of log files to keep, while older files are deleted.
- a |timedelta| which specifies the maximum age of files to keep.
- a |str| for human-friendly parametrization of the maximum age of files to keep.
Examples: ``"1 week, 3 days"``, ``"2 months"``, ...
- a |callable|_ which will be invoked before the retention process. It should accept the
list of log files as argument and process to whatever it wants (moving files, removing
them, etc.).
The ``compression`` happens at rotation or at sink stop if rotation is ``None``. This
parameter accepts:
- a |str| which corresponds to the compressed or archived file extension. This can be one
of: ``"gz"``, ``"bz2"``, ``"xz"``, ``"lzma"``, ``"tar"``, ``"tar.gz"``, ``"tar.bz2"``,
``"tar.xz"``, ``"zip"``.
- a |callable|_ which will be invoked after closing (and possibly renaming) the currently
logged file. It should accept the path of the log file as argument and process to whatever
it wants (custom compression, network sending, renaming it, removing it, etc.).
Either way, if you use a custom function designed according to your preferences, you must be
very careful not to use the ``logger`` within your function. Otherwise, there is a risk that
your program hang because of a deadlock.
.. _color:
.. rubric:: The color markups
When the sink supports it, the logs can be colored by using markups in the format string.
By default (when ``colorize`` is not specified), these are automatically converted or
removed depending on the sink's support for `ANSI codes`_. Loguru also honors the
|NO_COLOR|_ and |FORCE_COLOR|_ environment variables (the former taking precedence over the
latter).
To add colors, you just have to enclose your format string with the appropriate tags
(e.g. ``<red>some message</red>``). For convenience, you can use ``</>`` to close the last
opening tag without repeating its name (e.g. ``<red>another message</>``). The special tag
``<level>`` (abbreviated with ``<lvl>``) is transformed according to the configured color
of the logged message level.
Tags which are not recognized will raise an exception during parsing, to inform you about
possible misuse. If you wish to display a markup tag literally, you can escape it by
prepending a ``\`` like for example ``\<blue>``. To prevent the escaping to occur, you can
simply double the ``\`` (e.g. ``\\<blue>`` will print a literal ``\`` before colored text).
If, for some reason, you need to escape a string programmatically, note that the regex used
internally to parse markup tags is ``r"(\\*)(</?(?:[fb]g\s)?[^<>\s]*>)"``.
Note that when logging a message with ``opt(colors=True)``, color tags present in the
formatting arguments (``args`` and ``kwargs``) are completely ignored. This is important if
you need to log strings containing markups that might interfere with the color tags (in this
case, do not use f-string).
Here are the available tags (note that compatibility may vary depending on terminal):
+------------------------------------+--------------------------------------+
| Color (abbr) | Styles (abbr) |
+====================================+======================================+
| Black (k) | Bold (b) |
+------------------------------------+--------------------------------------+
| Blue (e) | Dim (d) |
+------------------------------------+--------------------------------------+
| Cyan (c) | Normal (n) |
+------------------------------------+--------------------------------------+
| Green (g) | Italic (i) |
+------------------------------------+--------------------------------------+
| Magenta (m) | Underline (u) |
+------------------------------------+--------------------------------------+
| Red (r) | Strike (s) |
+------------------------------------+--------------------------------------+
| White (w) | Reverse (v) |
+------------------------------------+--------------------------------------+
| Yellow (y) | Blink (l) |
+------------------------------------+--------------------------------------+
| | Hide (h) |
+------------------------------------+--------------------------------------+
Usage:
+-----------------+-------------------------------------------------------------------+
| Description | Examples |
| +---------------------------------+---------------------------------+
| | Foreground | Background |
+=================+=================================+=================================+
| Basic colors | ``<red>``, ``<r>`` | ``<GREEN>``, ``<G>`` |
+-----------------+---------------------------------+---------------------------------+
| Light colors | ``<light-blue>``, ``<le>`` | ``<LIGHT-CYAN>``, ``<LC>`` |
+-----------------+---------------------------------+---------------------------------+
| 8-bit colors | ``<fg 86>``, ``<fg 255>`` | ``<bg 42>``, ``<bg 9>`` |
+-----------------+---------------------------------+---------------------------------+
| Hex colors | ``<fg #00005f>``, ``<fg #EE1>`` | ``<bg #AF5FD7>``, ``<bg #fff>`` |
+-----------------+---------------------------------+---------------------------------+
| RGB colors | ``<fg 0,95,0>`` | ``<bg 72,119,65>`` |
+-----------------+---------------------------------+---------------------------------+
| Stylizing | ``<bold>``, ``<b>``, ``<underline>``, ``<u>`` |
+-----------------+-------------------------------------------------------------------+
.. _env:
.. rubric:: The environment variables
The default values of sink parameters can be entirely customized. This is particularly
useful if you don't like the log format of the pre-configured sink.
Each of the |add| default parameter can be modified by setting the ``LOGURU_[PARAM]``
environment variable. For example on Linux: ``export LOGURU_LEVEL="WARNING"``
or ``export LOGURU_FORMAT="{time} - {message}"``.
The default levels' attributes can also be modified by setting the ``LOGURU_[LEVEL]_[ATTR]``
environment variable. For example, on Windows: ``setx LOGURU_DEBUG_COLOR "<blue>"``
or ``setx LOGURU_TRACE_ICON "🚀"``. If you use the ``set`` command, do not include quotes
but escape special symbol as needed, e.g. ``set LOGURU_DEBUG_COLOR=^<blue^>``.
If you want to disable the pre-configured sink, you can set the ``LOGURU_AUTOINIT``
variable to ``False``.
On Linux, you will probably need to edit the ``~/.profile`` file to make this persistent. On
Windows, don't forget to restart your terminal for the change to be taken into account.
Examples
--------
>>> logger.add(sys.stdout, format="{time} - {level} - {message}", filter="sub.module")
>>> logger.add("file_{time}.log", level="TRACE", rotation="100 MB")
>>> def debug_only(record):
... return record["level"].name == "DEBUG"
...
>>> logger.add("debug.log", filter=debug_only) # Other levels are filtered out
>>> def my_sink(message):
... record = message.record
... update_db(message, time=record["time"], level=record["level"])
...
>>> logger.add(my_sink)
>>> def dynamic_format(record):
... # Caution: the template must be returned as-is (with placeholders left unformatted).
... if record["level"].no >= 40:
... return "<red>{time} {level} {message}</red>\n{exception}"
... return "{time} {level} {message}\n{exception}"
...
>>> logger.add(sys.stderr, format=dynamic_format)
>>> level_per_module = {
... "": "DEBUG",
... "third.lib": "WARNING",
... "anotherlib": False
... }
>>> logger.add(lambda m: print(m, end=""), filter=level_per_module, level=0)
>>> async def publish(message):
... await api.post(message)
...
>>> logger.add(publish, serialize=True)
>>> from logging import StreamHandler
>>> logger.add(StreamHandler(sys.stderr), format="{message}")
>>> class RandomStream:
... def __init__(self, seed, threshold):
... self.threshold = threshold
... random.seed(seed)
... def write(self, message):
... if random.random() > self.threshold:
... print(message)
...
>>> stream_object = RandomStream(seed=12345, threshold=0.25)
>>> logger.add(stream_object, level="INFO")
"""
with self._core.lock:
handler_id = self._core.handlers_count
self._core.handlers_count += 1
error_interceptor = ErrorInterceptor(catch, handler_id)
if colorize is None and serialize:
colorize = False
if isinstance(sink, (str, PathLike)):
path = sink
name = "'%s'" % path
if colorize is None:
colorize = False
wrapped_sink = FileSink(path, **kwargs)
kwargs = {}
encoding = wrapped_sink.encoding
terminator = "\n"
exception_prefix = ""
elif hasattr(sink, "write") and callable(sink.write):
name = getattr(sink, "name", None) or repr(sink)
if colorize is None:
colorize = _colorama.should_colorize(sink)
if colorize is True and _colorama.should_wrap(sink):
stream = _colorama.wrap(sink)
else:
stream = sink
wrapped_sink = StreamSink(stream)
encoding = getattr(sink, "encoding", None)
terminator = "\n"
exception_prefix = ""
elif isinstance(sink, logging.Handler):
name = repr(sink)
if colorize is None:
colorize = False
wrapped_sink = StandardSink(sink)
encoding = getattr(sink, "encoding", None)
terminator = ""
exception_prefix = "\n"
elif iscoroutinefunction(sink) or iscoroutinefunction(
getattr(sink, "__call__", None) # noqa: B004
):
name = getattr(sink, "__name__", None) or repr(sink)
if colorize is None:
colorize = False
loop = kwargs.pop("loop", None)
# The worker thread needs an event loop, it can't create a new one internally because it
# has to be accessible by the user while calling "complete()", instead we use the global
# one when the sink is added. If "enqueue=False" the event loop is dynamically retrieved
# at each logging call, which is much more convenient. However, coroutine can't access
# running loop in Python 3.5.2 and earlier versions, see python/asyncio#452.
if enqueue and loop is None:
try:
loop = _asyncio_loop.get_running_loop()
except RuntimeError as e:
raise ValueError(
"An event loop is required to add a coroutine sink with `enqueue=True`, "
"but none has been passed as argument and none is currently running."
) from e
coro = sink if iscoroutinefunction(sink) else sink.__call__
wrapped_sink = AsyncSink(coro, loop, error_interceptor)
encoding = "utf8"
terminator = "\n"
exception_prefix = ""
elif callable(sink):
name = getattr(sink, "__name__", None) or repr(sink)
if colorize is None:
colorize = False
wrapped_sink = CallableSink(sink)
encoding = "utf8"
terminator = "\n"
exception_prefix = ""
else:
raise TypeError("Cannot log to objects of type '%s'" % type(sink).__name__)
if kwargs:
raise TypeError("add() got an unexpected keyword argument '%s'" % next(iter(kwargs)))
if filter is None:
filter_func = None
elif filter == "":
filter_func = _filters.filter_none
elif isinstance(filter, str):
parent = filter + "."
length = len(parent)
filter_func = functools.partial(_filters.filter_by_name, parent=parent, length=length)
elif isinstance(filter, dict):
level_per_module = {}
for module, level_ in filter.items():
if module is not None and not isinstance(module, str):
raise TypeError(
"The filter dict contains an invalid module, "
"it should be a string (or None), not: '%s'" % type(module).__name__
)
if level_ is False:
levelno_ = False
elif level_ is True:
levelno_ = 0
elif isinstance(level_, str):
try:
levelno_ = self.level(level_).no
except ValueError:
raise ValueError(
"The filter dict contains a module '%s' associated to a level name "
"which does not exist: '%s'" % (module, level_)
) from None
elif isinstance(level_, int):
levelno_ = level_
else:
raise TypeError(
"The filter dict contains a module '%s' associated to an invalid level, "
"it should be an integer, a string or a boolean, not: '%s'"
% (module, type(level_).__name__)
)
if levelno_ < 0:
raise ValueError(
"The filter dict contains a module '%s' associated to an invalid level, "
"it should be a positive integer, not: '%d'" % (module, levelno_)
)
level_per_module[module] = levelno_
filter_func = functools.partial(
_filters.filter_by_level, level_per_module=level_per_module
)
elif callable(filter):
if filter == builtins.filter:
raise ValueError(
"The built-in 'filter()' function cannot be used as a 'filter' parameter, "
"this is most likely a mistake (please double-check the arguments passed "
"to 'logger.add()')."
)
filter_func = filter
else:
raise TypeError(
"Invalid filter, it should be a function, a string or a dict, not: '%s'"
% type(filter).__name__
)
if isinstance(level, str):
levelno = self.level(level).no
elif isinstance(level, int):
levelno = level
else:
raise TypeError(
"Invalid level, it should be an integer or a string, not: '%s'"
% type(level).__name__
)
if levelno < 0:
raise ValueError(
"Invalid level value, it should be a positive integer, not: %d" % levelno
)
if isinstance(format, str):
try:
formatter = Colorizer.prepare_format(format + terminator + "{exception}")
except ValueError as e:
raise ValueError(
"Invalid format, color markups could not be parsed correctly"
) from e
is_formatter_dynamic = False
elif callable(format):
if format == builtins.format:
raise ValueError(
"The built-in 'format()' function cannot be used as a 'format' parameter, "
"this is most likely a mistake (please double-check the arguments passed "
"to 'logger.add()')."
)
formatter = format
is_formatter_dynamic = True
else:
raise TypeError(
"Invalid format, it should be a string or a function, not: '%s'"
% type(format).__name__
)
if not isinstance(encoding, str):
encoding = "ascii"
if isinstance(context, str):
context = get_context(context)
elif context is not None and not isinstance(context, BaseContext):
raise TypeError(
"Invalid context, it should be a string or a multiprocessing context, "
"not: '%s'" % type(context).__name__
)
with self._core.lock:
exception_formatter = ExceptionFormatter(
colorize=colorize,
encoding=encoding,
diagnose=diagnose,
backtrace=backtrace,
hidden_frames_filename=self.catch.__code__.co_filename,
prefix=exception_prefix,
)
handler = Handler(
name=name,
sink=wrapped_sink,
levelno=levelno,
formatter=formatter,
is_formatter_dynamic=is_formatter_dynamic,
filter_=filter_func,
colorize=colorize,
serialize=serialize,
enqueue=enqueue,
multiprocessing_context=context,
id_=handler_id,
error_interceptor=error_interceptor,
exception_formatter=exception_formatter,
levels_ansi_codes=self._core.levels_ansi_codes,
)
handlers = self._core.handlers.copy()
handlers[handler_id] = handler
self._core.min_level = min(self._core.min_level, levelno)
self._core.handlers = handlers
return handler_id
def remove(self, handler_id=None):
"""Remove a previously added handler and stop sending logs to its sink.
Parameters
----------
handler_id : |int| or ``None``
The id of the sink to remove, as it was returned by the |add| method. If ``None``, all
handlers are removed. The pre-configured handler is guaranteed to have the index ``0``.
Raises
------
ValueError
If ``handler_id`` is not ``None`` but there is no active handler with such id.
Examples
--------
>>> i = logger.add(sys.stderr, format="{message}")
>>> logger.info("Logging")
Logging
>>> logger.remove(i)
>>> logger.info("No longer logging")
"""
if not (handler_id is None or isinstance(handler_id, int)):
raise TypeError(
"Invalid handler id, it should be an integer as returned "
"by the 'add()' method (or None), not: '%s'" % type(handler_id).__name__
)
with self._core.lock:
if handler_id is not None and handler_id not in self._core.handlers:
raise ValueError("There is no existing handler with id %d" % handler_id) from None
if handler_id is None:
handler_ids = list(self._core.handlers)
else:
handler_ids = [handler_id]
for handler_id in handler_ids:
handlers = self._core.handlers.copy()
handler = handlers.pop(handler_id)
# This needs to be done first in case "stop()" raises an exception
levelnos = (h.levelno for h in handlers.values())
self._core.min_level = min(levelnos, default=float("inf"))
self._core.handlers = handlers
handler.stop()
def complete(self):
"""Wait for the end of enqueued messages and asynchronous tasks scheduled by handlers.
This method proceeds in two steps: first it waits for all logging messages added to handlers
with ``enqueue=True`` to be processed, then it returns an object that can be awaited to
finalize all logging tasks added to the event loop by coroutine sinks.
It can be called from non-asynchronous code. This is especially recommended when the
``logger`` is utilized with ``multiprocessing`` to ensure messages put to the internal
queue have been properly transmitted before leaving a child process.
The returned object should be awaited before the end of a coroutine executed by
|asyncio.run| or |loop.run_until_complete| to ensure all asynchronous logging messages are
processed. The function |asyncio.get_running_loop| is called beforehand, only tasks
scheduled in the same loop that the current one will be awaited by the method.
Returns
-------
:term:`awaitable`
An awaitable object which ensures all asynchronous logging calls are completed when
awaited.
Examples
--------
>>> async def sink(message):
... await asyncio.sleep(0.1) # IO processing...
... print(message, end="")
...
>>> async def work():
... logger.info("Start")
... logger.info("End")
... await logger.complete()
...
>>> logger.add(sink)
1
>>> asyncio.run(work())
Start
End
>>> def process():
... logger.info("Message sent from the child")
... logger.complete()
...
>>> logger.add(sys.stderr, enqueue=True)
1
>>> process = multiprocessing.Process(target=process)
>>> process.start()
>>> process.join()
Message sent from the child
"""
tasks = []
with self._core.lock:
handlers = self._core.handlers.copy()
for handler in handlers.values():
handler.complete_queue()
tasks.extend(handler.tasks_to_complete())
class AwaitableCompleter:
def __await__(self):
for task in tasks:
yield from task.__await__()
return AwaitableCompleter()
def catch(
self,
exception=Exception,
*,
level="ERROR",
reraise=False,
onerror=None,
exclude=None,
default=None,
message="An error has been caught in function '{record[function]}', "
"process '{record[process].name}' ({record[process].id}), "
"thread '{record[thread].name}' ({record[thread].id}):"
):
"""Return a decorator to automatically log possibly caught error in wrapped function.
This is useful to ensure unexpected exceptions are logged, the entire program can be
wrapped by this method. This is also very useful to decorate |Thread.run| methods while
using threads to propagate errors to the main logger thread.
Note that the visibility of variables values (which uses the great |better_exceptions|_
library from `@Qix-`_) depends on the ``diagnose`` option of each configured sink.
The returned object can also be used as a context manager.
Parameters
----------
exception : |Exception|, optional
The type of exception to intercept. If several types should be caught, a tuple of
exceptions can be used too.
level : |str| or |int|, optional
The level name or severity with which the message should be logged.
reraise : |bool|, optional
Whether the exception should be raised again and hence propagated to the caller.
onerror : |callable|_, optional
A function that will be called if an error occurs, once the message has been logged.
It should accept the exception instance as it sole argument.
exclude : |Exception|, optional
A type of exception (or a tuple of types) that will be purposely ignored and hence
propagated to the caller without being logged.
default : |Any|, optional
The value to be returned by the decorated function if an error occurred without being
re-raised.
message : |str|, optional
The message that will be automatically logged if an exception occurs. Note that it will
be formatted with the ``record`` attribute.
Returns
-------
:term:`decorator` / :term:`context manager`
An object that can be used to decorate a function or as a context manager to log
exceptions possibly caught.
Examples
--------
>>> @logger.catch
... def f(x):
... 100 / x
...
>>> def g():
... f(10)
... f(0)
...
>>> g()
ERROR - An error has been caught in function 'g', process 'Main' (367), thread 'ch1' (1398):
Traceback (most recent call last):
File "program.py", line 12, in <module>
g()
└ <function g at 0x7f225fe2bc80>
> File "program.py", line 10, in g
f(0)
└ <function f at 0x7f225fe2b9d8>
File "program.py", line 6, in f
100 / x
└ 0
ZeroDivisionError: division by zero
>>> with logger.catch(message="Because we never know..."):
... main() # No exception, no logs
>>> # Use 'onerror' to prevent the program exit code to be 0 (if 'reraise=False') while
>>> # also avoiding the stacktrace to be duplicated on stderr (if 'reraise=True').
>>> @logger.catch(onerror=lambda _: sys.exit(1))
... def main():
... 1 / 0
"""
if callable(exception) and (
not isclass(exception) or not issubclass(exception, BaseException)
):
return self.catch()(exception)
logger = self
class Catcher:
def __init__(self, from_decorator):
self._from_decorator = from_decorator
def __enter__(self):
return None
def __exit__(self, type_, value, traceback_):
if type_ is None:
return None
# We must prevent infinite recursion in case "logger.catch()" handles an exception
# that occurs while logging another exception. This can happen for example when
# the exception formatter calls "repr(obj)" while the "__repr__" method is broken
# but decorated with "logger.catch()". In such a case, we ignore the catching
# mechanism and just let the exception be thrown (that way, the formatter will
# rightly assume the object is unprintable).
if getattr(logger._core.thread_locals, "already_logging_exception", False):
return False
if not issubclass(type_, exception):
return False
if exclude is not None and issubclass(type_, exclude):
return False
from_decorator = self._from_decorator
_, depth, _, *options = logger._options
if from_decorator:
depth += 1
catch_options = [(type_, value, traceback_), depth, True, *options]
logger._core.thread_locals.already_logging_exception = True
try:
logger._log(level, from_decorator, catch_options, message, (), {})
finally:
logger._core.thread_locals.already_logging_exception = False
if onerror is not None:
onerror(value)
return not reraise
def __call__(self, function):
if isclass(function):
raise TypeError(
"Invalid object decorated with 'catch()', it must be a function, "
"not a class (tried to wrap '%s')" % function.__name__
)
catcher = Catcher(True)
if iscoroutinefunction(function):
async def catch_wrapper(*args, **kwargs):
with catcher:
return await function(*args, **kwargs)
return default
elif isgeneratorfunction(function):
def catch_wrapper(*args, **kwargs):
with catcher:
return (yield from function(*args, **kwargs))
return default
elif isasyncgenfunction(function):
class AsyncGenCatchWrapper(AsyncGenerator):
def __init__(self, gen):
self._gen = gen
async def asend(self, value):
with catcher:
try:
return await self._gen.asend(value)
except StopAsyncIteration:
pass
except:
raise
raise StopAsyncIteration
async def athrow(self, *args, **kwargs):
return await self._gen.athrow(*args, **kwargs)
def catch_wrapper(*args, **kwargs):
gen = function(*args, **kwargs)
return AsyncGenCatchWrapper(gen)
else:
def catch_wrapper(*args, **kwargs):
with catcher:
return function(*args, **kwargs)
return default
functools.update_wrapper(catch_wrapper, function)
return catch_wrapper
async def __aenter__(self):
return self.__enter__()
async def __aexit__(self, type_, value, traceback_):
return self.__exit__(type_, value, traceback_)
return Catcher(False)
def opt(
self,
*,
exception=None,
record=False,
lazy=False,
colors=False,
raw=False,
capture=True,
depth=0,
ansi=False
):
r"""Parametrize a logging call to slightly change generated log message.
Note that it's not possible to chain |opt| calls, the last one takes precedence over the
others as it will "reset" the options to their default values.
Parameters
----------
exception : |bool|, |tuple| or |Exception|, optional
If it does not evaluate as ``False``, the passed exception is formatted and added to the
log message. It could be an |Exception| object or a ``(type, value, traceback)`` tuple,
otherwise the exception information is retrieved from |sys.exc_info|.
record : |bool|, optional
If ``True``, the record dict contextualizing the logging call can be used to format the
message by using ``{record[key]}`` in the log message.
lazy : |bool|, optional
If ``True``, the logging call attribute to format the message should be functions which
will be called only if the level is high enough. This can be used to avoid expensive
functions if not necessary.
colors : |bool|, optional
If ``True``, logged message will be colorized according to the markups it possibly
contains.
raw : |bool|, optional
If ``True``, the formatting of each sink will be bypassed and the message will be sent
as is.
capture : |bool|, optional
If ``False``, the ``**kwargs`` of logged message will not automatically populate
the ``extra`` dict (although they are still used for formatting).
depth : |int|, optional
Specify which stacktrace should be used to contextualize the logged message. This is
useful while using the logger from inside a wrapped function to retrieve worthwhile
information.
ansi : |bool|, optional
Deprecated since version 0.4.1: the ``ansi`` parameter will be removed in Loguru 1.0.0,
it is replaced by ``colors`` which is a more appropriate name.
Returns
-------
:class:`~Logger`
A logger wrapping the core logger, but transforming logged message adequately before
sending.
Examples
--------
>>> try:
... 1 / 0
... except ZeroDivisionError:
... logger.opt(exception=True).debug("Exception logged with debug level:")
...
[18:10:02] DEBUG in '<module>' - Exception logged with debug level:
Traceback (most recent call last, catch point marked):
> File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
>>> logger.opt(record=True).info("Current line is: {record[line]}")
[18:10:33] INFO in '<module>' - Current line is: 1
>>> logger.opt(lazy=True).debug("If sink <= DEBUG: {x}", x=lambda: math.factorial(2**5))
[18:11:19] DEBUG in '<module>' - If sink <= DEBUG: 263130836933693530167218012160000000
>>> logger.opt(colors=True).warning("We got a <red>BIG</red> problem")
[18:11:30] WARNING in '<module>' - We got a BIG problem
>>> logger.opt(raw=True).debug("No formatting\n")
No formatting
>>> logger.opt(capture=False).info("Displayed but not captured: {value}", value=123)
[18:11:41] Displayed but not captured: 123
>>> def wrapped():
... logger.opt(depth=1).info("Get parent context")
...
>>> def func():
... wrapped()
...
>>> func()
[18:11:54] DEBUG in 'func' - Get parent context
"""
if ansi:
colors = True
warnings.warn(
"The 'ansi' parameter is deprecated, please use 'colors' instead",
DeprecationWarning,
stacklevel=2,
)
args = self._options[-2:]
return Logger(self._core, exception, depth, record, lazy, colors, raw, capture, *args)
def bind(__self, **kwargs): # noqa: N805
"""Bind attributes to the ``extra`` dict of each logged message record.
This is used to add custom context to each logging call.
Parameters
----------
**kwargs
Mapping between keys and values that will be added to the ``extra`` dict.
Returns
-------
:class:`~Logger`
A logger wrapping the core logger, but which sends record with the customized ``extra``
dict.
Examples
--------
>>> logger.add(sys.stderr, format="{extra[ip]} - {message}")
>>> class Server:
... def __init__(self, ip):
... self.ip = ip
... self.logger = logger.bind(ip=ip)
... def call(self, message):
... self.logger.info(message)
...
>>> instance_1 = Server("192.168.0.200")
>>> instance_2 = Server("127.0.0.1")
>>> instance_1.call("First instance")
192.168.0.200 - First instance
>>> instance_2.call("Second instance")
127.0.0.1 - Second instance
"""
*options, extra = __self._options
return Logger(__self._core, *options, {**extra, **kwargs})
@contextlib.contextmanager
def contextualize(__self, **kwargs): # noqa: N805
"""Bind attributes to the context-local ``extra`` dict while inside the ``with`` block.
Contrary to |bind| there is no ``logger`` returned, the ``extra`` dict is modified in-place
and updated globally. Most importantly, it uses |contextvars| which means that
contextualized values are unique to each threads and asynchronous tasks.
The ``extra`` dict will retrieve its initial state once the context manager is exited.
Parameters
----------
**kwargs
Mapping between keys and values that will be added to the context-local ``extra`` dict.
Returns
-------
:term:`context manager` / :term:`decorator`
A context manager (usable as a decorator too) that will bind the attributes once entered
and restore the initial state of the ``extra`` dict while exited.
Examples
--------
>>> logger.add(sys.stderr, format="{message} | {extra}")
1
>>> def task():
... logger.info("Processing!")
...
>>> with logger.contextualize(task_id=123):
... task()
...
Processing! | {'task_id': 123}
>>> logger.info("Done.")
Done. | {}
"""
with __self._core.lock:
new_context = {**context.get(), **kwargs}
token = context.set(new_context)
try:
yield
finally:
with __self._core.lock:
context.reset(token)
def patch(self, patcher):
"""Attach a function to modify the record dict created by each logging call.
The ``patcher`` may be used to update the record on-the-fly before it's propagated to the
handlers. This allows the "extra" dict to be populated with dynamic values and also permits
advanced modifications of the record emitted while logging a message. The function is called
once before sending the log message to the different handlers.
It is recommended to apply modification on the ``record["extra"]`` dict rather than on the
``record`` dict itself, as some values are used internally by `Loguru`, and modify them may
produce unexpected results.
The logger can be patched multiple times. In this case, the functions are called in the
same order as they are added.
Parameters
----------
patcher: |callable|_
The function to which the record dict will be passed as the sole argument. This function
is in charge of updating the record in-place, the function does not need to return any
value, the modified record object will be re-used.
Returns
-------
:class:`~Logger`
A logger wrapping the core logger, but which records are passed through the ``patcher``
function before being sent to the added handlers.
Examples
--------
>>> logger.add(sys.stderr, format="{extra[utc]} {message}")
>>> logger = logger.patch(lambda record: record["extra"].update(utc=datetime.utcnow())
>>> logger.info("That's way, you can log messages with time displayed in UTC")
>>> def wrapper(func):
... @functools.wraps(func)
... def wrapped(*args, **kwargs):
... logger.patch(lambda r: r.update(function=func.__name__)).info("Wrapped!")
... return func(*args, **kwargs)
... return wrapped
>>> def recv_record_from_network(pipe):
... record = pickle.loads(pipe.read())
... level, message = record["level"], record["message"]
... logger.patch(lambda r: r.update(record)).log(level, message)
"""
*options, patchers, extra = self._options
return Logger(self._core, *options, [*patchers, patcher], extra)
def level(self, name, no=None, color=None, icon=None):
r"""Add, update or retrieve a logging level.
Logging levels are defined by their ``name`` to which a severity ``no``, an ansi ``color``
tag and an ``icon`` are associated and possibly modified at run-time. To |log| to a custom
level, you should necessarily use its name, the severity number is not linked back to levels
name (this implies that several levels can share the same severity).
To add a new level, its ``name`` and its ``no`` are required. A ``color`` and an ``icon``
can also be specified or will be empty by default.
To update an existing level, pass its ``name`` with the parameters to be changed. It is not
possible to modify the ``no`` of a level once it has been added.
To retrieve level information, the ``name`` solely suffices.
Parameters
----------
name : |str|
The name of the logging level.
no : |int|
The severity of the level to be added or updated.
color : |str|
The color markup of the level to be added or updated.
icon : |str|
The icon of the level to be added or updated.
Returns
-------
``Level``
A |namedtuple| containing information about the level.
Raises
------
ValueError
If attempting to access a level with a ``name`` that is not registered, or if trying to
change the severity ``no`` of an existing level.
Examples
--------
>>> level = logger.level("ERROR")
>>> print(level)
Level(name='ERROR', no=40, color='<red><bold>', icon='❌')
>>> logger.add(sys.stderr, format="{level.no} {level.icon} {message}")
1
>>> logger.level("CUSTOM", no=15, color="<blue>", icon="@")
Level(name='CUSTOM', no=15, color='<blue>', icon='@')
>>> logger.log("CUSTOM", "Logging...")
15 @ Logging...
>>> logger.level("WARNING", icon=r"/!\\")
Level(name='WARNING', no=30, color='<yellow><bold>', icon='/!\\\\')
>>> logger.warning("Updated!")
30 /!\\ Updated!
"""
if not isinstance(name, str):
raise TypeError(
"Invalid level name, it should be a string, not: '%s'" % type(name).__name__
)
if no is color is icon is None:
try:
return self._core.levels[name]
except KeyError:
raise ValueError("Level '%s' does not exist" % name) from None
if name not in self._core.levels:
if no is None:
raise ValueError(
"Level '%s' does not exist, you have to create it by specifying a level no"
% name
)
old_color, old_icon = "", " "
elif no is not None:
raise ValueError("Level '%s' already exists, you can't update its severity no" % name)
else:
_, no, old_color, old_icon = self.level(name)
if color is None:
color = old_color
if icon is None:
icon = old_icon
if not isinstance(no, int):
raise TypeError(
"Invalid level no, it should be an integer, not: '%s'" % type(no).__name__
)
if no < 0:
raise ValueError("Invalid level no, it should be a positive integer, not: %d" % no)
ansi = Colorizer.ansify(color)
level = Level(name, no, color, icon)
with self._core.lock:
self._core.levels[name] = level
self._core.levels_ansi_codes[name] = ansi
self._core.levels_lookup[name] = (name, name, no, icon)
for handler in self._core.handlers.values():
handler.update_format(name)
return level
def disable(self, name):
"""Disable logging of messages coming from ``name`` module and its children.
Developers of library using `Loguru` should absolutely disable it to avoid disrupting
users with unrelated logs messages.
Note that in some rare circumstances, it is not possible for `Loguru` to
determine the module's ``__name__`` value. In such situation, ``record["name"]`` will be
equal to ``None``, this is why ``None`` is also a valid argument.
Parameters
----------
name : |str| or ``None``
The name of the parent module to disable.
Examples
--------
>>> logger.info("Allowed message by default")
[22:21:55] Allowed message by default
>>> logger.disable("my_library")
>>> logger.info("While publishing a library, don't forget to disable logging")
"""
self._change_activation(name, False)
def enable(self, name):
"""Enable logging of messages coming from ``name`` module and its children.
Logging is generally disabled by imported library using `Loguru`, hence this function
allows users to receive these messages anyway.
To enable all logs regardless of the module they are coming from, an empty string ``""`` can
be passed.
Parameters
----------
name : |str| or ``None``
The name of the parent module to re-allow.
Examples
--------
>>> logger.disable("__main__")
>>> logger.info("Disabled, so nothing is logged.")
>>> logger.enable("__main__")
>>> logger.info("Re-enabled, messages are logged.")
[22:46:12] Re-enabled, messages are logged.
"""
self._change_activation(name, True)
def configure(self, *, handlers=None, levels=None, extra=None, patcher=None, activation=None):
"""Configure the core logger.
It should be noted that ``extra`` values set using this function are available across all
modules, so this is the best way to set overall default values.
To load the configuration directly from a file, such as JSON or YAML, it is also possible to
use the |loguru-config|_ library developed by `@erezinman`_.
Parameters
----------
handlers : |list| of |dict|, optional
A list of each handler to be added. The list should contain dicts of params passed to
the |add| function as keyword arguments. If not ``None``, all previously added
handlers are first removed.
levels : |list| of |dict|, optional
A list of each level to be added or updated. The list should contain dicts of params
passed to the |level| function as keyword arguments. This will never remove previously
created levels.
extra : |dict|, optional
A dict containing additional parameters bound to the core logger, useful to share
common properties if you call |bind| in several of your files modules. If not ``None``,
this will remove previously configured ``extra`` dict.
patcher : |callable|_, optional
A function that will be applied to the record dict of each logged messages across all
modules using the logger. It should modify the dict in-place without returning anything.
The function is executed prior to the one possibly added by the |patch| method. If not
``None``, this will replace previously configured ``patcher`` function.
activation : |list| of |tuple|, optional
A list of ``(name, state)`` tuples which denotes which loggers should be enabled (if
``state`` is ``True``) or disabled (if ``state`` is ``False``). The calls to |enable|
and |disable| are made accordingly to the list order. This will not modify previously
activated loggers, so if you need a fresh start prepend your list with ``("", False)``
or ``("", True)``.
Returns
-------
:class:`list` of :class:`int`
A list containing the identifiers of added sinks (if any).
Examples
--------
>>> logger.configure(
... handlers=[
... dict(sink=sys.stderr, format="[{time}] {message}"),
... dict(sink="file.log", enqueue=True, serialize=True),
... ],
... levels=[dict(name="NEW", no=13, icon="¤", color="")],
... extra={"common_to_all": "default"},
... patcher=lambda record: record["extra"].update(some_value=42),
... activation=[("my_module.secret", False), ("another_library.module", True)],
... )
[1, 2]
>>> # Set a default "extra" dict to logger across all modules, without "bind()"
>>> extra = {"context": "foo"}
>>> logger.configure(extra=extra)
>>> logger.add(sys.stderr, format="{extra[context]} - {message}")
>>> logger.info("Context without bind")
>>> # => "foo - Context without bind"
>>> logger.bind(context="bar").info("Suppress global context")
>>> # => "bar - Suppress global context"
"""
if handlers is not None:
self.remove()
else:
handlers = []
if levels is not None:
for params in levels:
self.level(**params)
if patcher is not None:
with self._core.lock:
self._core.patcher = patcher
if extra is not None:
with self._core.lock:
self._core.extra.clear()
self._core.extra.update(extra)
if activation is not None:
for name, state in activation:
if state:
self.enable(name)
else:
self.disable(name)
return [self.add(**params) for params in handlers]
def reinstall(self):
"""Reinstall the core of logger.
When using multiprocessing, you can pass logger as a parameter to the target of
``multiprocessing.Process``, and run this method once, thus you don't need to pass
logger to every function you called in the same process with spawn multiprocessing.
Examples
--------
>>> def subworker(logger):
... logger.reinstall()
... logger.info("Child")
... deeper_subworker()
>>> def deeper_subworker():
... logger.info("Grandchild")
>>> def test_process_spawn():
... spawn_context = multiprocessing.get_context("spawn")
... logger.add("file.log", context=spawn_context, enqueue=True, catch=False)
... process = spawn_context.Process(target=subworker, args=(logger,))
... process.start()
... process.join()
... assert process.exitcode == 0
... logger.info("Main")
... logger.remove()
"""
from . import logger
logger._core = self._core
def _change_activation(self, name, status):
if not (name is None or isinstance(name, str)):
raise TypeError(
"Invalid name, it should be a string (or None), not: '%s'" % type(name).__name__
)
with self._core.lock:
enabled = self._core.enabled.copy()
if name is None:
for n in enabled:
if n is None:
enabled[n] = status
self._core.activation_none = status
self._core.enabled = enabled
return
if name != "":
name += "."
activation_list = [
(n, s) for n, s in self._core.activation_list if n[: len(name)] != name
]
parent_status = next((s for n, s in activation_list if name[: len(n)] == n), None)
if parent_status != status and not (name == "" and status is True):
activation_list.append((name, status))
def modules_depth(x):
return x[0].count(".")
activation_list.sort(key=modules_depth, reverse=True)
for n in enabled:
if n is not None and (n + ".")[: len(name)] == name:
enabled[n] = status
self._core.activation_list = activation_list
self._core.enabled = enabled
@staticmethod
def parse(file, pattern, *, cast={}, chunk=2**16): # noqa: B006
"""Parse raw logs and extract each entry as a |dict|.
The logging format has to be specified as the regex ``pattern``, it will then be
used to parse the ``file`` and retrieve each entry based on the named groups present
in the regex.
Parameters
----------
file : |str|, |Path| or |file-like object|_
The path of the log file to be parsed, or an already opened file object.
pattern : |str| or |re.Pattern|_
The regex to use for logs parsing, it should contain named groups which will be included
in the returned dict.
cast : |callable|_ or |dict|, optional
A function that should convert in-place the regex groups parsed (a dict of string
values) to more appropriate types. If a dict is passed, it should be a mapping between
keys of parsed log dict and the function that should be used to convert the associated
value.
chunk : |int|, optional
The number of bytes read while iterating through the logs, this avoids having to load
the whole file in memory.
Yields
------
:class:`dict`
The dict mapping regex named groups to matched values, as returned by |match.groupdict|
and optionally converted according to ``cast`` argument.
Examples
--------
>>> reg = r"(?P<lvl>[0-9]+): (?P<msg>.*)" # If log format is "{level.no} - {message}"
>>> for e in logger.parse("file.log", reg): # A file line could be "10 - A debug message"
... print(e) # => {'lvl': '10', 'msg': 'A debug message'}
>>> caster = dict(lvl=int) # Parse 'lvl' key as an integer
>>> for e in logger.parse("file.log", reg, cast=caster):
... print(e) # => {'lvl': 10, 'msg': 'A debug message'}
>>> def cast(groups):
... if "date" in groups:
... groups["date"] = datetime.strptime(groups["date"], "%Y-%m-%d %H:%M:%S")
...
>>> with open("file.log") as file:
... for log in logger.parse(file, reg, cast=cast):
... print(log["date"], log["something_else"])
"""
if isinstance(file, (str, PathLike)):
@contextlib.contextmanager
def opener():
with open(str(file)) as fileobj:
yield fileobj
elif hasattr(file, "read") and callable(file.read):
@contextlib.contextmanager
def opener():
yield file
else:
raise TypeError(
"Invalid file, it should be a string path or a file object, not: '%s'"
% type(file).__name__
)
if isinstance(cast, dict):
def cast_function(groups):
for key, converter in cast.items():
if key in groups:
groups[key] = converter(groups[key])
elif callable(cast):
cast_function = cast
else:
raise TypeError(
"Invalid cast, it should be a function or a dict, not: '%s'" % type(cast).__name__
)
try:
regex = re.compile(pattern)
except TypeError:
raise TypeError(
"Invalid pattern, it should be a string or a compiled regex, not: '%s'"
% type(pattern).__name__
) from None
with opener() as fileobj:
matches = Logger._find_iter(fileobj, regex, chunk)
for match in matches:
groups = match.groupdict()
cast_function(groups)
yield groups
@staticmethod
def _find_iter(fileobj, regex, chunk):
buffer = fileobj.read(0)
while True:
text = fileobj.read(chunk)
buffer += text
matches = list(regex.finditer(buffer))
if not text:
yield from matches
break
if len(matches) > 1:
end = matches[-2].end()
buffer = buffer[end:]
yield from matches[:-1]
def _log(self, level, from_decorator, options, message, args, kwargs):
core = self._core
if not core.handlers:
return
try:
level_id, level_name, level_no, level_icon = core.levels_lookup[level]
except (KeyError, TypeError):
if isinstance(level, str):
raise ValueError("Level '%s' does not exist" % level) from None
if not isinstance(level, int):
raise TypeError(
"Invalid level, it should be an integer or a string, not: '%s'"
% type(level).__name__
) from None
if level < 0:
raise ValueError(
"Invalid level value, it should be a positive integer, not: %d" % level
) from None
cache = (None, "Level %d" % level, level, " ")
level_id, level_name, level_no, level_icon = cache
core.levels_lookup[level] = cache
if level_no < core.min_level:
return
(exception, depth, record, lazy, colors, raw, capture, patchers, extra) = options
try:
frame = get_frame(depth + 2)
except ValueError:
f_globals = {}
f_lineno = 0
co_name = "<unknown>"
co_filename = "<unknown>"
else:
f_globals = frame.f_globals
f_lineno = frame.f_lineno
co_name = frame.f_code.co_name
co_filename = frame.f_code.co_filename
try:
name = f_globals["__name__"]
except KeyError:
name = None
try:
if not core.enabled[name]:
return
except KeyError:
enabled = core.enabled
if name is None:
status = core.activation_none
enabled[name] = status
if not status:
return
else:
dotted_name = name + "."
for dotted_module_name, status in core.activation_list:
if dotted_name[: len(dotted_module_name)] == dotted_module_name:
if status:
break
enabled[name] = False
return
enabled[name] = True
current_datetime = aware_now()
file_name = basename(co_filename)
thread = current_thread()
process = current_process()
elapsed = current_datetime - start_time
if exception:
if isinstance(exception, BaseException):
type_, value, traceback = (type(exception), exception, exception.__traceback__)
elif isinstance(exception, tuple):
type_, value, traceback = exception
else:
type_, value, traceback = sys.exc_info()
exception = RecordException(type_, value, traceback)
else:
exception = None
log_record = {
"elapsed": elapsed,
"exception": exception,
"extra": {**core.extra, **context.get(), **extra},
"file": RecordFile(file_name, co_filename),
"function": co_name,
"level": RecordLevel(level_name, level_no, level_icon),
"line": f_lineno,
"message": str(message),
"module": splitext(file_name)[0],
"name": name,
"process": RecordProcess(process.ident, process.name),
"thread": RecordThread(thread.ident, thread.name),
"time": current_datetime,
}
if lazy:
args = [arg() for arg in args]
kwargs = {key: value() for key, value in kwargs.items()}
if capture and kwargs:
log_record["extra"].update(kwargs)
if record:
if "record" in kwargs:
raise TypeError(
"The message can't be formatted: 'record' shall not be used as a keyword "
"argument while logger has been configured with '.opt(record=True)'"
)
kwargs.update(record=log_record)
if colors:
if args or kwargs:
colored_message = Colorizer.prepare_message(message, args, kwargs)
else:
colored_message = Colorizer.prepare_simple_message(str(message))
log_record["message"] = colored_message.stripped
elif args or kwargs:
colored_message = None
with try_formatting(KeyError, IndexError, AttributeError, ValueError):
log_record["message"] = message.format(*args, **kwargs)
else:
colored_message = None
if core.patcher:
core.patcher(log_record)
for patcher in patchers:
patcher(log_record)
for handler in core.handlers.values():
handler.emit(log_record, level_id, from_decorator, raw, colored_message)
def trace(__self, __message, *args, **kwargs): # noqa: N805
r"""Log ``message.format(*args, **kwargs)`` with severity ``'TRACE'``."""
__self._log("TRACE", False, __self._options, __message, args, kwargs)
def debug(__self, __message, *args, **kwargs): # noqa: N805
r"""Log ``message.format(*args, **kwargs)`` with severity ``'DEBUG'``."""
__self._log("DEBUG", False, __self._options, __message, args, kwargs)
def info(__self, __message, *args, **kwargs): # noqa: N805
r"""Log ``message.format(*args, **kwargs)`` with severity ``'INFO'``."""
__self._log("INFO", False, __self._options, __message, args, kwargs)
def success(__self, __message, *args, **kwargs): # noqa: N805
r"""Log ``message.format(*args, **kwargs)`` with severity ``'SUCCESS'``."""
__self._log("SUCCESS", False, __self._options, __message, args, kwargs)
def warning(__self, __message, *args, **kwargs): # noqa: N805
r"""Log ``message.format(*args, **kwargs)`` with severity ``'WARNING'``."""
__self._log("WARNING", False, __self._options, __message, args, kwargs)
def error(__self, __message, *args, **kwargs): # noqa: N805
r"""Log ``message.format(*args, **kwargs)`` with severity ``'ERROR'``."""
__self._log("ERROR", False, __self._options, __message, args, kwargs)
def critical(__self, __message, *args, **kwargs): # noqa: N805
r"""Log ``message.format(*args, **kwargs)`` with severity ``'CRITICAL'``."""
__self._log("CRITICAL", False, __self._options, __message, args, kwargs)
def exception(__self, __message, *args, **kwargs): # noqa: N805
r"""Log an ``'ERROR'`` message while also capturing the currently handled exception.
This method internally uses |sys.exc_info|, therefore it should only be called within
an ``except`` block. To log an exception that has already been caught, use the ``exception``
argument of |opt| along with a call to the |error| method (for example).
"""
options = (True, *__self._options[1:])
__self._log("ERROR", False, options, __message, args, kwargs)
def log(__self, __level, __message, *args, **kwargs): # noqa: N805
r"""Log ``message.format(*args, **kwargs)`` with severity ``level``.
Note that if an |int| is provided as ``level``, the level is interpreted as an anonymous
one and displayed as such (see also |FAQ anonymous levels| for more details).
"""
__self._log(__level, False, __self._options, __message, args, kwargs)
def start(self, *args, **kwargs):
"""Add a handler sending log messages to a sink adequately configured.
Deprecated function, use |add| instead.
Warnings
--------
.. deprecated:: 0.2.2
``start()`` will be removed in Loguru 1.0.0, it is replaced by ``add()`` which is a less
confusing name.
"""
warnings.warn(
"The 'start()' method is deprecated, please use 'add()' instead",
DeprecationWarning,
stacklevel=2,
)
return self.add(*args, **kwargs)
def stop(self, *args, **kwargs):
"""Remove a previously added handler and stop sending logs to its sink.
Deprecated function, use |remove| instead.
Warnings
--------
.. deprecated:: 0.2.2
``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less
confusing name.
"""
warnings.warn(
"The 'stop()' method is deprecated, please use 'remove()' instead",
DeprecationWarning,
stacklevel=2,
)
return self.remove(*args, **kwargs)
| Logger |
python | ray-project__ray | python/ray/autoscaler/v2/autoscaler.py | {
"start": 1870,
"end": 8918
} | class ____:
def __init__(
self,
session_name: str,
config_reader: IConfigReader,
gcs_client: GcsClient,
event_logger: Optional[AutoscalerEventLogger] = None,
metrics_reporter: Optional[AutoscalerMetricsReporter] = None,
) -> None:
"""
Args:
session_name: The current Ray session name.
config_reader: The config reader.
gcs_client: The GCS client.
event_logger: The event logger for emitting cluster events.
metrics_reporter: The metrics reporter for emitting cluster metrics.
"""
self._config_reader = config_reader
config = config_reader.get_cached_autoscaling_config()
logger.info(f"Using Autoscaling Config: \n{config.dump()}")
self._gcs_client = gcs_client
self._cloud_instance_provider = None
self._instance_manager = None
self._ray_stop_errors_queue = Queue()
self._ray_install_errors_queue = Queue()
self._event_logger = event_logger
self._metrics_reporter = metrics_reporter
self._init_cloud_instance_provider(config, config_reader)
self._cloud_resource_monitor = None
self._init_instance_manager(
session_name=session_name,
config=config,
cloud_provider=self._cloud_instance_provider,
gcs_client=self._gcs_client,
)
self._scheduler = ResourceDemandScheduler(self._event_logger)
def _init_cloud_instance_provider(
self, config: AutoscalingConfig, config_reader: IConfigReader
):
"""
Initialize the cloud provider, and its dependencies (the v1 node provider)
Args:
config: The autoscaling config.
config_reader: The config reader.
"""
provider_config = config.get_provider_config()
if provider_config["type"] == "kuberay":
provider_config["head_node_type"] = config.get_head_node_type()
self._cloud_instance_provider = KubeRayProvider(
config.get_config("cluster_name"),
provider_config,
)
elif config.provider == Provider.READ_ONLY:
provider_config["gcs_address"] = self._gcs_client.address
self._cloud_instance_provider = ReadOnlyProvider(
provider_config=provider_config,
)
else:
node_provider_v1 = _get_node_provider(
provider_config,
config.get_config("cluster_name"),
)
self._cloud_instance_provider = NodeProviderAdapter(
v1_provider=node_provider_v1,
config_reader=config_reader,
)
def _init_instance_manager(
self,
session_name: str,
cloud_provider: ICloudInstanceProvider,
gcs_client: GcsClient,
config: AutoscalingConfig,
):
"""
Initialize the instance manager, and its dependencies.
"""
instance_storage = InstanceStorage(
cluster_id=session_name,
storage=InMemoryStorage(),
)
subscribers: List[InstanceUpdatedSubscriber] = []
subscribers.append(CloudInstanceUpdater(cloud_provider=cloud_provider))
subscribers.append(
RayStopper(gcs_client=gcs_client, error_queue=self._ray_stop_errors_queue)
)
if not config.disable_node_updaters() and isinstance(
cloud_provider, NodeProviderAdapter
):
head_node_ip = urlsplit("//" + self._gcs_client.address).hostname
assert head_node_ip is not None, "Invalid GCS address format"
subscribers.append(
ThreadedRayInstaller(
head_node_ip=head_node_ip,
instance_storage=instance_storage,
ray_installer=RayInstaller(
provider=cloud_provider.v1_provider,
config=config,
),
error_queue=self._ray_install_errors_queue,
# TODO(rueian): Rewrite the ThreadedRayInstaller and its underlying
# NodeUpdater and CommandRunner to use the asyncio, so that we don't
# need to use so many threads. We use so many threads now because
# they are blocking and letting the new cloud machines to wait for
# previous machines to finish installing Ray is quite inefficient.
max_concurrent_installs=config.get_max_num_worker_nodes() or 50,
)
)
self._cloud_resource_monitor = CloudResourceMonitor()
subscribers.append(self._cloud_resource_monitor)
self._instance_manager = InstanceManager(
instance_storage=instance_storage,
instance_status_update_subscribers=subscribers,
)
def update_autoscaling_state(
self,
) -> Optional[AutoscalingState]:
"""Update the autoscaling state of the cluster by reconciling the current
state of the cluster resources, the cloud providers as well as instance
update subscribers with the desired state.
Returns:
AutoscalingState: The new autoscaling state of the cluster or None if
the state is not updated.
Raises:
None: No exception.
"""
try:
ray_stop_errors = []
while not self._ray_stop_errors_queue.empty():
ray_stop_errors.append(self._ray_stop_errors_queue.get())
ray_install_errors = []
while not self._ray_install_errors_queue.empty():
ray_install_errors.append(self._ray_install_errors_queue.get())
# Get the current state of the ray cluster resources.
ray_cluster_resource_state = get_cluster_resource_state(self._gcs_client)
# Refresh the config from the source
self._config_reader.refresh_cached_autoscaling_config()
autoscaling_config = self._config_reader.get_cached_autoscaling_config()
return Reconciler.reconcile(
instance_manager=self._instance_manager,
scheduler=self._scheduler,
cloud_provider=self._cloud_instance_provider,
cloud_resource_monitor=self._cloud_resource_monitor,
ray_cluster_resource_state=ray_cluster_resource_state,
non_terminated_cloud_instances=(
self._cloud_instance_provider.get_non_terminated()
),
cloud_provider_errors=self._cloud_instance_provider.poll_errors(),
ray_install_errors=ray_install_errors,
ray_stop_errors=ray_stop_errors,
autoscaling_config=autoscaling_config,
metrics_reporter=self._metrics_reporter,
)
except Exception as e:
logger.exception(e)
return None
| Autoscaler |
python | pytorch__pytorch | test/inductor/test_codecache.py | {
"start": 106180,
"end": 107619
} | class ____(TestCase):
@requires_cuda_and_triton
def test_cuda_compile_command(self):
cmd_no_extra_args: str = cuda_compile_command(
["abc.cu", "def.cu"], "output", "so"
)
assert "nvcc " in cmd_no_extra_args, cmd_no_extra_args
assert "abc.cu" in cmd_no_extra_args, cmd_no_extra_args
assert "def.cu" in cmd_no_extra_args, cmd_no_extra_args
assert "output" in cmd_no_extra_args, cmd_no_extra_args
cmd_extra_args: str = cuda_compile_command(
["abc.cu", "def.cu"], "output", "so", ["-Wwhatever", "-nothing"]
)
assert "nvcc " in cmd_extra_args, cmd_extra_args
assert " -Wwhatever" in cmd_extra_args, cmd_extra_args
assert " -nothing" in cmd_extra_args, cmd_extra_args
assert "abc.cu" in cmd_extra_args, cmd_extra_args
assert "def.cu" in cmd_extra_args, cmd_extra_args
assert "output " in cmd_extra_args, cmd_extra_args
with mock.patch("subprocess.check_output") as check_output_mock:
CUDACodeCache.compile("test123.cu", "so", ["-Wsomething"])
check_output_mock.assert_called()
cmd_parts: list[str] = check_output_mock.call_args[0][0]
assert cmd_parts[0].endswith("nvcc"), cmd_parts
assert "-Wsomething" in cmd_parts, cmd_parts
assert "-DNDEBUG" in cmd_parts, cmd_parts
@instantiate_parametrized_tests
| TestCudaCompileCommand |
python | ZoranPandovski__al-go-rithms | data_structures/Graphs/graphsearch/transitive_closure_graph/python/transitive_closure_graph.py | {
"start": 171,
"end": 1416
} | class ____:
def __init__(self,vertices):
# No. of vertices
self.V= vertices
# default dictionary to store graph
self.graph= defaultdict(list)
# To store transitive closure
self.tc = [[0 for j in range(self.V)] for i in range(self.V)]
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
# A recursive DFS traversal function that finds
# all reachable vertices for s
def DFSUtil(self,s,v):
# Mark reachability from s to v as true.
self.tc[s][v] = 1
# Find all the vertices reachable through v
for i in self.graph[v]:
if self.tc[s][i]==0:
self.DFSUtil(s,i)
# The function to find transitive closure. It uses
# recursive DFSUtil()
def transitiveClosure(self):
# Call the recursive function to print DFS
# traversal starting from all vertices one by one
for i in range(self.V):
self.DFSUtil(i, i)
print (self.tc)
# Create a graph
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print ("Transitive closure matrix is")
g.transitiveClosure();
| Graph |
python | pandas-dev__pandas | asv_bench/benchmarks/tslibs/fields.py | {
"start": 162,
"end": 783
} | class ____:
params = [
_sizes,
["seconds", "microseconds", "nanoseconds"],
]
param_names = ["size", "field"]
def setup(self, size, field):
arr = np.random.randint(0, 10, size=size, dtype="i8")
self.i8data = arr
arr = np.random.randint(-86400 * 1_000_000_000, 0, size=size, dtype="i8")
self.i8data_negative = arr
def time_get_timedelta_field(self, size, field):
get_timedelta_field(self.i8data, field)
def time_get_timedelta_field_negative_td(self, size, field):
get_timedelta_field(self.i8data_negative, field)
| TimeGetTimedeltaField |
python | nedbat__coveragepy | tests/test_annotate.py | {
"start": 349,
"end": 3784
} | class ____(CoverageTest):
"""Test the annotate feature with gold files."""
def make_multi(self) -> None:
"""Make a few source files we need for the tests."""
self.make_file(
"multi.py",
"""\
import a.a
import b.b
a.a.a(1)
b.b.b(2)
""",
)
self.make_file("a/__init__.py")
self.make_file(
"a/a.py",
"""\
def a(x):
if x == 1:
print("x is 1")
else:
print("x is not 1")
""",
)
self.make_file("b/__init__.py")
self.make_file(
"b/b.py",
"""\
def b(x):
msg = f"x is {x}"
print(msg)
""",
)
def test_multi(self) -> None:
self.make_multi()
cov = coverage.Coverage()
self.start_import_stop(cov, "multi")
cov.annotate()
compare(gold_path("annotate/multi"), ".", "*,cover")
def test_annotate_dir(self) -> None:
self.make_multi()
cov = coverage.Coverage(source=["."])
self.start_import_stop(cov, "multi")
cov.annotate(directory="out_anno_dir")
compare(gold_path("annotate/anno_dir"), "out_anno_dir", "*,cover")
def test_encoding(self) -> None:
self.make_file(
"utf8.py",
"""\
# -*- coding: utf-8 -*-
# This comment has an accent: é
print("spam eggs")
""",
)
cov = coverage.Coverage()
self.start_import_stop(cov, "utf8")
cov.annotate()
compare(gold_path("annotate/encodings"), ".", "*,cover")
def test_white(self) -> None:
self.make_file(
"white.py",
"""\
# A test case sent to me by Steve White
def f(self):
if self==1:
pass
elif self.m('fred'):
pass
elif (g==1) and (b==2):
pass
elif self.m('fred')==True:
pass
elif ((g==1) and (b==2))==True:
pass
else:
pass
def g(x):
if x == 1:
a = 1
else:
a = 2
g(1)
def h(x):
if 0: #pragma: no cover
pass
if x == 1:
a = 1
else:
a = 2
h(2)
""",
)
cov = coverage.Coverage()
self.start_import_stop(cov, "white")
cov.annotate()
compare(gold_path("annotate/white"), ".", "*,cover")
def test_missing_after_else(self) -> None:
self.make_file(
"mae.py",
"""\
def f(x):
if x == 1:
print("1")
else:
print("2")
if f(1):
print("nope")
if f(2):
print("nope")
""",
)
cov = coverage.Coverage()
self.start_import_stop(cov, "mae")
cov.annotate()
assert self.stdout() == "1\n2\n"
compare(gold_path("annotate/mae"), ".", "*,cover")
| AnnotationGoldTest |
python | bokeh__bokeh | src/bokeh/models/widgets/tables.py | {
"start": 19529,
"end": 19762
} | class ____(CellEditor):
''' Spinner-based time cell editor.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| TimeEditor |
python | falconry__falcon | tests/_inspect_fixture.py | {
"start": 1144,
"end": 1323
} | class ____:
def process_request(self, *args):
pass
def process_resource(self, *args):
pass
def process_response(self, *args):
pass
| MyMiddleware |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fragments.py | {
"start": 1479,
"end": 1660
} | class ____(GQLResult):
typename__: Typename[Literal["ArtifactSequence"]] = "ArtifactSequence"
name: str
project: Optional[ProjectInfoFragment]
| SourceCollectionInfoFragment |
python | astropy__astropy | astropy/utils/masked/tests/test_functions.py | {
"start": 14258,
"end": 14497
} | class ____(MaskedUfuncTests, QuantitySetup):
def test_ufunc_inplace_error2(self):
out = Masked(np.zeros(self.ma.shape))
with pytest.raises(TypeError):
np.add(self.ma, self.mb, out=out)
| TestMaskedQuantityUfuncs |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/mwaa.py | {
"start": 1452,
"end": 7694
} | class ____(AwsBaseSensor[MwaaHook]):
"""
Waits for a DAG Run in an MWAA Environment to complete.
If the DAG Run fails, an AirflowException is thrown.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:MwaaDagRunSensor`
:param external_env_name: The external MWAA environment name that contains the DAG Run you want to wait for
(templated)
:param external_dag_id: The DAG ID in the external MWAA environment that contains the DAG Run you want to wait for
(templated)
:param external_dag_run_id: The DAG Run ID in the external MWAA environment that you want to wait for (templated)
:param success_states: Collection of DAG Run states that would make this task marked as successful, default is
``{airflow.utils.state.DagRunState.SUCCESS}`` (templated)
:param failure_states: Collection of DAG Run states that would make this task marked as failed and raise an
AirflowException, default is ``{airflow.utils.state.DagRunState.FAILED}`` (templated)
:param airflow_version: The Airflow major version the MWAA environment runs.
This parameter is only used if the local web token method is used to call Airflow API. (templated)
:param deferrable: If True, the sensor will operate in deferrable mode. This mode requires aiobotocore
module to be installed.
(default: False, but can be overridden in config file by setting default_deferrable to True)
:param poke_interval: Polling period in seconds to check for the status of the job. (default: 60)
:param max_retries: Number of times before returning the current state. (default: 720)
:param aws_conn_id: The Airflow connection used for AWS credentials.
If this is ``None`` or empty then the default boto3 behaviour is used. If
running Airflow in a distributed manner and aws_conn_id is None or
empty, then default boto3 configuration would be used (and must be
maintained on each worker node).
:param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
:param verify: Whether or not to verify SSL certificates. See:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
:param botocore_config: Configuration dictionary (key-values) for botocore client. See:
https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
"""
aws_hook_class = MwaaHook
template_fields: Sequence[str] = aws_template_fields(
"external_env_name",
"external_dag_id",
"external_dag_run_id",
"success_states",
"failure_states",
"airflow_version",
"deferrable",
"max_retries",
"poke_interval",
)
def __init__(
self,
*,
external_env_name: str,
external_dag_id: str,
external_dag_run_id: str,
success_states: Collection[str] | None = None,
failure_states: Collection[str] | None = None,
airflow_version: Literal[2, 3] | None = None,
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
poke_interval: int = 60,
max_retries: int = 720,
**kwargs,
):
super().__init__(**kwargs)
self.success_states = set(success_states) if success_states else {DagRunState.SUCCESS.value}
self.failure_states = set(failure_states) if failure_states else {DagRunState.FAILED.value}
if len(self.success_states & self.failure_states):
raise ValueError("success_states and failure_states must not have any values in common")
self.external_env_name = external_env_name
self.external_dag_id = external_dag_id
self.external_dag_run_id = external_dag_run_id
self.airflow_version = airflow_version
self.deferrable = deferrable
self.poke_interval = poke_interval
self.max_retries = max_retries
def poke(self, context: Context) -> bool:
self.log.info(
"Poking for DAG run %s of DAG %s in MWAA environment %s",
self.external_dag_run_id,
self.external_dag_id,
self.external_env_name,
)
response = self.hook.invoke_rest_api(
env_name=self.external_env_name,
path=f"/dags/{self.external_dag_id}/dagRuns/{self.external_dag_run_id}",
method="GET",
airflow_version=self.airflow_version,
)
# If RestApiStatusCode == 200, the RestApiResponse must have the "state" key, otherwise something terrible has
# happened in the API and KeyError would be raised
# If RestApiStatusCode >= 300, a botocore exception would've already been raised during the
# self.hook.invoke_rest_api call
# The scope of this sensor is going to only be raising AirflowException due to failure of the DAGRun
state = response["RestApiResponse"]["state"]
if state in self.failure_states:
raise AirflowException(
f"The DAG run {self.external_dag_run_id} of DAG {self.external_dag_id} in MWAA environment {self.external_env_name} "
f"failed with state: {state}"
)
return state in self.success_states
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> None:
return None
def execute(self, context: Context):
if self.deferrable:
self.defer(
trigger=MwaaDagRunCompletedTrigger(
external_env_name=self.external_env_name,
external_dag_id=self.external_dag_id,
external_dag_run_id=self.external_dag_run_id,
success_states=self.success_states,
failure_states=self.failure_states,
waiter_delay=int(self.poke_interval),
waiter_max_attempts=self.max_retries,
aws_conn_id=self.aws_conn_id,
),
method_name="execute_complete",
)
else:
super().execute(context=context)
| MwaaDagRunSensor |
python | numpy__numpy | benchmarks/benchmarks/bench_ufunc_strides.py | {
"start": 4499,
"end": 4700
} | class ____(_AbstractBinary):
arrlen = 100000
params = [
[np.maximum, np.minimum],
[1, 2], [1, 2], [1, 2],
['b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q']
]
| BinaryInt |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_compat.py | {
"start": 2966,
"end": 3772
} | class ____:
a: list
b: tuple
c: namedtuple
d: dict
e: defaultdict
def test_dataclass_asdict():
ANamedTuple = namedtuple("ANamedTuple", ("with_some_field"))
e = defaultdict(list)
e["a"].append(1)
obj = FilledWithStuff(a=[1], b=(2), c=ANamedTuple(3), d={4: 5}, e=e)
assert dataclass_asdict(obj) == {
"a": [1],
"b": (2),
"c": ANamedTuple(3),
"d": {4: 5},
"e": {"a": [1]},
}
@pytest.mark.parametrize("width", [None, 8])
@pytest.mark.parametrize("x", [0, 2, 123])
def test_extract_bits_roundtrip(width, x):
bits = extract_bits(x, width=width)
if width is not None:
assert len(bits) == width
assert x == sum(v << p for p, v in enumerate(reversed(bits)))
@dataclass(frozen=True, slots=False)
| FilledWithStuff |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/base_env.py | {
"start": 18998,
"end": 19562
} | class ____(NamedTuple):
"""
A NamedTuple containing information about the observation and action
spaces for a group of Agents under the same behavior.
- observation_specs is a List of ObservationSpec NamedTuple containing
information about the information of the Agent's observations such as their shapes.
The order of the ObservationSpec is the same as the order of the observations of an
agent.
- action_spec is an ActionSpec NamedTuple.
"""
observation_specs: List[ObservationSpec]
action_spec: ActionSpec
| BehaviorSpec |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/request_builder.py | {
"start": 661,
"end": 1616
} | class ____:
def __init__(self, resource: str = None, api="client_center") -> None:
self._query_params = {}
self._body = None
self.resource = resource
if api == "client_center":
self._api = CLIENT_CENTER_BASE_URL
elif api == "bulk":
self._api = BULK_BASE_URL
elif api == "reporting":
self._api = REPORTING_BASE_URL
else:
raise Exception(f"Unsupported API request: {api}")
def with_body(self, body: Union[str, bytes]):
self._body = body
return self
def build(self) -> HttpRequest:
endpoint = f"/{self.resource}" if self.resource else ""
return HttpRequest(
url=f"{self._api}{endpoint}",
query_params=self._query_params,
body=self._body,
)
def build_report_url(self) -> HttpRequest:
return HttpRequest(
url=REPORT_URL,
)
| RequestBuilder |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/analyzer_cli_test.py | {
"start": 78874,
"end": 81951
} | class ____(test_util.TensorFlowTestCase):
@classmethod
def setUpClass(cls):
cls._dump_root = tempfile.mkdtemp()
with session.Session(config=no_rewrite_session_config()) as sess:
loop_var = constant_op.constant(0, name="while_loop_test/loop_var")
cond = lambda loop_var: math_ops.less(loop_var, 10)
body = lambda loop_var: math_ops.add(loop_var, 1)
while_loop = while_loop_tf.while_loop(
cond, body, [loop_var], parallel_iterations=1)
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_url = "file://%s" % cls._dump_root
watch_opts = run_options.debug_options.debug_tensor_watch_opts
# Add debug tensor watch for "while/Identity".
watch = watch_opts.add()
watch.node_name = "while/Identity"
watch.output_slot = 0
watch.debug_ops.append("DebugIdentity")
watch.debug_urls.append(debug_url)
# Invoke Session.run().
run_metadata = config_pb2.RunMetadata()
sess.run(while_loop, options=run_options, run_metadata=run_metadata)
cls._debug_dump = debug_data.DebugDumpDir(
cls._dump_root, partition_graphs=run_metadata.partition_graphs)
cls._analyzer, cls._registry = create_analyzer_cli(cls._debug_dump)
@classmethod
def tearDownClass(cls):
# Tear down temporary dump directory.
file_io.delete_recursively(cls._dump_root)
def testMultipleDumpsPrintTensorNoNumber(self):
output = self._registry.dispatch_command("pt", ["while/Identity:0"])
self.assertEqual("Tensor \"while/Identity:0\" generated 10 dumps:",
output.lines[0])
for i in range(10):
self.assertTrue(output.lines[i + 1].startswith("#%d" % i))
self.assertTrue(output.lines[i + 1].endswith(
" ms] while/Identity:0:DebugIdentity"))
self.assertEqual(
"You can use the -n (--number) flag to specify which dump to print.",
output.lines[-3])
self.assertEqual("For example:", output.lines[-2])
self.assertEqual(" print_tensor while/Identity:0 -n 0", output.lines[-1])
def testMultipleDumpsPrintTensorWithNumber(self):
for i in range(5):
output = self._registry.dispatch_command(
"pt", ["while/Identity:0", "-n", "%d" % i])
self.assertEqual("Tensor \"while/Identity:0:DebugIdentity (dump #%d)\":" %
i, output.lines[0])
self.assertEqual(" dtype: int32", output.lines[1])
self.assertEqual(" shape: ()", output.lines[2])
self.assertEqual("", output.lines[3])
self.assertTrue(output.lines[4].startswith("array(%d" % i))
self.assertTrue(output.lines[4].endswith(")"))
def testMultipleDumpsPrintTensorInvalidNumber(self):
output = self._registry.dispatch_command("pt",
["while/Identity:0", "-n", "10"])
self.assertEqual([
"ERROR: Specified number (10) exceeds the number of available dumps "
"(10) for tensor while/Identity:0"
], output.lines)
if __name__ == "__main__":
googletest.main()
| AnalyzerCLIWhileLoopTest |
python | Pylons__pyramid | tests/test_events.py | {
"start": 11036,
"end": 11339
} | class ____:
def __init__(self):
self.subscribed = []
def add_subscriber(self, wrapped, ifaces, **predicates):
if not predicates:
self.subscribed.append((wrapped, ifaces))
else:
self.subscribed.append((wrapped, ifaces, predicates))
| DummyConfigurator |
python | django__django | django/core/mail/backends/dummy.py | {
"start": 110,
"end": 234
} | class ____(BaseEmailBackend):
def send_messages(self, email_messages):
return len(list(email_messages))
| EmailBackend |
python | jazzband__pip-tools | piptools/build.py | {
"start": 1225,
"end": 12519
} | class ____:
extras: tuple[str, ...]
requirements: tuple[InstallRequirement, ...]
build_requirements: tuple[InstallRequirement, ...]
def maybe_statically_parse_project_metadata(
src_file: pathlib.Path,
) -> StaticProjectMetadata | None:
"""
Return the metadata for a project, if it can be statically parsed from ``pyproject.toml``.
This function is typically significantly faster than invoking a build backend.
Returns None if the project metadata cannot be statically parsed.
"""
if src_file.name != PYPROJECT_TOML:
return None
try:
with open(src_file, "rb") as f:
pyproject_contents = tomllib.load(f)
except tomllib.TOMLDecodeError:
return None
# Not valid PEP 621 metadata
if (
"project" not in pyproject_contents
or "name" not in pyproject_contents["project"]
):
return None
project_table = pyproject_contents["project"]
# Dynamic dependencies require build backend invocation
dynamic = project_table.get("dynamic", [])
if "dependencies" in dynamic or "optional-dependencies" in dynamic:
return None
package_name = project_table["name"]
comes_from = f"{package_name} ({src_file.as_posix()})"
extras = project_table.get("optional-dependencies", {}).keys()
install_requirements = [
InstallRequirement(Requirement(req), comes_from)
for req in project_table.get("dependencies", [])
]
for extra, reqs in (
pyproject_contents.get("project", {}).get("optional-dependencies", {}).items()
):
for req in reqs:
requirement = Requirement(req)
if requirement.name == package_name:
# Similar to logic for handling self-referential requirements
# from _prepare_requirements
requirement.url = src_file.parent.absolute().as_uri()
# Note we don't need to modify `requirement` to include this extra
marker = Marker(f"extra == '{extra}'")
install_requirements.append(
InstallRequirement(requirement, comes_from, markers=marker)
)
return StaticProjectMetadata(
extras=tuple(extras),
requirements=tuple(install_requirements),
)
def build_project_metadata(
src_file: pathlib.Path,
build_targets: tuple[str, ...],
*,
upgrade_packages: tuple[str, ...] | None = None,
attempt_static_parse: bool,
isolated: bool,
quiet: bool,
) -> ProjectMetadata | StaticProjectMetadata:
"""
Return the metadata for a project.
First, optionally attempt to determine the metadata statically from the
``pyproject.toml`` file. This will not work if build_targets are specified,
since we cannot determine build requirements statically.
Uses the ``prepare_metadata_for_build_wheel`` hook for the wheel metadata
if available, otherwise ``build_wheel``.
Uses the ``prepare_metadata_for_build_{target}`` hook for each ``build_targets``
if available.
:param src_file: Project source file
:param build_targets: A tuple of build targets to get the dependencies
of (``sdist`` or ``wheel`` or ``editable``).
:param attempt_static_parse: Whether to attempt to statically parse the
project metadata from ``pyproject.toml``.
Cannot be used with ``build_targets``.
:param isolated: Whether to run invoke the backend in the current
environment or to create an isolated one and invoke it
there.
:param quiet: Whether to suppress the output of subprocesses.
"""
if attempt_static_parse:
if build_targets:
raise ValueError(
"Cannot execute the PEP 517 optional get_requires_for_build* "
"hooks statically, as build requirements are requested"
)
project_metadata = maybe_statically_parse_project_metadata(src_file)
if project_metadata is not None:
return project_metadata
src_dir = src_file.parent
with _create_project_builder(
src_dir,
upgrade_packages=upgrade_packages,
isolated=isolated,
quiet=quiet,
) as builder:
metadata = _build_project_wheel_metadata(builder)
extras = tuple(metadata.get_all("Provides-Extra") or ())
requirements = tuple(
_prepare_requirements(metadata=metadata, src_file=src_file)
)
build_requirements = tuple(
_prepare_build_requirements(
builder=builder,
src_file=src_file,
build_targets=build_targets,
package_name=_get_name(metadata),
)
)
return ProjectMetadata(
extras=extras,
requirements=requirements,
build_requirements=build_requirements,
)
@contextlib.contextmanager
def _env_var(
env_var_name: str,
env_var_value: str,
/,
) -> Iterator[None]:
sentinel = object()
original_pip_constraint = os.getenv(env_var_name, sentinel)
pip_constraint_was_unset = original_pip_constraint is sentinel
os.environ[env_var_name] = env_var_value
try:
yield
finally:
if pip_constraint_was_unset:
del os.environ[env_var_name]
else:
# Assert here is necessary because MyPy can't infer type
# narrowing in the complex case.
assert isinstance(original_pip_constraint, str)
os.environ[env_var_name] = original_pip_constraint
@contextlib.contextmanager
def _temporary_constraints_file_set_for_pip(
upgrade_packages: tuple[str, ...],
) -> Iterator[None]:
with tempfile.NamedTemporaryFile(
mode="w+t",
delete=False, # FIXME: switch to `delete_on_close` in Python 3.12+
) as tmpfile:
# NOTE: `delete_on_close=False` here (or rather `delete=False`,
# NOTE: temporarily) is important for cross-platform execution. It is
# NOTE: required on Windows so that the underlying `pip install`
# NOTE: invocation by pypa/build will be able to access the constraint
# NOTE: file via a subprocess and not fail installing it due to a
# NOTE: permission error related to this file handle still open in our
# NOTE: parent process. To achieve this, we `.close()` the file
# NOTE: descriptor before we hand off the control to the build frontend
# NOTE: and with `delete_on_close=False`, the
# NOTE: `tempfile.NamedTemporaryFile()` context manager does not remove
# NOTE: it from disk right away.
# NOTE: Due to support of versions below Python 3.12, we are forced to
# NOTE: temporarily resort to using `delete=False`, meaning that the CM
# NOTE: never attempts removing the file from disk, not even on exit.
# NOTE: So we do this manually until we can migrate to using the more
# NOTE: ergonomic argument `delete_on_close=False`.
# Write packages to upgrade to a temporary file to set as
# constraints for the installation to the builder environment,
# in case build requirements are among them
tmpfile.write("\n".join(upgrade_packages))
# FIXME: replace `delete` with `delete_on_close` in Python 3.12+
# FIXME: and replace `.close()` with `.flush()`
tmpfile.close()
try:
with _env_var("PIP_CONSTRAINT", tmpfile.name):
yield
finally:
# FIXME: replace `delete` with `delete_on_close` in Python 3.12+
# FIXME: and drop this manual deletion
os.unlink(tmpfile.name)
@contextlib.contextmanager
def _create_project_builder(
src_dir: pathlib.Path,
*,
upgrade_packages: tuple[str, ...] | None = None,
isolated: bool,
quiet: bool,
) -> Iterator[build.ProjectBuilder]:
if quiet:
runner = pyproject_hooks.quiet_subprocess_runner
else:
runner = pyproject_hooks.default_subprocess_runner
if not isolated:
yield build.ProjectBuilder(src_dir, runner=runner)
return
maybe_pip_constrained_context = (
contextlib.nullcontext()
if upgrade_packages is None
else _temporary_constraints_file_set_for_pip(upgrade_packages)
)
with maybe_pip_constrained_context, build.env.DefaultIsolatedEnv() as env:
builder = build.ProjectBuilder.from_isolated_env(env, src_dir, runner)
env.install(builder.build_system_requires)
env.install(builder.get_requires_for_build("wheel"))
yield builder
def _build_project_wheel_metadata(
builder: build.ProjectBuilder,
) -> PackageMetadata:
with tempfile.TemporaryDirectory() as tmpdir:
path = pathlib.Path(builder.metadata_path(tmpdir))
return importlib_metadata.PathDistribution(path).metadata
def _get_name(metadata: PackageMetadata) -> str:
retval = metadata.get_all("Name")[0] # type: ignore[index]
assert isinstance(retval, str)
return retval
def _prepare_requirements(
metadata: PackageMetadata, src_file: pathlib.Path
) -> Iterator[InstallRequirement]:
package_name = _get_name(metadata)
comes_from = f"{package_name} ({src_file.as_posix()})"
package_dir = src_file.parent
for req in metadata.get_all("Requires-Dist") or []:
parts = parse_req_from_line(req, comes_from)
if parts.requirement.name == package_name:
# Replace package name with package directory in the requirement
# string so that pip can find the package as self-referential.
# Note the string can contain extras, so we need to replace only
# the package name, not the whole string.
replaced_package_name = req.replace(package_name, str(package_dir), 1)
parts = parse_req_from_line(replaced_package_name, comes_from)
yield copy_install_requirement(
InstallRequirement(
parts.requirement,
comes_from,
link=parts.link,
markers=parts.markers,
extras=parts.extras,
)
)
def _prepare_build_requirements(
builder: build.ProjectBuilder,
src_file: pathlib.Path,
build_targets: tuple[str, ...],
package_name: str,
) -> Iterator[InstallRequirement]:
result = collections.defaultdict(set)
# Build requirements will only be present if a pyproject.toml file exists,
# but if there is also a setup.py file then only that will be explicitly
# processed due to the order of `DEFAULT_REQUIREMENTS_FILES`.
src_file = src_file.parent / PYPROJECT_TOML
for req in builder.build_system_requires:
result[req].add(f"{package_name} ({src_file}::build-system.requires)")
for build_target in build_targets:
for req in builder.get_requires_for_build(build_target):
result[req].add(
f"{package_name} ({src_file}::build-system.backend::{build_target})"
)
for req, comes_from_sources in result.items():
for comes_from in comes_from_sources:
yield install_req_from_line(req, comes_from=comes_from)
| ProjectMetadata |
python | allegroai__clearml | clearml/backend_config/environment.py | {
"start": 150,
"end": 1240
} | class ____(Entry):
@classmethod
def default_conversions(cls) -> Dict[Any, Callable[[str], Any]]:
conversions = super(EnvEntry, cls).default_conversions().copy()
conversions[bool] = text_to_bool
return conversions
def __init__(self, key: str, *more_keys: Any, **kwargs: Any) -> None:
super(EnvEntry, self).__init__(key, *more_keys, **kwargs)
self._ignore_errors = kwargs.pop("ignore_errors", False)
def pop(self) -> None:
for k in self.keys:
environ.pop(k, None)
def _get(self, key: str) -> Union[str, Any]:
value = getenv(key, "").strip()
return value or NotSet
def _set(self, key: str, value: str) -> None:
environ[key] = value
def __str__(self) -> str:
return "env:{}".format(super(EnvEntry, self).__str__())
def error(self, message: str) -> None:
if not self._ignore_errors:
print("Environment configuration: {}".format(message))
def exists(self) -> bool:
return any(key for key in self.keys if getenv(key) is not None)
| EnvEntry |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/skip_test.py | {
"start": 3273,
"end": 5513
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(index=[-1, 2, 3])))
def testInvalidIndex(self, index):
dataset = dataset_ops.Dataset.range(10).skip(8)
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(random_access.at(dataset, index=index))
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(index=[-1, 0])))
def testEmptyDataset(self, index):
dataset = dataset_ops.Dataset.from_tensor_slices([]).skip(8)
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(random_access.at(dataset, index=index))
@combinations.generate(
combinations.times(test_base.default_test_combinations()))
def testBasic(self):
dataset = dataset_ops.Dataset.range(11).skip(3)
for i in range(8):
self.assertEqual(self.evaluate(random_access.at(dataset, index=i)), i + 3)
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(skip=[-2, -1])))
def testNegativeSkip(self, skip):
dataset = dataset_ops.Dataset.range(11).skip(skip)
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(random_access.at(dataset, index=0))
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(skip=[5, 8])))
def testSkipGreaterThanNumElements(self, skip):
dataset = dataset_ops.Dataset.range(4).skip(skip)
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(random_access.at(dataset, index=0))
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(elements=[0, 5, 10], skip=[-1, 0, 5, 15])))
def testMultipleCombinations(self, elements, skip):
dataset = dataset_ops.Dataset.range(elements).skip(skip)
for i in range(self.evaluate(dataset.cardinality())):
self.assertEqual(
self.evaluate(random_access.at(dataset, index=i)), i + skip)
| SkipRandomAccessTest |
python | tornadoweb__tornado | tornado/test/httpserver_test.py | {
"start": 11196,
"end": 11434
} | class ____(PostEchoHandler):
def decode_argument(self, value, name=None):
try:
return value.decode("gbk")
except Exception:
raise HTTPError(400, "invalid gbk bytes: %r" % value)
| PostEchoGBKHandler |
python | ray-project__ray | python/ray/air/util/tensor_extensions/arrow.py | {
"start": 25459,
"end": 25712
} | class ____(pa.ExtensionScalar):
def as_py(self, **kwargs) -> np.ndarray:
return self.__array__()
def __array__(self) -> np.ndarray:
return self.type._extension_scalar_to_ndarray(self)
@PublicAPI(stability="beta")
| ArrowTensorScalar |
python | davidhalter__jedi | test/test_api/test_interpreter.py | {
"start": 23553,
"end": 26151
} | class ____:
its_me = 1
@pytest.mark.parametrize('class_is_findable', [False, True])
def test_try_to_use_return_annotation_for_property(class_is_findable):
class WithProperties(object):
@property
def with_annotation1(self) -> str:
raise BaseException
@property
def with_annotation2(self) -> 'str':
raise BaseException
@property
def with_annotation3(self) -> Hello:
raise BaseException
@property
def with_annotation4(self) -> 'Hello':
raise BaseException
@property
def with_annotation_garbage1(self) -> 'asldjflksjdfljdslkjfsl': # noqa
return Hello()
@property
def with_annotation_garbage2(self) -> 'sdf$@@$5*+8': # noqa
return Hello()
@property
def without_annotation(self):
return ""
if not class_is_findable:
WithProperties.__name__ = "something_somewhere"
Hello.__name__ = "something_somewhere_else"
namespace = {'p': WithProperties()}
_assert_interpreter_complete('p.without_annotation.upp', namespace, ['upper'])
_assert_interpreter_complete('p.with_annotation1.upp', namespace, ['upper'])
_assert_interpreter_complete('p.with_annotation2.upp', namespace, ['upper'])
_assert_interpreter_complete('p.with_annotation3.its', namespace, ['its_me'])
_assert_interpreter_complete('p.with_annotation4.its', namespace, ['its_me'])
# This is a fallback, if the annotations don't help
_assert_interpreter_complete('p.with_annotation_garbage1.its', namespace, ['its_me'])
_assert_interpreter_complete('p.with_annotation_garbage2.its', namespace, ['its_me'])
def test_nested__getitem__():
d = {'foo': {'bar': 1}}
_assert_interpreter_complete('d["fo', locals(), ['"foo"'])
_assert_interpreter_complete('d["foo"]["ba', locals(), ['"bar"'])
_assert_interpreter_complete('(d["foo"])["ba', locals(), ['"bar"'])
_assert_interpreter_complete('((d["foo"]))["ba', locals(), ['"bar"'])
@pytest.mark.parametrize('class_is_findable', [False, True])
def test_custom__getitem__(class_is_findable, allow_unsafe_getattr):
class CustomGetItem:
def __getitem__(self, x: int):
return "asdf"
if not class_is_findable:
CustomGetItem.__name__ = "something_somewhere"
namespace = {'c': CustomGetItem()}
if not class_is_findable and not allow_unsafe_getattr:
expected = []
else:
expected = ['upper']
_assert_interpreter_complete('c["a"].up', namespace, expected)
| Hello |
python | getsentry__sentry | tests/sentry/middleware/test_ratelimit_middleware.py | {
"start": 14576,
"end": 17301
} | class ____(APITestCase):
endpoint = "ratelimit-header-endpoint"
def test_header_counts(self) -> None:
"""Ensure that the header remainder counts decrease properly"""
with freeze_time("2000-01-01"):
expected_reset_time = int(time() + 100)
response = self.get_success_response()
assert int(response["X-Sentry-Rate-Limit-Remaining"]) == 1
assert int(response["X-Sentry-Rate-Limit-Limit"]) == 2
assert int(response["X-Sentry-Rate-Limit-Reset"]) == expected_reset_time
response = self.get_success_response()
assert int(response["X-Sentry-Rate-Limit-Remaining"]) == 0
assert int(response["X-Sentry-Rate-Limit-Limit"]) == 2
assert int(response["X-Sentry-Rate-Limit-Reset"]) == expected_reset_time
response = self.get_error_response()
assert int(response["X-Sentry-Rate-Limit-Remaining"]) == 0
assert int(response["X-Sentry-Rate-Limit-Limit"]) == 2
assert int(response["X-Sentry-Rate-Limit-Reset"]) == expected_reset_time
response = self.get_error_response()
assert int(response["X-Sentry-Rate-Limit-Remaining"]) == 0
assert int(response["X-Sentry-Rate-Limit-Limit"]) == 2
assert int(response["X-Sentry-Rate-Limit-Reset"]) == expected_reset_time
@patch("sentry.middleware.ratelimit.get_rate_limit_key")
def test_omit_header(self, can_be_ratelimited_patch: MagicMock) -> None:
"""
Ensure that functions that can't be rate limited don't have rate limit headers
These functions include, but are not limited to:
- UI Statistics Endpoints
- Endpoints that don't inherit api.base.Endpoint
"""
can_be_ratelimited_patch.return_value = None
response = self.get_response()
assert not response.has_header("X-Sentry-Rate-Limit-Remaining")
assert not response.has_header("X-Sentry-Rate-Limit-Limit")
assert not response.has_header("X-Sentry-Rate-Limit-Reset")
def test_header_race_condition(self) -> None:
"""Make sure concurrent requests don't affect each other's rate limit"""
def parallel_request(*args, **kwargs):
self.client.get(reverse("race-condition-endpoint"))
with patch.object(
RateLimitHeaderTestEndpoint,
"inject_call",
parallel_request,
):
response = self.get_success_response()
assert int(response["X-Sentry-Rate-Limit-Remaining"]) == 1
assert int(response["X-Sentry-Rate-Limit-Limit"]) == 2
@override_settings(ROOT_URLCONF=__name__, SENTRY_SELF_HOSTED=False)
| TestRatelimitHeader |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 645207,
"end": 645789
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("TeamEdge"), graphql_name="edges")
nodes = sgqlc.types.Field(sgqlc.types.list_of("Team"), graphql_name="nodes")
page_info = sgqlc.types.Field(
sgqlc.types.non_null(PageInfo), graphql_name="pageInfo"
)
total_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="totalCount"
)
| TeamConnection |
python | huggingface__transformers | src/transformers/models/qwen3/modeling_qwen3.py | {
"start": 23592,
"end": 23965
} | class ____(GenericForQuestionAnswering, Qwen3PreTrainedModel):
base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
__all__ = [
"Qwen3ForCausalLM",
"Qwen3ForQuestionAnswering",
"Qwen3PreTrainedModel",
"Qwen3Model",
"Qwen3ForSequenceClassification",
"Qwen3ForTokenClassification",
]
| Qwen3ForQuestionAnswering |
python | pypa__pipenv | pipenv/exceptions.py | {
"start": 4835,
"end": 5683
} | class ____(FileError):
formatted_message = "{} {{}} {{}}".format("[bold red]ERROR:[/bold red]")
def __init__(self, filename, message=None, **kwargs):
extra = kwargs.pop("extra", [])
if not message:
message = "[bold]Please ensure that the file exists![/bold]"
message = self.formatted_message.format(
f"[bold]{filename} not found![/bold]", message
)
FileError.__init__(self, filename=filename, hint=message, **kwargs)
self.extra = extra
def show(self, file=None):
console = Console(stderr=True, file=file, highlight=False)
if self.extra:
if isinstance(self.extra, str):
self.extra = [self.extra]
for extra in self.extra:
console.print(extra)
console.print(self.message)
| PipenvFileError |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 277346,
"end": 300771
} | class ____(VegaLiteSchema):
"""
Config schema wrapper.
Parameters
----------
arc : dict, :class:`RectConfig`
Arc-specific Config
area : dict, :class:`AreaConfig`
Area-Specific Config
aria : bool
A boolean flag indicating if ARIA default attributes should be included for marks
and guides (SVG output only). If false, the ``"aria-hidden"`` attribute will be set
for all guides, removing them from the ARIA accessibility tree and Vega-Lite will
not generate default descriptions for marks.
**Default value:** ``true``.
autosize : dict, :class:`AutosizeType`, :class:`AutoSizeParams`, Literal['pad', 'none', 'fit', 'fit-x', 'fit-y']
How the visualization size should be determined. If a string, should be one of
``"pad"``, ``"fit"`` or ``"none"``. Object values can additionally specify
parameters for content sizing and automatic resizing.
**Default value**: ``pad``
axis : dict, :class:`AxisConfig`
Axis configuration, which determines default properties for all ``x`` and ``y``
`axes <https://vega.github.io/vega-lite/docs/axis.html>`__. For a full list of axis
configuration options, please see the `corresponding section of the axis
documentation <https://vega.github.io/vega-lite/docs/axis.html#config>`__.
axisBand : dict, :class:`AxisConfig`
Config for axes with "band" scales.
axisBottom : dict, :class:`AxisConfig`
Config for x-axis along the bottom edge of the chart.
axisDiscrete : dict, :class:`AxisConfig`
Config for axes with "point" or "band" scales.
axisLeft : dict, :class:`AxisConfig`
Config for y-axis along the left edge of the chart.
axisPoint : dict, :class:`AxisConfig`
Config for axes with "point" scales.
axisQuantitative : dict, :class:`AxisConfig`
Config for quantitative axes.
axisRight : dict, :class:`AxisConfig`
Config for y-axis along the right edge of the chart.
axisTemporal : dict, :class:`AxisConfig`
Config for temporal axes.
axisTop : dict, :class:`AxisConfig`
Config for x-axis along the top edge of the chart.
axisX : dict, :class:`AxisConfig`
X-axis specific config.
axisXBand : dict, :class:`AxisConfig`
Config for x-axes with "band" scales.
axisXDiscrete : dict, :class:`AxisConfig`
Config for x-axes with "point" or "band" scales.
axisXPoint : dict, :class:`AxisConfig`
Config for x-axes with "point" scales.
axisXQuantitative : dict, :class:`AxisConfig`
Config for x-quantitative axes.
axisXTemporal : dict, :class:`AxisConfig`
Config for x-temporal axes.
axisY : dict, :class:`AxisConfig`
Y-axis specific config.
axisYBand : dict, :class:`AxisConfig`
Config for y-axes with "band" scales.
axisYDiscrete : dict, :class:`AxisConfig`
Config for y-axes with "point" or "band" scales.
axisYPoint : dict, :class:`AxisConfig`
Config for y-axes with "point" scales.
axisYQuantitative : dict, :class:`AxisConfig`
Config for y-quantitative axes.
axisYTemporal : dict, :class:`AxisConfig`
Config for y-temporal axes.
background : str, dict, :class:`Color`, :class:`ExprRef`, :class:`HexColor`, :class:`ColorName`, Literal['black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'whitesmoke', 'yellowgreen', 'rebeccapurple']
CSS color property to use as the background of the entire view.
**Default value:** ``"white"``
bar : dict, :class:`BarConfig`
Bar-Specific Config
boxplot : dict, :class:`BoxPlotConfig`
Box Config
circle : dict, :class:`MarkConfig`
Circle-Specific Config
concat : dict, :class:`CompositionConfig`
Default configuration for all concatenation and repeat view composition operators
(``concat``, ``hconcat``, ``vconcat``, and ``repeat``)
countTitle : str
Default axis and legend title for count fields.
**Default value:** ``'Count of Records``.
customFormatTypes : bool
Allow the ``formatType`` property for text marks and guides to accept a custom
formatter function `registered as a Vega expression
<https://vega.github.io/vega-lite/usage/compile.html#format-type>`__.
errorband : dict, :class:`ErrorBandConfig`
ErrorBand Config
errorbar : dict, :class:`ErrorBarConfig`
ErrorBar Config
facet : dict, :class:`CompositionConfig`
Default configuration for the ``facet`` view composition operator
fieldTitle : Literal['verbal', 'functional', 'plain']
Defines how Vega-Lite generates title for fields. There are three possible styles:
* ``"verbal"`` (Default) - displays function in a verbal style (e.g., "Sum of
field", "Year-month of date", "field (binned)").
* ``"function"`` - displays function using parentheses and capitalized texts (e.g.,
"SUM(field)", "YEARMONTH(date)", "BIN(field)").
* ``"plain"`` - displays only the field name without functions (e.g., "field",
"date", "field").
font : str
Default font for all text marks, titles, and labels.
geoshape : dict, :class:`MarkConfig`
Geoshape-Specific Config
header : dict, :class:`HeaderConfig`
Header configuration, which determines default properties for all `headers
<https://vega.github.io/vega-lite/docs/header.html>`__.
For a full list of header configuration options, please see the `corresponding
section of in the header documentation
<https://vega.github.io/vega-lite/docs/header.html#config>`__.
headerColumn : dict, :class:`HeaderConfig`
Header configuration, which determines default properties for column `headers
<https://vega.github.io/vega-lite/docs/header.html>`__.
For a full list of header configuration options, please see the `corresponding
section of in the header documentation
<https://vega.github.io/vega-lite/docs/header.html#config>`__.
headerFacet : dict, :class:`HeaderConfig`
Header configuration, which determines default properties for non-row/column facet
`headers <https://vega.github.io/vega-lite/docs/header.html>`__.
For a full list of header configuration options, please see the `corresponding
section of in the header documentation
<https://vega.github.io/vega-lite/docs/header.html#config>`__.
headerRow : dict, :class:`HeaderConfig`
Header configuration, which determines default properties for row `headers
<https://vega.github.io/vega-lite/docs/header.html>`__.
For a full list of header configuration options, please see the `corresponding
section of in the header documentation
<https://vega.github.io/vega-lite/docs/header.html#config>`__.
image : dict, :class:`RectConfig`
Image-specific Config
legend : dict, :class:`LegendConfig`
Legend configuration, which determines default properties for all `legends
<https://vega.github.io/vega-lite/docs/legend.html>`__. For a full list of legend
configuration options, please see the `corresponding section of in the legend
documentation <https://vega.github.io/vega-lite/docs/legend.html#config>`__.
line : dict, :class:`LineConfig`
Line-Specific Config
lineBreak : str, dict, :class:`ExprRef`
A delimiter, such as a newline character, upon which to break text strings into
multiple lines. This property provides a global default for text marks, which is
overridden by mark or style config settings, and by the lineBreak mark encoding
channel. If signal-valued, either string or regular expression (regexp) values are
valid.
locale : dict, :class:`Locale`
Locale definitions for string parsing and formatting of number and date values. The
locale object should contain ``number`` and/or ``time`` properties with `locale
definitions <https://vega.github.io/vega/docs/api/locale/>`__. Locale definitions
provided in the config block may be overridden by the View constructor locale
option.
mark : dict, :class:`MarkConfig`
Mark Config
normalizedNumberFormat : str
If normalizedNumberFormatType is not specified, D3 number format for axis labels,
text marks, and tooltips of normalized stacked fields (fields with ``stack:
"normalize"``). For example ``"s"`` for SI units. Use `D3's number format pattern
<https://github.com/d3/d3-format#locale_format>`__.
If ``config.normalizedNumberFormatType`` is specified and
``config.customFormatTypes`` is ``true``, this value will be passed as ``format``
alongside ``datum.value`` to the ``config.numberFormatType`` function. **Default
value:** ``%``
normalizedNumberFormatType : str
`Custom format type
<https://vega.github.io/vega-lite/docs/config.html#custom-format-type>`__ for
``config.normalizedNumberFormat``.
**Default value:** ``undefined`` -- This is equilvalent to call D3-format, which is
exposed as `format in Vega-Expression
<https://vega.github.io/vega/docs/expressions/#format>`__. **Note:** You must also
set ``customFormatTypes`` to ``true`` to use this feature.
numberFormat : str
If numberFormatType is not specified, D3 number format for guide labels, text marks,
and tooltips of non-normalized fields (fields *without* ``stack: "normalize"``). For
example ``"s"`` for SI units. Use `D3's number format pattern
<https://github.com/d3/d3-format#locale_format>`__.
If ``config.numberFormatType`` is specified and ``config.customFormatTypes`` is
``true``, this value will be passed as ``format`` alongside ``datum.value`` to the
``config.numberFormatType`` function.
numberFormatType : str
`Custom format type
<https://vega.github.io/vega-lite/docs/config.html#custom-format-type>`__ for
``config.numberFormat``.
**Default value:** ``undefined`` -- This is equilvalent to call D3-format, which is
exposed as `format in Vega-Expression
<https://vega.github.io/vega/docs/expressions/#format>`__. **Note:** You must also
set ``customFormatTypes`` to ``true`` to use this feature.
padding : dict, float, :class:`ExprRef`, :class:`Padding`
The default visualization padding, in pixels, from the edge of the visualization
canvas to the data rectangle. If a number, specifies padding for all sides. If an
object, the value should have the format ``{"left": 5, "top": 5, "right": 5,
"bottom": 5}`` to specify padding for each side of the visualization.
**Default value**: ``5``
params : Sequence[dict, :class:`TopLevelParameter`, :class:`VariableParameter`, :class:`TopLevelSelectionParameter`]
Dynamic variables or selections that parameterize a visualization.
point : dict, :class:`MarkConfig`
Point-Specific Config
projection : dict, :class:`ProjectionConfig`
Projection configuration, which determines default properties for all `projections
<https://vega.github.io/vega-lite/docs/projection.html>`__. For a full list of
projection configuration options, please see the `corresponding section of the
projection documentation
<https://vega.github.io/vega-lite/docs/projection.html#config>`__.
range : dict, :class:`RangeConfig`
An object hash that defines default range arrays or schemes for using with scales.
For a full list of scale range configuration options, please see the `corresponding
section of the scale documentation
<https://vega.github.io/vega-lite/docs/scale.html#config>`__.
rect : dict, :class:`RectConfig`
Rect-Specific Config
rule : dict, :class:`MarkConfig`
Rule-Specific Config
scale : dict, :class:`ScaleConfig`
Scale configuration determines default properties for all `scales
<https://vega.github.io/vega-lite/docs/scale.html>`__. For a full list of scale
configuration options, please see the `corresponding section of the scale
documentation <https://vega.github.io/vega-lite/docs/scale.html#config>`__.
selection : dict, :class:`SelectionConfig`
An object hash for defining default properties for each type of selections.
square : dict, :class:`MarkConfig`
Square-Specific Config
style : dict, :class:`StyleConfigIndex`
An object hash that defines key-value mappings to determine default properties for
marks with a given `style
<https://vega.github.io/vega-lite/docs/mark.html#mark-def>`__. The keys represent
styles names; the values have to be valid `mark configuration objects
<https://vega.github.io/vega-lite/docs/mark.html#config>`__.
text : dict, :class:`MarkConfig`
Text-Specific Config
tick : dict, :class:`TickConfig`
Tick-Specific Config
timeFormat : str
Default time format for raw time values (without time units) in text marks, legend
labels and header labels.
**Default value:** ``"%b %d, %Y"`` **Note:** Axes automatically determine the format
for each label automatically so this config does not affect axes.
timeFormatType : str
`Custom format type
<https://vega.github.io/vega-lite/docs/config.html#custom-format-type>`__ for
``config.timeFormat``.
**Default value:** ``undefined`` -- This is equilvalent to call D3-time-format,
which is exposed as `timeFormat in Vega-Expression
<https://vega.github.io/vega/docs/expressions/#timeFormat>`__. **Note:** You must
also set ``customFormatTypes`` to ``true`` and there must *not* be a ``timeUnit``
defined to use this feature.
title : dict, :class:`TitleConfig`
Title configuration, which determines default properties for all `titles
<https://vega.github.io/vega-lite/docs/title.html>`__. For a full list of title
configuration options, please see the `corresponding section of the title
documentation <https://vega.github.io/vega-lite/docs/title.html#config>`__.
tooltipFormat : dict, :class:`FormatConfig`
Define `custom format configuration
<https://vega.github.io/vega-lite/docs/config.html#format>`__ for tooltips. If
unspecified, default format config will be applied.
trail : dict, :class:`LineConfig`
Trail-Specific Config
view : dict, :class:`ViewConfig`
Default properties for `single view plots
<https://vega.github.io/vega-lite/docs/spec.html#single>`__.
"""
_schema = {"$ref": "#/definitions/Config"}
def __init__(
self,
arc: Optional[SchemaBase | Map] = Undefined,
area: Optional[SchemaBase | Map] = Undefined,
aria: Optional[bool] = Undefined,
autosize: Optional[SchemaBase | Map | AutosizeType_T] = Undefined,
axis: Optional[SchemaBase | Map] = Undefined,
axisBand: Optional[SchemaBase | Map] = Undefined,
axisBottom: Optional[SchemaBase | Map] = Undefined,
axisDiscrete: Optional[SchemaBase | Map] = Undefined,
axisLeft: Optional[SchemaBase | Map] = Undefined,
axisPoint: Optional[SchemaBase | Map] = Undefined,
axisQuantitative: Optional[SchemaBase | Map] = Undefined,
axisRight: Optional[SchemaBase | Map] = Undefined,
axisTemporal: Optional[SchemaBase | Map] = Undefined,
axisTop: Optional[SchemaBase | Map] = Undefined,
axisX: Optional[SchemaBase | Map] = Undefined,
axisXBand: Optional[SchemaBase | Map] = Undefined,
axisXDiscrete: Optional[SchemaBase | Map] = Undefined,
axisXPoint: Optional[SchemaBase | Map] = Undefined,
axisXQuantitative: Optional[SchemaBase | Map] = Undefined,
axisXTemporal: Optional[SchemaBase | Map] = Undefined,
axisY: Optional[SchemaBase | Map] = Undefined,
axisYBand: Optional[SchemaBase | Map] = Undefined,
axisYDiscrete: Optional[SchemaBase | Map] = Undefined,
axisYPoint: Optional[SchemaBase | Map] = Undefined,
axisYQuantitative: Optional[SchemaBase | Map] = Undefined,
axisYTemporal: Optional[SchemaBase | Map] = Undefined,
background: Optional[
str | Parameter | SchemaBase | Map | ColorName_T
] = Undefined,
bar: Optional[SchemaBase | Map] = Undefined,
boxplot: Optional[SchemaBase | Map] = Undefined,
circle: Optional[SchemaBase | Map] = Undefined,
concat: Optional[SchemaBase | Map] = Undefined,
countTitle: Optional[str] = Undefined,
customFormatTypes: Optional[bool] = Undefined,
errorband: Optional[SchemaBase | Map] = Undefined,
errorbar: Optional[SchemaBase | Map] = Undefined,
facet: Optional[SchemaBase | Map] = Undefined,
fieldTitle: Optional[Literal["verbal", "functional", "plain"]] = Undefined,
font: Optional[str] = Undefined,
geoshape: Optional[SchemaBase | Map] = Undefined,
header: Optional[SchemaBase | Map] = Undefined,
headerColumn: Optional[SchemaBase | Map] = Undefined,
headerFacet: Optional[SchemaBase | Map] = Undefined,
headerRow: Optional[SchemaBase | Map] = Undefined,
image: Optional[SchemaBase | Map] = Undefined,
legend: Optional[SchemaBase | Map] = Undefined,
line: Optional[SchemaBase | Map] = Undefined,
lineBreak: Optional[str | Parameter | SchemaBase | Map] = Undefined,
locale: Optional[SchemaBase | Map] = Undefined,
mark: Optional[SchemaBase | Map] = Undefined,
normalizedNumberFormat: Optional[str] = Undefined,
normalizedNumberFormatType: Optional[str] = Undefined,
numberFormat: Optional[str] = Undefined,
numberFormatType: Optional[str] = Undefined,
padding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
params: Optional[Sequence[SchemaBase | Map]] = Undefined,
point: Optional[SchemaBase | Map] = Undefined,
projection: Optional[SchemaBase | Map] = Undefined,
range: Optional[SchemaBase | Map] = Undefined,
rect: Optional[SchemaBase | Map] = Undefined,
rule: Optional[SchemaBase | Map] = Undefined,
scale: Optional[SchemaBase | Map] = Undefined,
selection: Optional[SchemaBase | Map] = Undefined,
square: Optional[SchemaBase | Map] = Undefined,
style: Optional[SchemaBase | Map] = Undefined,
text: Optional[SchemaBase | Map] = Undefined,
tick: Optional[SchemaBase | Map] = Undefined,
timeFormat: Optional[str] = Undefined,
timeFormatType: Optional[str] = Undefined,
title: Optional[SchemaBase | Map] = Undefined,
tooltipFormat: Optional[SchemaBase | Map] = Undefined,
trail: Optional[SchemaBase | Map] = Undefined,
view: Optional[SchemaBase | Map] = Undefined,
**kwds,
):
super().__init__(
arc=arc,
area=area,
aria=aria,
autosize=autosize,
axis=axis,
axisBand=axisBand,
axisBottom=axisBottom,
axisDiscrete=axisDiscrete,
axisLeft=axisLeft,
axisPoint=axisPoint,
axisQuantitative=axisQuantitative,
axisRight=axisRight,
axisTemporal=axisTemporal,
axisTop=axisTop,
axisX=axisX,
axisXBand=axisXBand,
axisXDiscrete=axisXDiscrete,
axisXPoint=axisXPoint,
axisXQuantitative=axisXQuantitative,
axisXTemporal=axisXTemporal,
axisY=axisY,
axisYBand=axisYBand,
axisYDiscrete=axisYDiscrete,
axisYPoint=axisYPoint,
axisYQuantitative=axisYQuantitative,
axisYTemporal=axisYTemporal,
background=background,
bar=bar,
boxplot=boxplot,
circle=circle,
concat=concat,
countTitle=countTitle,
customFormatTypes=customFormatTypes,
errorband=errorband,
errorbar=errorbar,
facet=facet,
fieldTitle=fieldTitle,
font=font,
geoshape=geoshape,
header=header,
headerColumn=headerColumn,
headerFacet=headerFacet,
headerRow=headerRow,
image=image,
legend=legend,
line=line,
lineBreak=lineBreak,
locale=locale,
mark=mark,
normalizedNumberFormat=normalizedNumberFormat,
normalizedNumberFormatType=normalizedNumberFormatType,
numberFormat=numberFormat,
numberFormatType=numberFormatType,
padding=padding,
params=params,
point=point,
projection=projection,
range=range,
rect=rect,
rule=rule,
scale=scale,
selection=selection,
square=square,
style=style,
text=text,
tick=tick,
timeFormat=timeFormat,
timeFormatType=timeFormatType,
title=title,
tooltipFormat=tooltipFormat,
trail=trail,
view=view,
**kwds,
)
| Config |
python | pyca__cryptography | tests/hazmat/primitives/test_x448.py | {
"start": 1319,
"end": 12531
} | class ____:
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "X448", "rfc7748.txt"),
load_nist_vectors,
),
)
def test_rfc7748(self, vector, backend):
private = binascii.unhexlify(vector["input_scalar"])
public = binascii.unhexlify(vector["input_u"])
shared_key = binascii.unhexlify(vector["output_u"])
private_key = X448PrivateKey.from_private_bytes(private)
public_key = X448PublicKey.from_public_bytes(public)
computed_shared_key = private_key.exchange(public_key)
assert computed_shared_key == shared_key
def test_rfc7748_1000_iteration(self, backend):
old_private = private = public = binascii.unhexlify(
b"05000000000000000000000000000000000000000000000000000000"
b"00000000000000000000000000000000000000000000000000000000"
)
shared_key = binascii.unhexlify(
b"aa3b4749d55b9daf1e5b00288826c467274ce3ebbdd5c17b975e09d4"
b"af6c67cf10d087202db88286e2b79fceea3ec353ef54faa26e219f38"
)
private_key = X448PrivateKey.from_private_bytes(private)
public_key = X448PublicKey.from_public_bytes(public)
for _ in range(1000):
computed_shared_key = private_key.exchange(public_key)
private_key = X448PrivateKey.from_private_bytes(
computed_shared_key
)
public_key = X448PublicKey.from_public_bytes(old_private)
old_private = computed_shared_key
assert computed_shared_key == shared_key
# These vectors are also from RFC 7748
# https://tools.ietf.org/html/rfc7748#section-6.2
@pytest.mark.parametrize(
("private_bytes", "public_bytes"),
[
(
binascii.unhexlify(
b"9a8f4925d1519f5775cf46b04b5800d4ee9ee8bae8bc5565d498c28d"
b"d9c9baf574a9419744897391006382a6f127ab1d9ac2d8c0a598726b"
),
binascii.unhexlify(
b"9b08f7cc31b7e3e67d22d5aea121074a273bd2b83de09c63faa73d2c"
b"22c5d9bbc836647241d953d40c5b12da88120d53177f80e532c41fa0"
),
),
(
binascii.unhexlify(
b"1c306a7ac2a0e2e0990b294470cba339e6453772b075811d8fad0d1d"
b"6927c120bb5ee8972b0d3e21374c9c921b09d1b0366f10b65173992d"
),
binascii.unhexlify(
b"3eb7a829b0cd20f5bcfc0b599b6feccf6da4627107bdb0d4f345b430"
b"27d8b972fc3e34fb4232a13ca706dcb57aec3dae07bdc1c67bf33609"
),
),
],
)
def test_pub_priv_bytes_raw(self, private_bytes, public_bytes, backend):
private_key = X448PrivateKey.from_private_bytes(private_bytes)
assert (
private_key.private_bytes(
serialization.Encoding.Raw,
serialization.PrivateFormat.Raw,
serialization.NoEncryption(),
)
== private_bytes
)
assert private_key.private_bytes_raw() == private_bytes
assert (
private_key.public_key().public_bytes(
serialization.Encoding.Raw, serialization.PublicFormat.Raw
)
== public_bytes
)
assert private_key.public_key().public_bytes_raw() == public_bytes
public_key = X448PublicKey.from_public_bytes(public_bytes)
assert (
public_key.public_bytes(
serialization.Encoding.Raw, serialization.PublicFormat.Raw
)
== public_bytes
)
assert public_key.public_bytes_raw() == public_bytes
@pytest.mark.parametrize(
("encoding", "fmt", "encryption", "passwd", "load_func"),
[
(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.BestAvailableEncryption(b"password"),
b"password",
serialization.load_pem_private_key,
),
(
serialization.Encoding.DER,
serialization.PrivateFormat.PKCS8,
serialization.BestAvailableEncryption(b"password"),
b"password",
serialization.load_der_private_key,
),
(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
None,
serialization.load_pem_private_key,
),
(
serialization.Encoding.DER,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
None,
serialization.load_der_private_key,
),
],
)
def test_round_trip_private_serialization(
self, encoding, fmt, encryption, passwd, load_func, backend
):
key = X448PrivateKey.generate()
serialized = key.private_bytes(encoding, fmt, encryption)
loaded_key = load_func(serialized, passwd, backend)
assert isinstance(loaded_key, X448PrivateKey)
def test_generate(self, backend):
key = X448PrivateKey.generate()
assert key
assert key.public_key()
def test_invalid_type_exchange(self, backend):
key = X448PrivateKey.generate()
with pytest.raises(TypeError):
key.exchange(object()) # type: ignore[arg-type]
def test_invalid_length_from_public_bytes(self, backend):
with pytest.raises(ValueError):
X448PublicKey.from_public_bytes(b"a" * 55)
with pytest.raises(ValueError):
X448PublicKey.from_public_bytes(b"a" * 57)
def test_invalid_length_from_private_bytes(self, backend):
with pytest.raises(ValueError):
X448PrivateKey.from_private_bytes(b"a" * 55)
with pytest.raises(ValueError):
X448PrivateKey.from_private_bytes(b"a" * 57)
def test_invalid_private_bytes(self, backend):
key = X448PrivateKey.generate()
with pytest.raises(TypeError):
key.private_bytes(
serialization.Encoding.Raw,
serialization.PrivateFormat.Raw,
None, # type: ignore[arg-type]
)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.Raw,
serialization.PrivateFormat.Raw,
DummyKeySerializationEncryption(),
)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.Raw,
serialization.PrivateFormat.PKCS8,
DummyKeySerializationEncryption(),
)
with pytest.raises(ValueError):
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.Raw,
serialization.NoEncryption(),
)
def test_invalid_public_bytes(self, backend):
key = X448PrivateKey.generate().public_key()
with pytest.raises(ValueError):
key.public_bytes(
serialization.Encoding.Raw,
serialization.PublicFormat.SubjectPublicKeyInfo,
)
with pytest.raises(ValueError):
key.public_bytes(
serialization.Encoding.PEM, serialization.PublicFormat.PKCS1
)
with pytest.raises(ValueError):
key.public_bytes(
serialization.Encoding.PEM, serialization.PublicFormat.Raw
)
def test_invalid_public_key_pem(self):
with pytest.raises(ValueError):
serialization.load_pem_public_key(
textwrap.dedent("""
-----BEGIN PUBLIC KEY-----
MCswBQYDK2VvAyIA////////////////////////////////////////////
-----END PUBLIC KEY-----""").encode()
)
def test_buffer_protocol(self, backend):
private_bytes = binascii.unhexlify(
b"9a8f4925d1519f5775cf46b04b5800d4ee9ee8bae8bc5565d498c28d"
b"d9c9baf574a9419744897391006382a6f127ab1d9ac2d8c0a598726b"
)
key = X448PrivateKey.from_private_bytes(bytearray(private_bytes))
assert (
key.private_bytes(
serialization.Encoding.Raw,
serialization.PrivateFormat.Raw,
serialization.NoEncryption(),
)
== private_bytes
)
@pytest.mark.supported(
only_if=lambda backend: backend.x448_supported(),
skip_message="Requires OpenSSL with X448 support",
)
def test_public_key_equality(backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "X448", "x448-pkcs8.der"),
lambda derfile: derfile.read(),
mode="rb",
)
key1 = serialization.load_der_private_key(key_bytes, None).public_key()
key2 = serialization.load_der_private_key(key_bytes, None).public_key()
key3 = X448PrivateKey.generate().public_key()
assert key1 == key2
assert key1 != key3
assert key1 != object()
with pytest.raises(TypeError):
key1 < key2 # type: ignore[operator]
@pytest.mark.supported(
only_if=lambda backend: backend.x448_supported(),
skip_message="Requires OpenSSL with X448 support",
)
def test_public_key_copy(backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "X448", "x448-pkcs8.der"),
lambda derfile: derfile.read(),
mode="rb",
)
key1 = serialization.load_der_private_key(key_bytes, None).public_key()
key2 = copy.copy(key1)
assert key1 == key2
@pytest.mark.supported(
only_if=lambda backend: backend.x448_supported(),
skip_message="Requires OpenSSL with X448 support",
)
def test_public_key_deepcopy(backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "X448", "x448-pkcs8.der"),
lambda derfile: derfile.read(),
mode="rb",
)
key1 = serialization.load_der_private_key(key_bytes, None).public_key()
key2 = copy.deepcopy(key1)
assert key1 == key2
@pytest.mark.supported(
only_if=lambda backend: backend.x448_supported(),
skip_message="Requires OpenSSL with X448 support",
)
def test_private_key_copy(backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "X448", "x448-pkcs8.der"),
lambda derfile: derfile.read(),
mode="rb",
)
key1 = serialization.load_der_private_key(key_bytes, None)
key2 = copy.copy(key1)
assert key1 == key2
@pytest.mark.supported(
only_if=lambda backend: backend.x448_supported(),
skip_message="Requires OpenSSL with X448 support",
)
def test_private_key_deepcopy(backend):
key_bytes = load_vectors_from_file(
os.path.join("asymmetric", "X448", "x448-pkcs8.der"),
lambda derfile: derfile.read(),
mode="rb",
)
key1 = serialization.load_der_private_key(key_bytes, None)
key2 = copy.deepcopy(key1)
assert key1 == key2
| TestX448Exchange |
python | python-pillow__Pillow | src/PIL/ImageFilter.py | {
"start": 7853,
"end": 8036
} | class ____(BuiltinFilter):
name = "Contour"
# fmt: off
filterargs = (3, 3), 1, 255, (
-1, -1, -1,
-1, 8, -1,
-1, -1, -1,
)
# fmt: on
| CONTOUR |
python | falconry__falcon | tests/test_httperror.py | {
"start": 36288,
"end": 36515
} | class ____(AsyncOnlyMediaHandler):
def serialize(self, media, content_type=None):
assert media == {'title': '410 Gone'}
return b'this is sync instead'
_serialize_sync = serialize
| SyncInterfaceMediaHandler |
python | chroma-core__chroma | chromadb/utils/embedding_functions/text2vec_embedding_function.py | {
"start": 213,
"end": 3081
} | class ____(EmbeddingFunction[Documents]):
"""
This class is used to generate embeddings for a list of texts using the Text2Vec model.
"""
def __init__(self, model_name: str = "shibing624/text2vec-base-chinese"):
"""
Initialize the Text2VecEmbeddingFunction.
Args:
model_name (str, optional): The name of the model to use for text embeddings.
Defaults to "shibing624/text2vec-base-chinese".
"""
try:
from text2vec import SentenceModel
except ImportError:
raise ValueError(
"The text2vec python package is not installed. Please install it with `pip install text2vec`"
)
self.model_name = model_name
self._model = SentenceModel(model_name_or_path=model_name)
def __call__(self, input: Documents) -> Embeddings:
"""
Generate embeddings for the given documents.
Args:
input: Documents or images to generate embeddings for.
Returns:
Embeddings for the documents.
"""
# Text2Vec only works with text documents
if not all(isinstance(item, str) for item in input):
raise ValueError("Text2Vec only supports text documents, not images")
embeddings = self._model.encode(list(input), convert_to_numpy=True)
# Convert to numpy arrays
return [np.array(embedding, dtype=np.float32) for embedding in embeddings]
@staticmethod
def name() -> str:
return "text2vec"
def default_space(self) -> Space:
return "cosine"
def supported_spaces(self) -> List[Space]:
return ["cosine", "l2", "ip"]
@staticmethod
def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]":
model_name = config.get("model_name")
if model_name is None:
assert False, "This code should not be reached"
return Text2VecEmbeddingFunction(model_name=model_name)
def get_config(self) -> Dict[str, Any]:
return {"model_name": self.model_name}
def validate_config_update(
self, old_config: Dict[str, Any], new_config: Dict[str, Any]
) -> None:
# model_name is also used as the identifier for model path if stored locally.
# Users should be able to change the path if needed, so we should not validate that.
# e.g. moving file path from /v1/my-model.bin to /v2/my-model.bin
return
@staticmethod
def validate_config(config: Dict[str, Any]) -> None:
"""
Validate the configuration using the JSON schema.
Args:
config: Configuration to validate
Raises:
ValidationError: If the configuration does not match the schema
"""
validate_config_schema(config, "text2vec")
| Text2VecEmbeddingFunction |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_ean.py | {
"start": 850,
"end": 1834
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.to_be_valid_ean"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.apply(lambda x: is_valid_ean(x))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
| ColumnValuesToBeValidEan |
python | doocs__leetcode | solution/1100-1199/1182.Shortest Distance to Target Color/Solution.py | {
"start": 0,
"end": 730
} | class ____:
def shortestDistanceColor(
self, colors: List[int], queries: List[List[int]]
) -> List[int]:
n = len(colors)
right = [[inf] * 3 for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for j in range(3):
right[i][j] = right[i + 1][j]
right[i][colors[i] - 1] = i
left = [[-inf] * 3 for _ in range(n + 1)]
for i, c in enumerate(colors, 1):
for j in range(3):
left[i][j] = left[i - 1][j]
left[i][c - 1] = i - 1
ans = []
for i, c in queries:
d = min(i - left[i + 1][c - 1], right[i][c - 1] - i)
ans.append(-1 if d > n else d)
return ans
| Solution |
python | Netflix__metaflow | metaflow/plugins/argo/argo_workflows.py | {
"start": 206295,
"end": 207046
} | class ____(object):
# https://argoproj.github.io/argo-workflows/fields/#parameter
def __init__(self, name):
tree = lambda: defaultdict(tree)
self.payload = tree()
self.payload["name"] = name
def value(self, value):
self.payload["value"] = value
return self
def default(self, value):
self.payload["default"] = value
return self
def valueFrom(self, value_from):
self.payload["valueFrom"] = value_from
return self
def description(self, description):
self.payload["description"] = description
return self
def to_json(self):
return self.payload
def __str__(self):
return json.dumps(self.payload, indent=4)
| Parameter |
python | dagster-io__dagster | python_modules/dagster/dagster/_daemon/sensor.py | {
"start": 4095,
"end": 27075
} | class ____(AbstractContextManager):
def __init__(
self,
remote_sensor: RemoteSensor,
tick: InstigatorTick,
instance: DagsterInstance,
logger: logging.Logger,
tick_retention_settings,
):
self._remote_sensor = remote_sensor
self._instance = instance
self._logger = logger
self._tick = tick
self._should_update_cursor_on_failure = False
self._purge_settings = defaultdict(set)
for status, day_offset in tick_retention_settings.items():
self._purge_settings[day_offset].add(status)
@property
def status(self) -> TickStatus:
return self._tick.status
@property
def logger(self) -> logging.Logger:
return self._logger
@property
def run_count(self) -> int:
return len(self._tick.run_ids)
@property
def tick_id(self) -> str:
return str(self._tick.tick_id)
@property
def tick(self) -> InstigatorTick:
return self._tick
@property
def log_key(self) -> Sequence[str]:
return [
self._remote_sensor.handle.repository_handle.repository_name,
self._remote_sensor.name,
self.tick_id,
]
def update_state(self, status: TickStatus, **kwargs: object):
if status in {TickStatus.SKIPPED, TickStatus.SUCCESS}:
kwargs["failure_count"] = 0
kwargs["consecutive_failure_count"] = 0
skip_reason = cast("Optional[str]", kwargs.get("skip_reason"))
cursor = cast("Optional[str]", kwargs.get("cursor"))
origin_run_id = cast("Optional[str]", kwargs.get("origin_run_id"))
user_interrupted = cast("Optional[bool]", kwargs.get("user_interrupted"))
kwargs.pop("skip_reason", None)
kwargs.pop("cursor", None)
kwargs.pop("origin_run_id", None)
kwargs.pop("user_interrupted", None)
if kwargs:
check.inst_param(status, "status", TickStatus)
if status:
self._tick = self._tick.with_status(status=status, **kwargs)
if skip_reason:
self._tick = self._tick.with_reason(skip_reason=skip_reason)
if cursor:
self._tick = self._tick.with_cursor(cursor)
if origin_run_id:
self._tick = self._tick.with_origin_run(origin_run_id)
if user_interrupted:
self._tick = self._tick.with_user_interrupted(user_interrupted)
def add_run_info(self, run_id: Optional[str] = None, run_key: Optional[str] = None) -> None:
self._tick = self._tick.with_run_info(run_id, run_key)
def add_log_key(self, log_key: Sequence[str]) -> None:
self._tick = self._tick.with_log_key(log_key)
def add_dynamic_partitions_request_result(
self, dynamic_partitions_request_result: DynamicPartitionsRequestResult
) -> None:
self._tick = self._tick.with_dynamic_partitions_request_result(
dynamic_partitions_request_result
)
def set_should_update_cursor_on_failure(self, should_update_cursor_on_failure: bool) -> None:
self._should_update_cursor_on_failure = should_update_cursor_on_failure
def set_run_requests(
self,
run_requests: Sequence[RunRequest],
reserved_run_ids: Sequence[Optional[str]],
cursor: Optional[str],
) -> None:
self._tick = self._tick.with_run_requests(
run_requests=run_requests,
reserved_run_ids=reserved_run_ids,
cursor=cursor,
)
self._write()
def sensor_is_enabled(self):
instigator_state = self._instance.get_instigator_state(
self._remote_sensor.get_remote_origin_id(), self._remote_sensor.selector_id
)
if instigator_state and not instigator_state.is_running:
return False
return True
def _write(self) -> None:
# do not write the cursor into the ticks table for custom user-code AutomationConditionSensorDefinitions
if self._remote_sensor.sensor_type == SensorType.AUTOMATION:
self._instance.update_tick(self._tick.with_cursor(None))
else:
self._instance.update_tick(self._tick)
if self._tick.status not in FINISHED_TICK_STATES:
return
should_update_cursor_and_last_run_key = (
self._tick.status != TickStatus.FAILURE
) or self._should_update_cursor_on_failure
# fetch the most recent state. we do this as opposed to during context initialization time
# because we want to minimize the window of clobbering the sensor state upon updating the
# sensor state data.
state = self._instance.get_instigator_state(
self._remote_sensor.get_remote_origin_id(), self._remote_sensor.selector_id
)
last_run_key = state.instigator_data.last_run_key if state.instigator_data else None # type: ignore # (possible none)
last_sensor_start_timestamp = (
state.instigator_data.last_sensor_start_timestamp if state.instigator_data else None # type: ignore # (possible none)
)
if self._tick.run_keys and should_update_cursor_and_last_run_key:
last_run_key = self._tick.run_keys[-1]
cursor = state.instigator_data.cursor if state.instigator_data else None # type: ignore # (possible none)
if should_update_cursor_and_last_run_key:
cursor = self._tick.cursor
marked_timestamp = max(
self._tick.timestamp,
state.instigator_data.last_tick_start_timestamp or 0, # type: ignore # (possible none)
)
self._instance.update_instigator_state(
state.with_data( # type: ignore # (possible none)
SensorInstigatorData(
last_tick_timestamp=self._tick.timestamp,
last_run_key=last_run_key,
min_interval=self._remote_sensor.min_interval_seconds,
cursor=cursor,
last_tick_start_timestamp=marked_timestamp,
last_sensor_start_timestamp=last_sensor_start_timestamp,
sensor_type=self._remote_sensor.sensor_type,
last_tick_success_timestamp=None
if self._tick.status == TickStatus.FAILURE
else get_current_datetime().timestamp(),
)
)
)
def __enter__(self) -> Self:
return self
def __exit__( # pyright: ignore[reportIncompatibleMethodOverride]
self,
exception_type: type[BaseException],
exception_value: Exception,
traceback: TracebackType,
) -> None:
if exception_type and isinstance(exception_value, KeyboardInterrupt):
return
# Log the error if the failure wasn't an interrupt or the daemon generator stopping
if exception_value and not isinstance(exception_value, GeneratorExit):
if isinstance(
exception_value, (DagsterUserCodeUnreachableError, DagsterCodeLocationLoadError)
):
try:
raise DagsterUserCodeUnreachableError(
f"Unable to reach the user code server for sensor {self._remote_sensor.name}."
" Sensor will resume execution once the server is available."
) from exception_value
except:
error_data = DaemonErrorCapture.process_exception(
sys.exc_info(),
logger=self.logger,
log_message="Sensor tick caught an error",
)
self.update_state(
TickStatus.FAILURE,
error=error_data,
# don't increment the failure count - retry until the server is available again
failure_count=self._tick.failure_count,
consecutive_failure_count=self._tick.consecutive_failure_count + 1,
)
else:
error_data = DaemonErrorCapture.process_exception(
sys.exc_info(),
logger=self.logger,
log_message="Sensor tick caught an error",
)
self.update_state(
TickStatus.FAILURE,
error=error_data,
failure_count=self._tick.failure_count + 1,
consecutive_failure_count=self._tick.consecutive_failure_count + 1,
)
self._write()
for day_offset, statuses in self._purge_settings.items():
if day_offset <= 0:
continue
self._instance.purge_ticks(
self._remote_sensor.get_remote_origin_id(),
selector_id=self._remote_sensor.selector_id,
before=(get_current_datetime() - datetime.timedelta(days=day_offset)).timestamp(),
tick_statuses=list(statuses),
)
def execute_sensor_iteration_loop(
workspace_process_context: IWorkspaceProcessContext,
logger: logging.Logger,
shutdown_event: threading.Event,
until: Optional[float] = None,
threadpool_executor: Optional[ThreadPoolExecutor] = None,
submit_threadpool_executor: Optional[ThreadPoolExecutor] = None,
instrument_elapsed: ElapsedInstrumentation = default_elapsed_instrumentation,
) -> "DaemonIterator":
"""Helper function that performs sensor evaluations on a tighter loop, while reusing grpc locations
within a given daemon interval. Rather than relying on the daemon machinery to run the
iteration loop every 30 seconds, sensors are continuously evaluated, every 5 seconds. We rely on
each sensor definition's min_interval to check that sensor evaluations are spaced appropriately.
"""
from dagster._daemon.daemon import SpanMarker
sensor_tick_futures: dict[str, Future] = {}
while True:
start_time = get_current_timestamp()
if until and start_time >= until:
# provide a way of organically ending the loop to support test environment
break
yield SpanMarker.START_SPAN
try:
yield from execute_sensor_iteration(
workspace_process_context,
logger,
threadpool_executor=threadpool_executor,
submit_threadpool_executor=submit_threadpool_executor,
sensor_tick_futures=sensor_tick_futures,
instrument_elapsed=instrument_elapsed,
)
except Exception:
error_info = DaemonErrorCapture.process_exception(
exc_info=sys.exc_info(),
logger=logger,
log_message="SensorDaemon caught an error",
)
yield error_info
# Yield to check for heartbeats in case there were no yields within
# execute_sensor_iteration
yield SpanMarker.END_SPAN
end_time = get_current_timestamp()
loop_duration = end_time - start_time
sleep_time = max(0, MIN_INTERVAL_LOOP_TIME - loop_duration)
shutdown_event.wait(sleep_time)
yield None
def execute_sensor_iteration(
workspace_process_context: IWorkspaceProcessContext,
logger: logging.Logger,
threadpool_executor: Optional[ThreadPoolExecutor],
submit_threadpool_executor: Optional[ThreadPoolExecutor],
sensor_tick_futures: Optional[dict[str, Future]] = None,
debug_crash_flags: Optional[DebugCrashFlags] = None,
instrument_elapsed: ElapsedInstrumentation = default_elapsed_instrumentation,
):
instance = workspace_process_context.instance
current_workspace = {
location_entry.origin.location_name: location_entry
for location_entry in workspace_process_context.create_request_context()
.get_code_location_entries()
.values()
}
all_sensor_states = {
sensor_state.selector_id: sensor_state
for sensor_state in instance.all_instigator_state(instigator_type=InstigatorType.SENSOR)
}
tick_retention_settings = instance.get_tick_retention_settings(InstigatorType.SENSOR)
sensors: dict[str, RemoteSensor] = {}
for location_entry in current_workspace.values():
code_location = location_entry.code_location
if code_location:
for repo in code_location.get_repositories().values():
for sensor in repo.get_sensors():
if sensor.sensor_type.is_handled_by_asset_daemon:
continue
selector_id = sensor.selector_id
if sensor.get_current_instigator_state(
all_sensor_states.get(selector_id)
).is_running:
sensors[selector_id] = sensor
if not sensors:
yield
return
for sensor in sensors.values():
sensor_name = sensor.name
sensor_debug_crash_flags = debug_crash_flags.get(sensor_name) if debug_crash_flags else None
sensor_state = all_sensor_states.get(sensor.selector_id)
if not sensor_state:
assert sensor.default_status == DefaultSensorStatus.RUNNING
sensor_state = InstigatorState(
sensor.get_remote_origin(),
InstigatorType.SENSOR,
InstigatorStatus.DECLARED_IN_CODE,
SensorInstigatorData(
min_interval=sensor.min_interval_seconds,
last_sensor_start_timestamp=get_current_timestamp(),
sensor_type=sensor.sensor_type,
),
)
instance.add_instigator_state(sensor_state)
elif is_under_min_interval(sensor_state, sensor):
continue
elapsed = get_elapsed(sensor_state)
instrument_elapsed(sensor, elapsed, sensor.min_interval_seconds)
if threadpool_executor:
if sensor_tick_futures is None:
check.failed("sensor_tick_futures dict must be passed with threadpool_executor")
# only allow one tick per sensor to be in flight
if (
sensor.selector_id in sensor_tick_futures
and not sensor_tick_futures[sensor.selector_id].done()
):
continue
future = threadpool_executor.submit(
_process_tick,
workspace_process_context,
logger,
sensor,
sensor_state,
sensor_debug_crash_flags,
tick_retention_settings,
submit_threadpool_executor,
)
sensor_tick_futures[sensor.selector_id] = future
yield
else:
# evaluate the sensors in a loop, synchronously, yielding to allow the sensor daemon to
# heartbeat
yield from _process_tick_generator(
workspace_process_context,
logger,
sensor,
sensor_state,
sensor_debug_crash_flags,
tick_retention_settings,
submit_threadpool_executor=None,
)
def _get_evaluation_tick(
instance: DagsterInstance,
sensor: RemoteSensor,
instigator_data: Optional[SensorInstigatorData],
evaluation_timestamp: float,
logger: logging.Logger,
) -> InstigatorTick:
"""Returns the current tick that the sensor should evaluate for. If there is unfinished work
from the previous tick that must be resolved before proceeding, will return that previous tick.
"""
origin_id = sensor.get_remote_origin_id()
selector_id = sensor.get_remote_origin().get_selector().get_id()
consecutive_failure_count = 0
if instigator_data and instigator_data.last_tick_success_timestamp:
# if a last tick success timestamp was set, then the previous tick could not have been
# interrupted, so there is no need to fetch the previous tick
most_recent_tick = None
else:
most_recent_tick = next(iter(instance.get_ticks(origin_id, selector_id, limit=1)), None)
# check for unfinished work on the previous tick
if most_recent_tick is not None:
if most_recent_tick.status in {TickStatus.FAILURE, TickStatus.STARTED}:
consecutive_failure_count = (
most_recent_tick.consecutive_failure_count or most_recent_tick.failure_count
)
has_unrequested_runs = len(most_recent_tick.unsubmitted_run_ids_with_requests) > 0
if most_recent_tick.status == TickStatus.STARTED:
# if the previous tick was interrupted before it was able to request all of its runs,
# and it hasn't been too long, then resume execution of that tick
if (
evaluation_timestamp - most_recent_tick.timestamp <= MAX_TIME_TO_RESUME_TICK_SECONDS
and has_unrequested_runs
):
logger.warn(
f"Tick {most_recent_tick.tick_id} was interrupted part-way through, resuming"
)
return most_recent_tick
else:
# previous tick won't be resumed - move it into a SKIPPED state so it isn't left
# dangling in STARTED, but don't return it
logger.warn(f"Moving dangling STARTED tick {most_recent_tick.tick_id} into SKIPPED")
most_recent_tick = most_recent_tick.with_status(status=TickStatus.SKIPPED)
instance.update_tick(most_recent_tick)
elif (
most_recent_tick.status == TickStatus.FAILURE
and most_recent_tick.tick_data.failure_count <= MAX_FAILURE_RESUBMISSION_RETRIES
and has_unrequested_runs
):
logger.info(f"Retrying failed tick {most_recent_tick.tick_id}")
return instance.create_tick(
most_recent_tick.tick_data.with_status(
TickStatus.STARTED,
error=None,
timestamp=evaluation_timestamp,
end_timestamp=None,
),
)
# typical case, create a fresh tick
return instance.create_tick(
TickData(
instigator_origin_id=origin_id,
instigator_name=sensor.name,
instigator_type=InstigatorType.SENSOR,
status=TickStatus.STARTED,
timestamp=evaluation_timestamp,
selector_id=selector_id,
consecutive_failure_count=consecutive_failure_count,
)
)
def _process_tick_generator(
workspace_process_context: IWorkspaceProcessContext,
logger: logging.Logger,
remote_sensor: RemoteSensor,
sensor_state: InstigatorState,
sensor_debug_crash_flags: Optional[SingleInstigatorDebugCrashFlags],
tick_retention_settings,
submit_threadpool_executor: Optional[ThreadPoolExecutor],
):
instance = workspace_process_context.instance
error_info = None
now = get_current_datetime()
sensor_state = check.not_none(
instance.get_instigator_state(
remote_sensor.get_remote_origin_id(), remote_sensor.selector_id
)
)
if is_under_min_interval(sensor_state, remote_sensor):
# check the since we might have been queued before processing
return
else:
mark_sensor_state_for_tick(instance, remote_sensor, sensor_state, now)
try:
# get the tick that we should be evaluating for
tick = _get_evaluation_tick(
instance,
remote_sensor,
_sensor_instigator_data(sensor_state),
now.timestamp(),
logger,
)
check_for_debug_crash(sensor_debug_crash_flags, "TICK_CREATED")
with SensorLaunchContext(
remote_sensor,
tick,
instance,
logger,
tick_retention_settings,
) as tick_context:
check_for_debug_crash(sensor_debug_crash_flags, "TICK_HELD")
tick_context.add_log_key(tick_context.log_key)
with partition_loading_context(dynamic_partitions_store=instance):
# in cases where there is unresolved work left to do, do it
if len(tick.unsubmitted_run_ids_with_requests) > 0:
yield from _resume_tick(
workspace_process_context,
tick_context,
tick,
remote_sensor,
submit_threadpool_executor,
sensor_debug_crash_flags,
)
else:
yield from _evaluate_sensor(
workspace_process_context,
tick_context,
remote_sensor,
sensor_state,
submit_threadpool_executor,
sensor_debug_crash_flags,
)
except Exception:
error_info = DaemonErrorCapture.process_exception(
exc_info=sys.exc_info(),
logger=logger,
log_message=f"Sensor daemon caught an error for sensor {remote_sensor.name}",
)
yield error_info
# evaluate the tick immediately, but from within a thread. The main thread should be able to
# heartbeat to keep the daemon alive
_process_tick = return_as_list(_process_tick_generator)
def _sensor_instigator_data(state: InstigatorState) -> Optional[SensorInstigatorData]:
instigator_data = state.instigator_data
if instigator_data is None or isinstance(instigator_data, SensorInstigatorData):
return instigator_data
else:
check.failed(f"Expected SensorInstigatorData, got {instigator_data}")
def mark_sensor_state_for_tick(
instance: DagsterInstance,
remote_sensor: RemoteSensor,
sensor_state: InstigatorState,
now: datetime.datetime,
) -> None:
instigator_data = _sensor_instigator_data(sensor_state)
instance.update_instigator_state(
sensor_state.with_data(
SensorInstigatorData(
last_tick_timestamp=(
instigator_data.last_tick_timestamp if instigator_data else None
),
last_run_key=instigator_data.last_run_key if instigator_data else None,
min_interval=remote_sensor.min_interval_seconds,
cursor=instigator_data.cursor if instigator_data else None,
last_tick_start_timestamp=now.timestamp(),
sensor_type=remote_sensor.sensor_type,
last_sensor_start_timestamp=instigator_data.last_sensor_start_timestamp
if instigator_data
else None,
last_tick_success_timestamp=None,
)
)
)
| SensorLaunchContext |
python | huggingface__transformers | src/transformers/models/align/modeling_align.py | {
"start": 41172,
"end": 48812
} | class ____(AlignPreTrainedModel):
config: AlignConfig
def __init__(self, config: AlignConfig):
super().__init__(config)
if not isinstance(config.text_config, AlignTextConfig):
raise TypeError(
"config.text_config is expected to be of type AlignTextConfig but is of type"
f" {type(config.text_config)}."
)
if not isinstance(config.vision_config, AlignVisionConfig):
raise TypeError(
"config.vision_config is expected to be of type AlignVisionConfig but is of type"
f" {type(config.vision_config)}."
)
text_config = config.text_config
vision_config = config.vision_config
self.projection_dim = config.projection_dim
self.text_embed_dim = text_config.hidden_size
self.text_model = AlignTextModel(text_config)
self.vision_model = AlignVisionModel(vision_config)
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim)
self.temperature = nn.Parameter(torch.tensor(self.config.temperature_init_value))
# Initialize weights and apply final processing
self.post_init()
@filter_out_non_signature_kwargs()
@auto_docstring
def get_text_features(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
) -> torch.FloatTensor:
r"""
Returns:
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
applying the projection layer to the pooled output of [`AlignTextModel`].
Examples:
```python
>>> import torch
>>> from transformers import AutoTokenizer, AlignModel
>>> model = AlignModel.from_pretrained("kakaobrain/align-base")
>>> tokenizer = AutoTokenizer.from_pretrained("kakaobrain/align-base")
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> with torch.inference_mode():
... text_features = model.get_text_features(**inputs)
```"""
text_outputs = self.text_model(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
)
last_hidden_state = text_outputs[0][:, 0, :]
text_features = self.text_projection(last_hidden_state)
return text_features
@filter_out_non_signature_kwargs()
@auto_docstring
def get_image_features(self, pixel_values: torch.FloatTensor) -> torch.FloatTensor:
r"""
Returns:
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
applying the projection layer to the pooled output of [`AlignVisionModel`].
Examples:
```python
>>> import torch
>>> from transformers import AutoProcessor, AlignModel
>>> from transformers.image_utils import load_image
>>> model = AlignModel.from_pretrained("kakaobrain/align-base")
>>> processor = AutoProcessor.from_pretrained("kakaobrain/align-base")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = load_image(url)
>>> inputs = processor(images=image, return_tensors="pt")
>>> with torch.inference_mode():
... image_features = model.get_image_features(**inputs)
```"""
vision_outputs = self.vision_model(pixel_values=pixel_values)
image_features = vision_outputs.pooler_output
return image_features
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
return_loss: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, AlignOutput]:
r"""
return_loss (`bool`, *optional*):
Whether or not to return the contrastive loss.
Examples:
```python
>>> import torch
>>> from transformers import AutoProcessor, AlignModel
>>> from transformers.image_utils import load_image
>>> model = AlignModel.from_pretrained("kakaobrain/align-base")
>>> processor = AutoProcessor.from_pretrained("kakaobrain/align-base")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = load_image(url)
>>> inputs = processor(
... images=image, text=["a photo of a cat", "a photo of a dog"], return_tensors="pt", padding=True
... )
>>> with torch.inference_mode():
... outputs = model(**inputs)
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
```"""
# Use ALIGN model's config for some fields (if specified) instead of those of vision & text components.
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vision_outputs = self.vision_model(
pixel_values=pixel_values,
output_hidden_states=output_hidden_states,
return_dict=True,
)
text_outputs = self.text_model(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=True,
)
image_embeds = vision_outputs[1]
text_embeds = text_outputs[0][:, 0, :]
text_embeds = self.text_projection(text_embeds)
# normalized features
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
# cosine similarity as logits
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) / self.temperature
logits_per_image = logits_per_text.t()
loss = None
if return_loss:
loss = align_loss(logits_per_text)
return AlignOutput(
loss=loss,
logits_per_image=logits_per_image,
logits_per_text=logits_per_text,
text_embeds=text_embeds,
image_embeds=image_embeds,
text_model_output=text_outputs,
vision_model_output=vision_outputs,
)
__all__ = ["AlignPreTrainedModel", "AlignTextModel", "AlignVisionModel", "AlignModel"]
| AlignModel |
python | pyca__cryptography | tests/hazmat/primitives/test_pkcs12.py | {
"start": 10948,
"end": 27466
} | class ____:
@pytest.mark.parametrize(
(
"kgenerator",
"ktype",
"kparam",
),
[
pytest.param(
ed448.Ed448PrivateKey.generate,
ed448.Ed448PrivateKey,
[],
marks=pytest.mark.supported(
only_if=lambda backend: backend.ed448_supported(),
skip_message="Requires OpenSSL with Ed448 support",
),
),
pytest.param(
ed25519.Ed25519PrivateKey.generate,
ed25519.Ed25519PrivateKey,
[],
marks=pytest.mark.supported(
only_if=lambda backend: backend.ed25519_supported(),
skip_message="Requires OpenSSL with Ed25519 support",
),
),
(rsa.generate_private_key, rsa.RSAPrivateKey, [65537, 1024]),
(dsa.generate_private_key, dsa.DSAPrivateKey, [1024]),
]
+ [
pytest.param(
ec.generate_private_key, ec.EllipticCurvePrivateKey, [curve]
)
for curve in ec._CURVE_TYPES.values()
],
)
@pytest.mark.parametrize("name", [None, b"name"])
@pytest.mark.parametrize(
("algorithm", "password"),
[
(serialization.BestAvailableEncryption(b"password"), b"password"),
(serialization.NoEncryption(), None),
],
)
def test_generate_each_supported_keytype(
self, backend, kgenerator, ktype, kparam, name, algorithm, password
):
if ktype == ec.EllipticCurvePrivateKey:
_skip_curve_unsupported(backend, *kparam)
key = kgenerator(*kparam)
assert isinstance(key, ktype)
cacert, cakey = _load_ca(backend)
now = datetime.now(timezone.utc).replace(tzinfo=None)
cert = (
x509.CertificateBuilder()
.subject_name(cacert.subject)
.issuer_name(cacert.subject)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now)
.not_valid_after(now)
.sign(cakey, hashes.SHA256())
)
assert isinstance(cert, x509.Certificate)
p12 = serialize_key_and_certificates(
name, key, cert, [cacert], algorithm
)
parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates(
p12, password, backend
)
assert parsed_cert == cert
assert isinstance(parsed_key, ktype)
assert parsed_key.public_key().public_bytes(
Encoding.PEM, PublicFormat.SubjectPublicKeyInfo
) == key.public_key().public_bytes(
Encoding.PEM, PublicFormat.SubjectPublicKeyInfo
)
assert parsed_more_certs == [cacert]
def test_generate_with_cert_key_ca(self, backend):
cert, key = _load_ca(backend)
cert2 = _load_cert(
backend, os.path.join("x509", "custom", "dsa_selfsigned_ca.pem")
)
cert3 = _load_cert(backend, os.path.join("x509", "letsencryptx3.pem"))
encryption = serialization.NoEncryption()
p12 = serialize_key_and_certificates(
None, key, cert, [cert2, cert3], encryption
)
parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates(
p12, None, backend
)
assert parsed_cert == cert
assert isinstance(parsed_key, ec.EllipticCurvePrivateKey)
assert parsed_key.private_numbers() == key.private_numbers()
assert parsed_more_certs == [cert2, cert3]
def test_generate_cas_friendly_names(self, backend):
cert, key = _load_ca(backend)
cert2 = _load_cert(
backend, os.path.join("x509", "custom", "dsa_selfsigned_ca.pem")
)
cert3 = _load_cert(backend, os.path.join("x509", "letsencryptx3.pem"))
encryption = serialization.NoEncryption()
p12 = serialize_key_and_certificates(
b"test",
key,
cert,
[
PKCS12Certificate(cert2, b"cert2"),
PKCS12Certificate(cert3, None),
],
encryption,
)
p12_cert = load_pkcs12(p12, None, backend)
cas = p12_cert.additional_certs
assert cas[0].certificate == cert2
assert cas[0].friendly_name == b"cert2"
assert cas[1].certificate == cert3
assert cas[1].friendly_name is None
@pytest.mark.parametrize(
("encryption_algorithm", "password"),
[
(serialization.BestAvailableEncryption(b"password"), b"password"),
(
serialization.PrivateFormat.PKCS12.encryption_builder().build(
b"not a password"
),
b"not a password",
),
(serialization.NoEncryption(), None),
],
)
def test_generate_cas_friendly_names_no_key(
self, backend, encryption_algorithm, password
):
cert2 = _load_cert(
backend, os.path.join("x509", "custom", "dsa_selfsigned_ca.pem")
)
cert3 = _load_cert(backend, os.path.join("x509", "letsencryptx3.pem"))
p12 = serialize_key_and_certificates(
None,
None,
None,
[
PKCS12Certificate(cert2, b"cert2"),
PKCS12Certificate(cert3, None),
],
encryption_algorithm,
)
p12_cert = load_pkcs12(p12, password, backend)
cas = p12_cert.additional_certs
assert cas[0].certificate == cert2
assert cas[0].friendly_name == b"cert2"
assert cas[1].certificate == cert3
assert cas[1].friendly_name is None
def test_generate_wrong_types(self, backend):
cert, key = _load_ca(backend)
cert2 = _load_cert(backend, os.path.join("x509", "letsencryptx3.pem"))
encryption = serialization.NoEncryption()
with pytest.raises(TypeError) as exc:
serialize_key_and_certificates(
b"name", cert, cert, None, encryption
)
assert str(exc.value) == (
"Key must be RSA, DSA, EllipticCurve, ED25519, or ED448"
" private key, or None."
)
with pytest.raises(TypeError) as exc:
serialize_key_and_certificates(b"name", key, key, None, encryption)
assert "object cannot be cast as" in str(
exc.value
) and "Certificate" in str(exc.value)
with pytest.raises(TypeError) as exc:
serialize_key_and_certificates(b"name", key, cert, None, key)
assert str(exc.value) == (
"Key encryption algorithm must be a "
"KeySerializationEncryption instance"
)
with pytest.raises(TypeError) as exc:
serialize_key_and_certificates(None, key, cert, cert2, encryption)
with pytest.raises(TypeError) as exc:
serialize_key_and_certificates(None, key, cert, [key], encryption)
assert "failed to extract enum CertificateOrPKCS12Certificate" in str(
exc.value
)
@pytest.mark.parametrize(
("encryption_algorithm", "password"),
[
(serialization.BestAvailableEncryption(b"password"), b"password"),
(
serialization.PrivateFormat.PKCS12.encryption_builder().build(
b"not a password"
),
b"not a password",
),
(serialization.NoEncryption(), None),
],
)
def test_generate_no_cert(self, backend, encryption_algorithm, password):
_, key = _load_ca(backend)
p12 = serialize_key_and_certificates(
None, key, None, None, encryption_algorithm
)
parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates(
p12, password, backend
)
assert parsed_cert is None
assert isinstance(parsed_key, ec.EllipticCurvePrivateKey)
assert parsed_key.private_numbers() == key.private_numbers()
assert parsed_more_certs == []
@pytest.mark.parametrize(
("encryption_algorithm", "password"),
[
(serialization.BestAvailableEncryption(b"password"), b"password"),
(serialization.NoEncryption(), None),
],
)
def test_generate_cas_only(self, encryption_algorithm, password, backend):
cert, _ = _load_ca(backend)
p12 = serialize_key_and_certificates(
None, None, None, [cert], encryption_algorithm
)
parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates(
p12, password, backend
)
assert parsed_cert is None
assert parsed_key is None
assert parsed_more_certs == [cert]
@pytest.mark.parametrize(
("encryption_algorithm", "password"),
[
(serialization.BestAvailableEncryption(b"password"), b"password"),
(serialization.NoEncryption(), None),
],
)
def test_generate_cert_only(self, encryption_algorithm, password, backend):
# This test is a bit weird, but when passing *just* a cert
# with no corresponding key it will be encoded in the cas
# list. We have external consumers relying on this behavior
# (and the underlying structure makes no real distinction
# anyway) so this test ensures we don't break them.
cert, _ = _load_ca(backend)
p12 = serialize_key_and_certificates(
None, None, cert, [], encryption_algorithm
)
parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates(
p12, password, backend
)
assert parsed_cert is None
assert parsed_key is None
assert parsed_more_certs == [cert]
def test_generate_cert_only_none_cas(self, backend):
# Same as test_generate_cert_only, but passing None instead of an
# empty list for cas.
cert, _ = _load_ca(backend)
p12 = serialize_key_and_certificates(
None, None, cert, None, serialization.NoEncryption()
)
parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates(
p12, None
)
assert parsed_cert is None
assert parsed_key is None
assert parsed_more_certs == [cert]
def test_invalid_utf8_friendly_name(self, backend):
cert, _ = _load_ca(backend)
with pytest.raises(ValueError):
serialize_key_and_certificates(
b"\xc9", None, cert, None, serialization.NoEncryption()
)
def test_must_supply_something(self):
with pytest.raises(ValueError) as exc:
serialize_key_and_certificates(
None, None, None, None, serialization.NoEncryption()
)
assert str(exc.value) == (
"You must supply at least one of key, cert, or cas"
)
def test_generate_unsupported_encryption_type(self, backend):
cert, key = _load_ca(backend)
with pytest.raises(ValueError) as exc:
serialize_key_and_certificates(
None,
key,
cert,
None,
DummyKeySerializationEncryption(),
)
assert str(exc.value) == "Unsupported key encryption type"
@pytest.mark.parametrize(
("enc_alg", "enc_alg_der"),
[
(
PBES.PBESv2SHA256AndAES256CBC,
[
b"\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x05\x0d", # PBESv2
b"\x06\x09\x60\x86\x48\x01\x65\x03\x04\x01\x2a", # AES
],
),
(
PBES.PBESv1SHA1And3KeyTripleDESCBC,
[b"\x06\x0a\x2a\x86\x48\x86\xf7\x0d\x01\x0c\x01\x03"],
),
(
None,
[],
),
],
)
@pytest.mark.parametrize(
("mac_alg", "mac_alg_der"),
[
(hashes.SHA1(), b"\x06\x05\x2b\x0e\x03\x02\x1a"),
(hashes.SHA256(), b"\x06\t`\x86H\x01e\x03\x04\x02\x01"),
(None, None),
],
)
@pytest.mark.parametrize(
("iters", "iter_der"),
[
(420, b"\x02\x02\x01\xa4"),
(22222, b"\x02\x02\x56\xce"),
(None, None),
],
)
def test_key_serialization_encryption(
self,
backend,
enc_alg,
enc_alg_der,
mac_alg,
mac_alg_der,
iters,
iter_der,
):
builder = serialization.PrivateFormat.PKCS12.encryption_builder()
if enc_alg is not None:
builder = builder.key_cert_algorithm(enc_alg)
if mac_alg is not None:
builder = builder.hmac_hash(mac_alg)
if iters is not None:
builder = builder.kdf_rounds(iters)
encryption = builder.build(b"password")
key = ec.generate_private_key(ec.SECP256R1())
cacert, cakey = _load_ca(backend)
now = datetime.now(timezone.utc).replace(tzinfo=None)
cert = (
x509.CertificateBuilder()
.subject_name(cacert.subject)
.issuer_name(cacert.subject)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now)
.not_valid_after(now)
.sign(cakey, hashes.SHA256())
)
assert isinstance(cert, x509.Certificate)
p12 = serialize_key_and_certificates(
b"name", key, cert, [cacert], encryption
)
# We want to know if we've serialized something that has the parameters
# we expect, so we match on specific byte strings of OIDs & DER values.
for der in enc_alg_der:
assert der in p12
if mac_alg_der is not None:
assert mac_alg_der in p12
if iter_der is not None:
assert iter_der in p12
parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates(
p12, b"password", backend
)
assert parsed_cert == cert
assert isinstance(parsed_key, ec.EllipticCurvePrivateKey)
assert parsed_key.public_key().public_bytes(
Encoding.PEM, PublicFormat.SubjectPublicKeyInfo
) == key.public_key().public_bytes(
Encoding.PEM, PublicFormat.SubjectPublicKeyInfo
)
assert parsed_more_certs == [cacert]
def test_set_mac_key_certificate_mismatch(self, backend):
cacert, _ = _load_ca(backend)
key = ec.generate_private_key(ec.SECP256R1())
encryption = (
serialization.PrivateFormat.PKCS12.encryption_builder()
.hmac_hash(hashes.SHA256())
.build(b"password")
)
with pytest.raises(ValueError):
serialize_key_and_certificates(
b"name", key, cacert, [], encryption
)
@pytest.mark.parametrize(
"encryption_algorithm",
[
serialization.NoEncryption(),
serialization.BestAvailableEncryption(b"password"),
],
)
def test_generate_localkeyid(self, backend, encryption_algorithm):
cert, key = _load_ca(backend)
p12 = serialize_key_and_certificates(
None, key, cert, None, encryption_algorithm
)
# Dirty, but does the trick. Should be there:
# * 2x if unencrypted (once for the key and once for the cert)
# * 1x if encrypted (the cert one is encrypted, but the key one is
# plaintext)
count = (
2
if isinstance(encryption_algorithm, serialization.NoEncryption)
else 1
)
assert p12.count(cert.fingerprint(hashes.SHA1())) == count
def test_invalid_utf8_password_pbes1(self, backend):
cert, key = _load_ca(backend)
encryption_algorithm = (
PrivateFormat.PKCS12.encryption_builder()
.key_cert_algorithm(PBES.PBESv1SHA1And3KeyTripleDESCBC)
.build(b"\xff")
)
with pytest.raises(ValueError):
serialize_key_and_certificates(
None, key, cert, None, encryption_algorithm
)
@pytest.mark.skip_fips(
reason="PKCS12 unsupported in FIPS mode. So much bad crypto in it."
)
| TestPKCS12Creation |
python | huggingface__transformers | tests/models/mbart/test_tokenization_mbart.py | {
"start": 1181,
"end": 2974
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "facebook/mbart-large-en-ro"
tokenizer_class = MBartTokenizer
integration_expected_tokens = ['▁This', '▁is', '▁a', '▁test', '▁', '😊', '▁I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fals', 'é', '.', '▁', '生活的', '真', '谛', '是', '▁Hi', '▁Hello', '▁Hi', '▁Hello', '▁Hello', '<s>', '▁hi', '<s>', '▁there', '▁The', '▁following', '▁string', '▁should', '▁be', '▁properly', '▁en', 'code', 'd', ':', '▁Hello', '.', '▁But', '▁ir', 'd', '▁and', '▁ปี', '▁ir', 'd', '▁ด', '▁Hey', '▁how', '▁are', '▁you', '▁doing'] # fmt: skip
integration_expected_token_ids = [3293, 83, 10, 3034, 6, 82803, 87, 509, 103122, 23, 483, 13821, 4, 136, 903, 83, 84047, 446, 5, 6, 62668, 5364, 245875, 354, 2673, 35378, 2673, 35378, 35378, 0, 1274, 0, 2685, 581, 25632, 79315, 5608, 186, 155965, 22, 40899, 71, 12, 35378, 5, 4966, 193, 71, 136, 10249, 193, 71, 48229, 28240, 3642, 621, 398, 20594] # fmt: skip
expected_tokens_from_ids = ['▁This', '▁is', '▁a', '▁test', '▁', '😊', '▁I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fals', 'é', '.', '▁', '生活的', '真', '谛', '是', '▁Hi', '▁Hello', '▁Hi', '▁Hello', '▁Hello', '<s>', '▁hi', '<s>', '▁there', '▁The', '▁following', '▁string', '▁should', '▁be', '▁properly', '▁en', 'code', 'd', ':', '▁Hello', '.', '▁But', '▁ir', 'd', '▁and', '▁ปี', '▁ir', 'd', '▁ด', '▁Hey', '▁how', '▁are', '▁you', '▁doing'] # fmt: skip
integration_expected_decoded_text = "This is a test 😊 I was born in 92000, and this is falsé. 生活的真谛是 Hi Hello Hi Hello Hello<s> hi<s> there The following string should be properly encoded: Hello. But ird and ปี ird ด Hey how are you doing"
@require_torch
@require_sentencepiece
@require_tokenizers
| MBartTokenizationTest |
python | ray-project__ray | rllib/core/rl_module/torch/torch_compile_config.py | {
"start": 65,
"end": 1601
} | class ____:
"""Configuration options for RLlib's usage of torch.compile in RLModules.
# On `torch.compile` in Torch RLModules
`torch.compile` invokes torch's dynamo JIT compiler that can potentially bring
speedups to RL Module's forward methods.
This is a performance optimization that should be disabled for debugging.
General usage:
- Usually, you only want to `RLModule._forward_train` to be compiled on
instances of RLModule used for learning. (e.g. the learner)
- In some cases, it can bring speedups to also compile
`RLModule._forward_exploration` on instances used for exploration. (e.g.
RolloutWorker)
- In some cases, it can bring speedups to also compile
`RLModule._forward_inference` on instances used for inference. (e.g.
RolloutWorker)
Note that different backends are available on different platforms.
Also note that the default backend for torch dynamo is "aot_eager" on macOS.
This is a debugging backend that is expected not to improve performance because
the inductor backend is not supported on OSX so far.
Args:
torch_dynamo_backend: The torch.dynamo backend to use.
torch_dynamo_mode: The torch.dynamo mode to use.
kwargs: Additional keyword arguments to pass to `torch.compile()`
"""
torch_dynamo_backend: str = (
"aot_eager" if sys.platform == "darwin" else "cudagraphs"
)
torch_dynamo_mode: str = None
kwargs: dict = field(default_factory=lambda: dict())
| TorchCompileConfig |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 135985,
"end": 137258
} | class ____(Request):
"""
Convert public projects to private
:param ids: Ids of the projects to convert. Only the projects originated by the
company can be converted
:type ids: Sequence[str]
"""
_service = "projects"
_action = "make_private"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"ids": {
"description": "Ids of the projects to convert. Only the projects originated by the company can be converted",
"items": {"type": "string"},
"type": ["array", "null"],
}
},
"type": "object",
}
def __init__(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None:
super(MakePrivateRequest, self).__init__(**kwargs)
self.ids = ids
@schema_property("ids")
def ids(self) -> Optional[List[str]]:
return self._property_ids
@ids.setter
def ids(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_ids = None
return
self.assert_isinstance(value, "ids", (list, tuple))
self.assert_isinstance(value, "ids", six.string_types, is_array=True)
self._property_ids = value
| MakePrivateRequest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/source_salesforce/streams.py | {
"start": 38475,
"end": 42375
} | class ____(RestSalesforceStream, CheckpointMixin, ABC):
state_checkpoint_interval = 500
_slice = None
def __init__(self, replication_key: str, stream_slice_step: str = "P30D", **kwargs):
self.replication_key = replication_key
super().__init__(**kwargs)
self._stream_slice_step = stream_slice_step
self._stream_slicer_cursor = None
self._state = {}
def set_cursor(self, cursor: ConcurrentCursor) -> None:
self._stream_slicer_cursor = cursor
def stream_slices(
self, *, sync_mode: SyncMode, cursor_field: List[str] = None, stream_state: Mapping[str, Any] = None
) -> Iterable[Optional[Mapping[str, Any]]]:
if not self._stream_slicer_cursor:
raise ValueError("Cursor should be set at this point")
for stream_slice in self._stream_slicer_cursor.stream_slices():
yield StreamSlice(
partition={},
cursor_slice={
"start_date": stream_slice["start_date"].replace("Z", "+00:00"),
"end_date": stream_slice["end_date"].replace("Z", "+00:00"),
},
)
@property
def stream_slice_step(self) -> pendulum.Duration:
return pendulum.parse(self._stream_slice_step)
def request_params(
self,
stream_state: Mapping[str, Any],
stream_slice: Mapping[str, Any] = None,
next_page_token: Mapping[str, Any] = None,
property_chunk: Mapping[str, Any] = None,
) -> MutableMapping[str, Any]:
if next_page_token:
"""
If `next_page_token` is set, subsequent requests use `nextRecordsUrl`, and do not include any parameters.
"""
return {}
property_chunk = property_chunk or {}
start_date = max(
(stream_state or {}).get(self.cursor_field, self.start_date),
(stream_slice or {}).get("start_date", ""),
(next_page_token or {}).get("start_date", ""),
)
end_date = (stream_slice or {}).get("end_date", pendulum.now(tz="UTC").isoformat(timespec="milliseconds"))
select_fields = ",".join(property_chunk.keys())
table_name = self.name
where_conditions = []
if start_date:
where_conditions.append(f"{self.cursor_field} >= {start_date}")
if end_date:
where_conditions.append(f"{self.cursor_field} < {end_date}")
where_clause = f"WHERE {' AND '.join(where_conditions)}"
query = f"SELECT {select_fields} FROM {table_name} {where_clause}"
return {"q": query}
@property
def cursor_field(self) -> str:
return self.replication_key
@property
def state(self):
return self._state
@state.setter
def state(self, value):
self._state = value
def _get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:
"""
Return the latest state by comparing the cursor value in the latest record with the stream's most recent state
object and returning an updated state object. Check if latest record is IN stream slice interval => ignore if not
"""
latest_record_value: pendulum.DateTime = pendulum.parse(latest_record[self.cursor_field])
slice_max_value: pendulum.DateTime = pendulum.parse(self._slice.get("end_date"))
max_possible_value = min(latest_record_value, slice_max_value)
if current_stream_state.get(self.cursor_field):
if latest_record_value > slice_max_value:
return {self.cursor_field: max_possible_value.isoformat()}
max_possible_value = max(latest_record_value, pendulum.parse(current_stream_state[self.cursor_field]))
return {self.cursor_field: max_possible_value.isoformat()}
| IncrementalRestSalesforceStream |
python | django__django | django/contrib/gis/db/models/functions.py | {
"start": 12203,
"end": 12254
} | class ____(GeomOutputGeoFunc):
arity = 1
| Envelope |
python | numpy__numpy | numpy/distutils/fcompiler/pg.py | {
"start": 1810,
"end": 3568
} | class ____(FCompiler):
compiler_type = 'flang'
description = 'Portland Group Fortran LLVM Compiler'
version_pattern = r'\s*(flang|clang) version (?P<version>[\d.-]+).*'
ar_exe = 'lib.exe'
possible_executables = ['flang']
executables = {
'version_cmd': ["<F77>", "--version"],
'compiler_f77': ["flang"],
'compiler_fix': ["flang"],
'compiler_f90': ["flang"],
'linker_so': [None],
'archiver': [ar_exe, "/verbose", "/OUT:"],
'ranlib': None
}
library_switch = '/OUT:' # No space after /OUT:!
module_dir_switch = '-module ' # Don't remove ending space!
def get_libraries(self):
opt = FCompiler.get_libraries(self)
opt.extend(['flang', 'flangrti', 'ompstub'])
return opt
@functools.lru_cache(maxsize=128)
def get_library_dirs(self):
"""List of compiler library directories."""
opt = FCompiler.get_library_dirs(self)
flang_dir = dirname(self.executables['compiler_f77'][0])
opt.append(normpath(join(flang_dir, '..', 'lib')))
return opt
def get_flags(self):
return []
def get_flags_free(self):
return []
def get_flags_debug(self):
return ['-g']
def get_flags_opt(self):
return ['-O3']
def get_flags_arch(self):
return []
def runtime_library_dir_option(self, dir):
raise NotImplementedError
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
from numpy.distutils import customized_fcompiler
if 'flang' in sys.argv:
print(customized_fcompiler(compiler='flang').get_version())
else:
print(customized_fcompiler(compiler='pg').get_version())
| PGroupFlangCompiler |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 46501,
"end": 46902
} | class ____:
def test_bernoulli(self):
brn = special.bernoulli(5)
assert_allclose(brn, array([1.0000,
-0.5000,
0.1667,
0.0000,
-0.0333,
0.0000]),
atol=1.5e-4, rtol=0)
| TestBernoulli |
python | numba__numba | numba/cuda/cudadecl.py | {
"start": 2356,
"end": 2485
} | class ____(ConcreteTemplate):
key = cuda.threadfence_block
cases = [signature(types.none)]
@register
| Cuda_threadfence_block |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-opensearch/llama_index/vector_stores/opensearch/base.py | {
"start": 1141,
"end": 35251
} | class ____:
"""
Object encapsulating an Opensearch index that has vector search enabled.
If the index does not yet exist, it is created during init.
Therefore, the underlying index is assumed to either:
1) not exist yet or 2) be created due to previous usage of this class.
Args:
endpoint (str): URL (http/https) of elasticsearch endpoint
index (str): Name of the elasticsearch index
dim (int): Dimension of the vector
embedding_field (str): Name of the field in the index to store
embedding array in.
text_field (str): Name of the field to grab text from
method (Optional[dict]): Opensearch "method" JSON obj for configuring
the KNN index.
This includes engine, metric, and other config params. Defaults to:
{"name": "hnsw", "space_type": "l2", "engine": "nmslib",
"parameters": {"ef_construction": 256, "m": 48}}
settings: Optional[dict]: Settings for the Opensearch index creation. Defaults to:
{"index": {"knn": True, "knn.algo_param.ef_search": 100}}
space_type (Optional[str]): space type for distance metric calculation. Defaults to: l2
os_client (Optional[OSClient]): Custom synchronous client (see OpenSearch from opensearch-py)
os_async_client (Optional[OSClient]): Custom asynchronous client (see AsyncOpenSearch from opensearch-py)
excluded_source_fields (Optional[List[str]]): Optional list of document "source" fields to exclude from OpenSearch responses.
**kwargs: Optional arguments passed to the OpenSearch client from opensearch-py.
"""
def __init__(
self,
endpoint: str,
index: str,
dim: int,
embedding_field: str = "embedding",
text_field: str = "content",
method: Optional[dict] = None,
settings: Optional[dict] = None,
engine: Optional[str] = "nmslib",
space_type: Optional[str] = "l2",
max_chunk_bytes: int = 1 * 1024 * 1024,
search_pipeline: Optional[str] = None,
os_client: Optional[OSClient] = None,
os_async_client: Optional[OSClient] = None,
excluded_source_fields: Optional[List[str]] = None,
**kwargs: Any,
):
"""Init params."""
if method is None:
method = {
"name": "hnsw",
"space_type": "l2",
"engine": engine,
"parameters": {"ef_construction": 256, "m": 48},
}
if settings is None:
settings = {"index": {"knn": True, "knn.algo_param.ef_search": 100}}
if embedding_field is None:
embedding_field = "embedding"
self._method = method
self._embedding_field = embedding_field
self._endpoint = endpoint
self._dim = dim
self._index = index
self._text_field = text_field
self._max_chunk_bytes = max_chunk_bytes
self._excluded_source_fields = excluded_source_fields
self._search_pipeline = search_pipeline
http_auth = kwargs.get("http_auth")
self.space_type = space_type
self.is_aoss = self._is_aoss_enabled(http_auth=http_auth)
# initialize mapping
idx_conf = {
"settings": settings,
"mappings": {
"properties": {
embedding_field: {
"type": "knn_vector",
"dimension": dim,
"method": method,
},
}
},
}
self._os_client = os_client or self._get_opensearch_client(
self._endpoint, **kwargs
)
self._os_async_client = os_async_client or self._get_async_opensearch_client(
self._endpoint, **kwargs
)
self._efficient_filtering_enabled = self._is_efficient_filtering_enabled()
not_found_error = self._import_not_found_error()
try:
self._os_client.indices.get(index=self._index)
except TypeError:
# Probably using async so switch to async client
try:
asyncio_run(self._os_async_client.indices.get(index=self._index))
except not_found_error:
asyncio_run(
self._os_async_client.indices.create(
index=self._index, body=idx_conf
)
)
if self.is_aoss:
asyncio_run(self._os_async_client.indices.exists(index=self._index))
else:
asyncio_run(
self._os_async_client.indices.refresh(index=self._index)
)
except not_found_error:
self._os_client.indices.create(index=self._index, body=idx_conf)
if self.is_aoss:
self._os_client.indices.exists(index=self._index)
else:
self._os_client.indices.refresh(index=self._index)
def _import_opensearch(self) -> Any:
"""Import OpenSearch if available, otherwise raise error."""
try:
from opensearchpy import OpenSearch
except ImportError:
raise ImportError(IMPORT_OPENSEARCH_PY_ERROR)
return OpenSearch
def _import_async_opensearch(self) -> Any:
"""Import AsyncOpenSearch if available, otherwise raise error."""
try:
from opensearchpy import AsyncOpenSearch
except ImportError:
raise ImportError(IMPORT_ASYNC_OPENSEARCH_PY_ERROR)
return AsyncOpenSearch
def _import_bulk(self) -> Any:
"""Import bulk if available, otherwise raise error."""
try:
from opensearchpy.helpers import bulk
except ImportError:
raise ImportError(IMPORT_OPENSEARCH_PY_ERROR)
return bulk
def _import_async_bulk(self) -> Any:
"""Import async_bulk if available, otherwise raise error."""
try:
from opensearchpy.helpers import async_bulk
except ImportError:
raise ImportError(IMPORT_ASYNC_OPENSEARCH_PY_ERROR)
return async_bulk
def _import_not_found_error(self) -> Any:
"""Import not found error if available, otherwise raise error."""
try:
from opensearchpy.exceptions import NotFoundError
except ImportError:
raise ImportError(IMPORT_OPENSEARCH_PY_ERROR)
return NotFoundError
def _get_opensearch_client(self, opensearch_url: str, **kwargs: Any) -> Any:
"""Get OpenSearch client from the opensearch_url, otherwise raise error."""
try:
opensearch = self._import_opensearch()
client = opensearch(opensearch_url, **kwargs)
except ValueError as e:
raise ImportError(
f"OpenSearch client string provided is not in proper format. "
f"Got error: {e} "
)
return client
def _get_async_opensearch_client(self, opensearch_url: str, **kwargs: Any) -> Any:
"""Get AsyncOpenSearch client from the opensearch_url, otherwise raise error."""
try:
opensearch = self._import_async_opensearch()
client = opensearch(opensearch_url, **kwargs)
except ValueError as e:
raise ValueError(
f"AsyncOpenSearch client string provided is not in proper format. "
f"Got error: {e} "
)
return client
def _get_opensearch_version(self) -> str:
info = self._os_client.info()
return info["version"]["number"]
def _bulk_ingest_embeddings(
self,
client: Any,
index_name: str,
embeddings: List[List[float]],
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
vector_field: str = "embedding",
text_field: str = "content",
mapping: Optional[Dict] = None,
max_chunk_bytes: Optional[int] = 1 * 1024 * 1024,
is_aoss: bool = False,
) -> List[str]:
"""Bulk Ingest Embeddings into given index."""
if not mapping:
mapping = {}
bulk = self._import_bulk()
not_found_error = self._import_not_found_error()
requests = []
return_ids = []
try:
client.indices.get(index=index_name)
except not_found_error:
client.indices.create(index=index_name, body=mapping)
for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
_id = ids[i] if ids else str(uuid.uuid4())
request = {
"_op_type": "index",
"_index": index_name,
vector_field: embeddings[i],
text_field: text,
"metadata": metadata,
}
if is_aoss:
request["id"] = _id
else:
request["_id"] = _id
requests.append(request)
return_ids.append(_id)
bulk(client, requests, max_chunk_bytes=max_chunk_bytes)
if not is_aoss:
client.indices.refresh(index=index_name)
return return_ids
async def _abulk_ingest_embeddings(
self,
client: Any,
index_name: str,
embeddings: List[List[float]],
texts: Iterable[str],
metadatas: Optional[List[dict]] = None,
ids: Optional[List[str]] = None,
vector_field: str = "embedding",
text_field: str = "content",
mapping: Optional[Dict] = None,
max_chunk_bytes: Optional[int] = 1 * 1024 * 1024,
is_aoss: bool = False,
) -> List[str]:
"""Async Bulk Ingest Embeddings into given index."""
if not mapping:
mapping = {}
async_bulk = self._import_async_bulk()
not_found_error = self._import_not_found_error()
requests = []
return_ids = []
try:
await client.indices.get(index=index_name)
except not_found_error:
await client.indices.create(index=index_name, body=mapping)
for i, text in enumerate(texts):
metadata = metadatas[i] if metadatas else {}
_id = ids[i] if ids else str(uuid.uuid4())
request = {
"_op_type": "index",
"_index": index_name,
vector_field: embeddings[i],
text_field: text,
"metadata": metadata,
}
if is_aoss:
request["id"] = _id
else:
request["_id"] = _id
requests.append(request)
return_ids.append(_id)
await async_bulk(client, requests, max_chunk_bytes=max_chunk_bytes)
if not is_aoss:
await client.indices.refresh(index=index_name)
return return_ids
def _default_approximate_search_query(
self,
query_vector: List[float],
k: int = 4,
filters: Optional[Union[Dict, List]] = None,
vector_field: str = "embedding",
excluded_source_fields: Optional[List[str]] = None,
) -> Dict:
"""For Approximate k-NN Search, this is the default query."""
query = {
"size": k,
"query": {
"knn": {
vector_field: {
"vector": query_vector,
"k": k,
}
}
},
}
if filters:
# filter key must be added only when filtering to avoid "filter doesn't support values of type: START_ARRAY" exception
query["query"]["knn"][vector_field]["filter"] = filters
if excluded_source_fields:
query["_source"] = {"exclude": excluded_source_fields}
return query
def _is_text_field(self, value: Any) -> bool:
"""
Check if value is a string and keyword filtering needs to be performed.
Not applied to datetime strings.
"""
if isinstance(value, str):
try:
datetime.fromisoformat(value)
return False
except ValueError as e:
return True
else:
return False
def _parse_filter(self, filter: MetadataFilter) -> dict:
"""
Parse a single MetadataFilter to equivalent OpenSearch expression.
As Opensearch does not differentiate between scalar/array keyword fields, IN and ANY are equivalent.
"""
key = f"metadata.{filter.key}"
op = filter.operator
equality_postfix = ".keyword" if self._is_text_field(value=filter.value) else ""
if op == FilterOperator.EQ:
return {"term": {f"{key}{equality_postfix}": filter.value}}
elif op in [
FilterOperator.GT,
FilterOperator.GTE,
FilterOperator.LT,
FilterOperator.LTE,
]:
return {"range": {key: {filter.operator.name.lower(): filter.value}}}
elif op == FilterOperator.NE:
return {
"bool": {
"must_not": {"term": {f"{key}{equality_postfix}": filter.value}}
}
}
elif op in [FilterOperator.IN, FilterOperator.ANY]:
if isinstance(filter.value, list) and all(
self._is_text_field(val) for val in filter.value
):
return {"terms": {f"{key}.keyword": filter.value}}
else:
return {"terms": {key: filter.value}}
elif op == FilterOperator.NIN:
return {"bool": {"must_not": {"terms": {key: filter.value}}}}
elif op == FilterOperator.ALL:
return {
"terms_set": {
key: {
"terms": filter.value,
"minimum_should_match_script": {"source": "params.num_terms"},
}
}
}
elif op == FilterOperator.TEXT_MATCH:
return {"match": {key: {"query": filter.value, "fuzziness": "AUTO"}}}
elif op == FilterOperator.CONTAINS:
return {"wildcard": {key: f"*{filter.value}*"}}
elif op == FilterOperator.IS_EMPTY:
return {"bool": {"must_not": {"exists": {"field": key}}}}
else:
raise ValueError(f"Unsupported filter operator: {filter.operator}")
def _parse_filters_recursively(self, filters: MetadataFilters) -> dict:
"""Parse (possibly nested) MetadataFilters to equivalent OpenSearch expression."""
condition_map = {FilterCondition.AND: "must", FilterCondition.OR: "should"}
bool_clause = condition_map[filters.condition]
bool_query: dict[str, dict[str, list[dict]]] = {"bool": {bool_clause: []}}
for filter_item in filters.filters:
if isinstance(filter_item, MetadataFilter):
bool_query["bool"][bool_clause].append(self._parse_filter(filter_item))
elif isinstance(filter_item, MetadataFilters):
bool_query["bool"][bool_clause].append(
self._parse_filters_recursively(filter_item)
)
else:
raise ValueError(f"Unsupported filter type: {type(filter_item)}")
return bool_query
def _parse_filters(self, filters: Optional[MetadataFilters]) -> List[dict]:
"""Parse MetadataFilters to equivalent OpenSearch expression."""
if filters is None:
return []
return [self._parse_filters_recursively(filters=filters)]
def _knn_search_query(
self,
embedding_field: str,
query_embedding: List[float],
k: int,
filters: Optional[MetadataFilters] = None,
search_method="approximate",
excluded_source_fields: Optional[List[str]] = None,
) -> Dict:
"""
Perform a k-Nearest Neighbors (kNN) search.
If the search method is "approximate" and the engine is "lucene" or "faiss", use efficient kNN filtering.
Otherwise, perform an exhaustive exact kNN search using "painless scripting" if the version of
OpenSearch supports it. If the OpenSearch version does not support it, use scoring script search.
Note:
- AWS OpenSearch Serverless does not support the painless scripting functionality at this time according to AWS.
- Approximate kNN search does not support pre-filtering.
Args:
query_embedding (List[float]): Vector embedding to query.
k (int): Maximum number of results.
filters (Optional[MetadataFilters]): Optional filters to apply for the search.
Supports filter-context queries documented at
https://opensearch.org/docs/latest/query-dsl/query-filter-context/
excluded_source_fields: Optional list of document "source" fields to exclude from the response.
Returns:
Dict: Up to k documents closest to query_embedding.
"""
filters = self._parse_filters(filters)
if not filters:
search_query = self._default_approximate_search_query(
query_embedding,
k,
vector_field=embedding_field,
excluded_source_fields=excluded_source_fields,
)
elif (
search_method == "approximate"
and self._method["engine"]
in [
"lucene",
"faiss",
]
and self._efficient_filtering_enabled
):
# if engine is lucene or faiss, opensearch recommends efficient-kNN filtering.
search_query = self._default_approximate_search_query(
query_embedding,
k,
filters={"bool": {"filter": filters}},
vector_field=embedding_field,
excluded_source_fields=excluded_source_fields,
)
else:
if self.is_aoss:
# if is_aoss is set we are using Opensearch Serverless AWS offering which cannot use
# painless scripting so default scoring script returned will be just normal knn_score script
search_query = self._default_scoring_script_query(
query_embedding,
k,
space_type=self.space_type,
pre_filter={"bool": {"filter": filters}},
vector_field=embedding_field,
excluded_source_fields=excluded_source_fields,
)
else:
# https://opensearch.org/docs/latest/search-plugins/knn/painless-functions/
search_query = self._default_scoring_script_query(
query_embedding,
k,
space_type="l2Squared",
pre_filter={"bool": {"filter": filters}},
vector_field=embedding_field,
excluded_source_fields=excluded_source_fields,
)
return search_query
def _hybrid_search_query(
self,
text_field: str,
query_str: str,
embedding_field: str,
query_embedding: List[float],
k: int,
filters: Optional[MetadataFilters] = None,
excluded_source_fields: Optional[List[str]] = None,
) -> Dict:
knn_query = self._knn_search_query(embedding_field, query_embedding, k, filters)
lexical_query = self._lexical_search_query(text_field, query_str, k, filters)
query = {
"size": k,
"query": {
"hybrid": {"queries": [lexical_query["query"], knn_query["query"]]}
},
}
if excluded_source_fields:
query["_source"] = {"exclude": excluded_source_fields}
return query
def _lexical_search_query(
self,
text_field: str,
query_str: str,
k: int,
filters: Optional[MetadataFilters] = None,
excluded_source_fields: Optional[List[str]] = None,
) -> Dict:
lexical_query = {
"bool": {"must": {"match": {text_field: {"query": query_str}}}}
}
parsed_filters = self._parse_filters(filters)
if len(parsed_filters) > 0:
lexical_query["bool"]["filter"] = parsed_filters
query = {
"size": k,
"query": lexical_query,
}
if excluded_source_fields:
query["_source"] = {"exclude": excluded_source_fields}
return query
def __get_painless_scripting_source(
self, space_type: str, vector_field: str = "embedding"
) -> str:
"""
For Painless Scripting, it returns the script source based on space type.
This does not work with Opensearch Serverless currently.
"""
source_value = (
f"(1.0 + {space_type}(params.query_value, doc['{vector_field}']))"
)
if space_type == "cosineSimilarity":
return source_value
else:
return f"1/{source_value}"
def _get_knn_scoring_script(self, space_type, vector_field, query_vector):
"""Default scoring script that will work with AWS Opensearch Serverless."""
return {
"source": "knn_score",
"lang": "knn",
"params": {
"field": vector_field,
"query_value": query_vector,
"space_type": space_type,
},
}
def _get_painless_scoring_script(self, space_type, vector_field, query_vector):
source = self.__get_painless_scripting_source(space_type, vector_field)
return {
"source": source,
"params": {
"field": vector_field,
"query_value": query_vector,
},
}
def _default_scoring_script_query(
self,
query_vector: List[float],
k: int = 4,
space_type: str = "l2Squared",
pre_filter: Optional[Union[Dict, List]] = None,
vector_field: str = "embedding",
excluded_source_fields: Optional[List[str]] = None,
) -> Dict:
"""
For Scoring Script Search, this is the default query. Has to account for Opensearch Service
Serverless which does not support painless scripting functions so defaults to knn_score.
"""
if not pre_filter:
pre_filter = MATCH_ALL_QUERY
# check if we can use painless scripting or have to use default knn_score script
if self.is_aoss:
if space_type == "l2Squared":
raise ValueError(
"Unsupported space type for aoss. Can only use l1, l2, cosinesimil."
)
script = self._get_knn_scoring_script(
space_type, vector_field, query_vector
)
else:
script = self._get_painless_scoring_script(
space_type, vector_field, query_vector
)
query = {
"size": k,
"query": {
"script_score": {
"query": pre_filter,
"script": script,
}
},
}
if excluded_source_fields:
query["_source"] = {"exclude": excluded_source_fields}
return query
def _is_aoss_enabled(self, http_auth: Any) -> bool:
"""Check if the service is http_auth is set as `aoss`."""
return (
http_auth is not None
and hasattr(http_auth, "service")
and http_auth.service == "aoss"
)
def _is_efficient_filtering_enabled(self) -> bool:
"""Check if kNN with efficient filtering is enabled."""
# Technically, AOSS supports efficient filtering,
# but we can't check the version number using .info(); AOSS doesn't support 'GET /'
# so we must skip and disable by default.
if self.is_aoss:
ef_enabled = False
else:
self._os_version = self._get_opensearch_version()
major, minor, patch = self._os_version.split(".")
ef_enabled = int(major) > 2 or (int(major) == 2 and int(minor) >= 9)
return ef_enabled
def index_results(self, nodes: List[BaseNode], **kwargs: Any) -> List[str]:
"""Store results in the index."""
embeddings: List[List[float]] = []
texts: List[str] = []
metadatas: List[dict] = []
ids: List[str] = []
for node in nodes:
ids.append(node.node_id)
embeddings.append(node.get_embedding())
texts.append(node.get_content(metadata_mode=MetadataMode.NONE))
metadatas.append(node_to_metadata_dict(node, remove_text=True))
return self._bulk_ingest_embeddings(
self._os_client,
self._index,
embeddings,
texts,
metadatas=metadatas,
ids=ids,
vector_field=self._embedding_field,
text_field=self._text_field,
mapping=None,
max_chunk_bytes=self._max_chunk_bytes,
is_aoss=self.is_aoss,
)
async def aindex_results(self, nodes: List[BaseNode], **kwargs: Any) -> List[str]:
"""Store results in the index."""
embeddings: List[List[float]] = []
texts: List[str] = []
metadatas: List[dict] = []
ids: List[str] = []
for node in nodes:
ids.append(node.node_id)
embeddings.append(node.get_embedding())
texts.append(node.get_content(metadata_mode=MetadataMode.NONE))
metadatas.append(node_to_metadata_dict(node, remove_text=True))
return await self._abulk_ingest_embeddings(
self._os_async_client,
self._index,
embeddings,
texts,
metadatas=metadatas,
ids=ids,
vector_field=self._embedding_field,
text_field=self._text_field,
mapping=None,
max_chunk_bytes=self._max_chunk_bytes,
is_aoss=self.is_aoss,
)
def delete_by_doc_id(self, doc_id: str) -> None:
"""
Deletes all OpenSearch documents corresponding to the given LlamaIndex `Document` ID.
Args:
doc_id (str): a LlamaIndex `Document` id
"""
search_query = {
"query": {"term": {"metadata.doc_id.keyword": {"value": doc_id}}}
}
self._os_client.delete_by_query(
index=self._index, body=search_query, refresh=True
)
async def adelete_by_doc_id(self, doc_id: str) -> None:
"""
Deletes all OpenSearch documents corresponding to the given LlamaIndex `Document` ID.
Args:
doc_id (str): a LlamaIndex `Document` id
"""
search_query = {
"query": {"term": {"metadata.doc_id.keyword": {"value": doc_id}}}
}
await self._os_async_client.delete_by_query(
index=self._index, body=search_query, refresh=True
)
def delete_nodes(
self,
node_ids: Optional[List[str]] = None,
filters: Optional[MetadataFilters] = None,
**delete_kwargs: Any,
) -> None:
"""
Deletes nodes.
Args:
node_ids (Optional[List[str]], optional): IDs of nodes to delete. Defaults to None.
filters (Optional[MetadataFilters], optional): Metadata filters. Defaults to None.
"""
if not node_ids and not filters:
return
query = {"query": {"bool": {"filter": []}}}
if node_ids:
query["query"]["bool"]["filter"].append({"terms": {"_id": node_ids or []}})
if filters:
query["query"]["bool"]["filter"].extend(self._parse_filters(filters))
self._os_client.delete_by_query(index=self._index, body=query, refresh=True)
async def adelete_nodes(
self,
node_ids: Optional[List[str]] = None,
filters: Optional[MetadataFilters] = None,
**delete_kwargs: Any,
) -> None:
"""
Deletes nodes.
Args:
node_ids (Optional[List[str]], optional): IDs of nodes to delete. Defaults to None.
filters (Optional[MetadataFilters], optional): Metadata filters. Defaults to None.
"""
if not node_ids and not filters:
return
query = {"query": {"bool": {"filter": []}}}
if node_ids:
query["query"]["bool"]["filter"].append({"terms": {"_id": node_ids or []}})
if filters:
query["query"]["bool"]["filter"].extend(self._parse_filters(filters))
await self._os_async_client.delete_by_query(
index=self._index, body=query, refresh=True
)
def clear(self) -> None:
"""Clears index."""
query = {"query": {"bool": {"filter": []}}}
self._os_client.delete_by_query(index=self._index, body=query, refresh=True)
async def aclear(self) -> None:
"""Clears index."""
query = {"query": {"bool": {"filter": []}}}
await self._os_async_client.delete_by_query(
index=self._index, body=query, refresh=True
)
def query(
self,
query_mode: VectorStoreQueryMode,
query_str: Optional[str],
query_embedding: List[float],
k: int,
filters: Optional[MetadataFilters] = None,
) -> VectorStoreQueryResult:
if query_mode == VectorStoreQueryMode.HYBRID:
if query_str is None or self._search_pipeline is None:
raise ValueError(INVALID_HYBRID_QUERY_ERROR)
search_query = self._hybrid_search_query(
self._text_field,
query_str,
self._embedding_field,
query_embedding,
k,
filters=filters,
excluded_source_fields=self._excluded_source_fields,
)
params = {
"search_pipeline": self._search_pipeline,
}
elif query_mode == VectorStoreQueryMode.TEXT_SEARCH:
search_query = self._lexical_search_query(
self._text_field,
query_str,
k,
filters=filters,
excluded_source_fields=self._excluded_source_fields,
)
params = None
else:
search_query = self._knn_search_query(
self._embedding_field,
query_embedding,
k,
filters=filters,
excluded_source_fields=self._excluded_source_fields,
)
params = None
res = self._os_client.search(
index=self._index, body=search_query, params=params
)
return self._to_query_result(res)
async def aquery(
self,
query_mode: VectorStoreQueryMode,
query_str: Optional[str],
query_embedding: List[float],
k: int,
filters: Optional[MetadataFilters] = None,
) -> VectorStoreQueryResult:
if query_mode == VectorStoreQueryMode.HYBRID:
if query_str is None or self._search_pipeline is None:
raise ValueError(INVALID_HYBRID_QUERY_ERROR)
search_query = self._hybrid_search_query(
self._text_field,
query_str,
self._embedding_field,
query_embedding,
k,
filters=filters,
excluded_source_fields=self._excluded_source_fields,
)
params = {
"search_pipeline": self._search_pipeline,
}
elif query_mode == VectorStoreQueryMode.TEXT_SEARCH:
search_query = self._lexical_search_query(
self._text_field,
query_str,
k,
filters=filters,
excluded_source_fields=self._excluded_source_fields,
)
params = None
else:
search_query = self._knn_search_query(
self._embedding_field,
query_embedding,
k,
filters=filters,
excluded_source_fields=self._excluded_source_fields,
)
params = None
res = await self._os_async_client.search(
index=self._index, body=search_query, params=params
)
return self._to_query_result(res)
def _to_query_result(self, res) -> VectorStoreQueryResult:
nodes = []
ids = []
scores = []
for hit in res["hits"]["hits"]:
source = hit["_source"]
node_id = hit["_id"]
text = source[self._text_field]
metadata = source.get("metadata", None)
try:
node = metadata_dict_to_node(metadata)
node.text = text
except Exception:
# TODO: Legacy support for old nodes
node_info = source.get("node_info")
relationships = source.get("relationships") or {}
start_char_idx = None
end_char_idx = None
if isinstance(node_info, dict):
start_char_idx = node_info.get("start", None)
end_char_idx = node_info.get("end", None)
node = TextNode(
text=text,
metadata=metadata,
id_=node_id,
start_char_idx=start_char_idx,
end_char_idx=end_char_idx,
relationships=relationships,
)
ids.append(node_id)
nodes.append(node)
scores.append(hit["_score"])
return VectorStoreQueryResult(nodes=nodes, ids=ids, similarities=scores)
| OpensearchVectorClient |
python | eventlet__eventlet | tests/greendns_test.py | {
"start": 32586,
"end": 34005
} | class ____(tests.LimitedTestCase):
def _make_mock_getaliases(self):
class GetAliases:
aliases = ['cname.example.com']
def __call__(self, *args, **kwargs):
return self.aliases
getaliases = GetAliases()
return getaliases
def setUp(self):
self._old_resolve = greendns.resolve
greendns.resolve = _make_mock_resolve()
self._old_getaliases = greendns.getaliases
def tearDown(self):
greendns.resolve = self._old_resolve
greendns.getaliases = self._old_getaliases
def test_ipaddr(self):
res = greendns.gethostbyname_ex('1.2.3.4')
assert res == ('1.2.3.4', [], ['1.2.3.4'])
def test_name(self):
greendns.resolve.add('host.example.com', '1.2.3.4')
greendns.getaliases = self._make_mock_getaliases()
greendns.getaliases.aliases = []
res = greendns.gethostbyname_ex('host.example.com')
assert res == ('host.example.com', [], ['1.2.3.4'])
def test_multiple_addrs(self):
greendns.resolve.add('host.example.com', '1.2.3.4')
greendns.resolve.add('host.example.com', '1.2.3.5')
greendns.getaliases = self._make_mock_getaliases()
greendns.getaliases.aliases = []
res = greendns.gethostbyname_ex('host.example.com')
assert res == ('host.example.com', [], ['1.2.3.4', '1.2.3.5'])
| TestGethostbyname_ex |
python | neetcode-gh__leetcode | python/0133-clone-graph.py | {
"start": 0,
"end": 407
} | class ____:
def cloneGraph(self, node: "Node") -> "Node":
oldToNew = {}
def dfs(node):
if node in oldToNew:
return oldToNew[node]
copy = Node(node.val)
oldToNew[node] = copy
for nei in node.neighbors:
copy.neighbors.append(dfs(nei))
return copy
return dfs(node) if node else None
| Solution |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/session_debug_multi_gpu_test.py | {
"start": 1358,
"end": 3415
} | class ____(test_util.TensorFlowTestCase):
def setUp(self):
self._dump_root = tempfile.mkdtemp()
def tearDown(self):
ops.reset_default_graph()
# Tear down temporary dump directory.
if os.path.isdir(self._dump_root):
file_io.delete_recursively(self._dump_root)
def testMultiGPUSessionRun(self):
local_devices = device_lib.list_local_devices()
gpu_device_names = []
for device in local_devices:
if device.device_type == "GPU":
gpu_device_names.append(device.name)
gpu_device_names = sorted(gpu_device_names)
if len(gpu_device_names) < 2:
self.skipTest(
"This test requires at least 2 GPUs, but only %d is available." %
len(gpu_device_names))
with session.Session() as sess:
v = variables.Variable([10.0, 15.0], dtype=dtypes.float32, name="v")
with ops.device(gpu_device_names[0]):
u0 = math_ops.add(v, v, name="u0")
with ops.device(gpu_device_names[1]):
u1 = math_ops.multiply(v, v, name="u1")
w = math_ops.subtract(u1, u0, name="w")
self.evaluate(v.initializer)
run_options = config_pb2.RunOptions(output_partition_graphs=True)
debug_utils.watch_graph(run_options, sess.graph,
debug_urls="file://" + self._dump_root)
run_metadata = config_pb2.RunMetadata()
self.assertAllClose(
[80.0, 195.0],
sess.run(w, options=run_options, run_metadata=run_metadata))
debug_dump_dir = debug_data.DebugDumpDir(
self._dump_root, partition_graphs=run_metadata.partition_graphs)
self.assertEqual(3, len(debug_dump_dir.devices()))
self.assertAllClose(
[10.0, 15.0], debug_dump_dir.get_tensors("v", 0, "DebugIdentity")[0])
self.assertAllClose(
[20.0, 30.0], debug_dump_dir.get_tensors("u0", 0, "DebugIdentity")[0])
self.assertAllClose(
[100.0, 225.0],
debug_dump_dir.get_tensors("u1", 0, "DebugIdentity")[0])
if __name__ == "__main__":
googletest.main()
| SessionDebugMultiGPUTest |
python | numba__numba | numba/tests/test_dictimpl.py | {
"start": 6042,
"end": 20038
} | class ____(TestCase):
def setUp(self):
"""Bind to the c_helper library and provide the ctypes wrapper.
"""
dict_t = ctypes.c_void_p
iter_t = ctypes.c_void_p
hash_t = ctypes.c_ssize_t
def wrap(name, restype, argtypes=()):
proto = ctypes.CFUNCTYPE(restype, *argtypes)
return proto(_helperlib.c_helpers[name])
# numba_test_dict()
self.numba_test_dict = wrap(
'test_dict',
ctypes.c_int,
)
# numba_dict_new_sized(
# NB_Dict **out,
# Py_ssize_t n_keys,
# Py_ssize_t key_size,
# Py_ssize_t val_size
# )
self.numba_dict_new_sized = wrap(
'dict_new_sized',
ctypes.c_int,
[
ctypes.POINTER(dict_t), # out
ctypes.c_ssize_t, # n_keys
ctypes.c_ssize_t, # key_size
ctypes.c_ssize_t, # val_size
],
)
# numba_dict_free(NB_Dict *d)
self.numba_dict_free = wrap(
'dict_free',
None,
[dict_t],
)
# numba_dict_length(NB_Dict *d)
self.numba_dict_length = wrap(
'dict_length',
ctypes.c_ssize_t,
[dict_t],
)
# numba_dict_insert_ez(
# NB_Dict *d,
# const char *key_bytes,
# Py_hash_t hash,
# const char *val_bytes,
# )
self.numba_dict_insert_ez = wrap(
'dict_insert_ez',
ctypes.c_int,
[
dict_t, # d
ctypes.c_char_p, # key_bytes
hash_t, # hash
ctypes.c_char_p, # val_bytes
],
)
# numba_dict_lookup(
# NB_Dict *d,
# const char *key_bytes,
# Py_hash_t hash,
# char *oldval_bytes
# )
self.numba_dict_lookup = wrap(
'dict_lookup',
ctypes.c_ssize_t,
[
dict_t, # d
ctypes.c_char_p, # key_bytes
hash_t, # hash
ctypes.c_char_p, # oldval_bytes
],
)
# numba_dict_delitem(
# NB_Dict *d,
# Py_hash_t hash,
# Py_ssize_t ix
# )
self.numba_dict_delitem = wrap(
'dict_delitem',
ctypes.c_int,
[
dict_t, # d
hash_t, # hash
ctypes.c_ssize_t, # ix
],
)
# numba_dict_popitem(
# NB_Dict *d,
# char *key_bytes,
# char *val_bytes
# )
self.numba_dict_popitem = wrap(
'dict_popitem',
ctypes.c_int,
[
dict_t, # d
ctypes.c_char_p, # key_bytes
ctypes.c_char_p, # val_bytes
],
)
# numba_dict_iter_sizeof()
self.numba_dict_iter_sizeof = wrap(
'dict_iter_sizeof',
ctypes.c_size_t,
)
# numba_dict_iter(
# NB_DictIter *it,
# NB_Dict *d
# )
self.numba_dict_iter = wrap(
'dict_iter',
None,
[
iter_t,
dict_t,
],
)
# numba_dict_iter_next(
# NB_DictIter *it,
# const char **key_ptr,
# const char **val_ptr
# )
self.numba_dict_iter_next = wrap(
'dict_iter_next',
ctypes.c_int,
[
iter_t, # it
ctypes.POINTER(ctypes.c_void_p), # key_ptr
ctypes.POINTER(ctypes.c_void_p), # val_ptr
],
)
def test_simple_c_test(self):
# Runs the basic test in C.
ret = self.numba_test_dict()
self.assertEqual(ret, 0)
def test_insertion_small(self):
# Tests insertion and lookup for a small dict.
d = Dict(self, 4, 8)
self.assertEqual(len(d), 0)
self.assertIsNone(d.get('abcd'))
# First key
d['abcd'] = 'beefcafe'
self.assertEqual(len(d), 1)
self.assertIsNotNone(d.get('abcd'))
self.assertEqual(d['abcd'], 'beefcafe')
# Duplicated key replaces
d['abcd'] = 'cafe0000'
self.assertEqual(len(d), 1)
self.assertEqual(d['abcd'], 'cafe0000')
# Second key
d['abce'] = 'cafe0001'
self.assertEqual(len(d), 2)
self.assertEqual(d['abcd'], 'cafe0000')
self.assertEqual(d['abce'], 'cafe0001')
# Third key
d['abcf'] = 'cafe0002'
self.assertEqual(len(d), 3)
self.assertEqual(d['abcd'], 'cafe0000')
self.assertEqual(d['abce'], 'cafe0001')
self.assertEqual(d['abcf'], 'cafe0002')
def check_insertion_many(self, nmax):
# Helper to test insertion/lookup/resize
d = Dict(self, 8, 8)
def make_key(v):
return "key_{:04}".format(v)
def make_val(v):
return "val_{:04}".format(v)
# Check insert
for i in range(nmax):
d[make_key(i)] = make_val(i)
self.assertEqual(len(d), i + 1)
# Check lookup
for i in range(nmax):
self.assertEqual(d[make_key(i)], make_val(i))
def test_insertion_many(self):
# Test insertion for differently sized dict
# Around minsize
self.check_insertion_many(nmax=7)
self.check_insertion_many(nmax=8)
self.check_insertion_many(nmax=9)
# Around nmax = 32
self.check_insertion_many(nmax=31)
self.check_insertion_many(nmax=32)
self.check_insertion_many(nmax=33)
# Around nmax = 1024
self.check_insertion_many(nmax=1023)
self.check_insertion_many(nmax=1024)
self.check_insertion_many(nmax=1025)
# Around nmax = 4096
self.check_insertion_many(nmax=4095)
self.check_insertion_many(nmax=4096)
self.check_insertion_many(nmax=4097)
def test_deletion_small(self):
# Test deletion
d = Dict(self, 4, 8)
self.assertEqual(len(d), 0)
self.assertIsNone(d.get('abcd'))
d['abcd'] = 'cafe0000'
d['abce'] = 'cafe0001'
d['abcf'] = 'cafe0002'
self.assertEqual(len(d), 3)
self.assertEqual(d['abcd'], 'cafe0000')
self.assertEqual(d['abce'], 'cafe0001')
self.assertEqual(d['abcf'], 'cafe0002')
self.assertEqual(len(d), 3)
# Delete first item
del d['abcd']
self.assertIsNone(d.get('abcd'))
self.assertEqual(d['abce'], 'cafe0001')
self.assertEqual(d['abcf'], 'cafe0002')
self.assertEqual(len(d), 2)
# Delete first item again
with self.assertRaises(KeyError):
del d['abcd']
# Delete third
del d['abcf']
self.assertIsNone(d.get('abcd'))
self.assertEqual(d['abce'], 'cafe0001')
self.assertIsNone(d.get('abcf'))
self.assertEqual(len(d), 1)
# Delete second
del d['abce']
self.assertIsNone(d.get('abcd'))
self.assertIsNone(d.get('abce'))
self.assertIsNone(d.get('abcf'))
self.assertEqual(len(d), 0)
def check_delete_randomly(self, nmax, ndrop, nrefill, seed=0):
# Helper to test deletion
random.seed(seed)
d = Dict(self, 8, 8)
keys = {}
def make_key(v):
return "k_{:06x}".format(v)
def make_val(v):
return "v_{:06x}".format(v)
for i in range(nmax):
d[make_key(i)] = make_val(i)
# Fill to nmax
for i in range(nmax):
k = make_key(i)
v = make_val(i)
keys[k] = v
self.assertEqual(d[k], v)
self.assertEqual(len(d), nmax)
# Randomly drop
droplist = random.sample(list(keys), ndrop)
remain = keys.copy()
for i, k in enumerate(droplist, start=1):
del d[k]
del remain[k]
self.assertEqual(len(d), nmax - i)
self.assertEqual(len(d), nmax - ndrop)
# Make sure everything dropped is gone
for k in droplist:
self.assertIsNone(d.get(k))
# Make sure everything else is still here
for k in remain:
self.assertEqual(d[k], remain[k])
# Refill
for i in range(nrefill):
k = make_key(nmax + i)
v = make_val(nmax + i)
remain[k] = v
d[k] = v
self.assertEqual(len(remain), len(d))
# Make sure everything is here
for k in remain:
self.assertEqual(d[k], remain[k])
def test_delete_randomly(self):
# Test deletion for differently sized dict
self.check_delete_randomly(nmax=8, ndrop=2, nrefill=2)
self.check_delete_randomly(nmax=13, ndrop=10, nrefill=31)
self.check_delete_randomly(nmax=100, ndrop=50, nrefill=200)
self.check_delete_randomly(nmax=100, ndrop=99, nrefill=100)
self.check_delete_randomly(nmax=100, ndrop=100, nrefill=100)
self.check_delete_randomly(nmax=1024, ndrop=999, nrefill=1)
self.check_delete_randomly(nmax=1024, ndrop=999, nrefill=2048)
def test_delete_randomly_large(self):
# Go beyond 2^16 to exercise large indices.
# Internally, size of index changes as the hashtable size changes.
# Size of index can be 8, 16, 32 or 64 bytes (on 64-bit).
# We are not inserting >2^32 elements because of limitation of time.
self.check_delete_randomly(nmax=2**17, ndrop=2**16, nrefill=2**10)
def test_popitem(self):
nmax = 10
d = Dict(self, 8, 8)
def make_key(v):
return "k_{:06x}".format(v)
def make_val(v):
return "v_{:06x}".format(v)
for i in range(nmax):
d[make_key(i)] = make_val(i)
self.assertEqual(len(d), nmax)
k, v = d.popitem()
self.assertEqual(len(d), nmax - 1)
self.assertEqual(k, make_key(len(d)))
self.assertEqual(v, make_val(len(d)))
while len(d):
n = len(d)
k, v = d.popitem()
self.assertEqual(len(d), n - 1)
self.assertEqual(k, make_key(len(d)))
self.assertEqual(v, make_val(len(d)))
self.assertEqual(len(d), 0)
with self.assertRaises(KeyError) as raises:
d.popitem()
self.assertIn(
'popitem(): dictionary is empty',
str(raises.exception),
)
def test_iter_items(self):
# Test .items iteration
d = Dict(self, 4, 4)
nmax = 1000
def make_key(v):
return "{:04}".format(v)
def make_val(v):
return "{:04}".format(v + nmax)
for i in range(nmax):
d[make_key(i)] = make_val(i)
# Check that the everything is ordered
for i, (k, v) in enumerate(d.items()):
self.assertEqual(make_key(i), k)
self.assertEqual(make_val(i), v)
def check_sizing(self, key_size, val_size, nmax):
# Helper to verify different key/value sizes.
d = Dict(self, key_size, val_size)
def make_key(v):
return "{:0{}}".format(v, key_size)[:key_size]
def make_val(v):
return "{:0{}}".format(nmax - v - 1, val_size)[:val_size]
for i in range(nmax):
d[make_key(i)] = make_val(i)
# Check that the everything is ordered
for i, (k, v) in enumerate(d.items()):
self.assertEqual(make_key(i), k)
self.assertEqual(make_val(i), v)
def test_sizing(self):
# Check different sizes of the key & value.
for i in range(1, 8):
self.check_sizing(key_size=i, val_size=i, nmax=2**i)
def test_parameterized_types(self):
"""https://github.com/numba/numba/issues/6401"""
register_model(ParametrizedType)(UniTupleModel)
@typeof_impl.register(Parametrized)
def typeof_unit(val, c):
return ParametrizedType(val)
@unbox(ParametrizedType)
def unbox_parametrized(typ, obj, context):
return context.unbox(types.UniTuple(typ.dtype, len(typ)), obj)
def dict_vs_cache_vs_parametrized(v):
assert 0
@overload(dict_vs_cache_vs_parametrized)
def ol_dict_vs_cache_vs_parametrized(v):
typ = v
def objmode_vs_cache_vs_parametrized_impl(v):
# typed.List shows same behaviour after fix for #6397
d = typed.Dict.empty(types.unicode_type, typ)
d['data'] = v
return objmode_vs_cache_vs_parametrized_impl
@jit(nopython=True, cache=True)
def set_parametrized_data(x, y):
# Has had a tendency to segfault when the compiled function
# was loaded from cache in a different process than the one
# it was originally compiled in.
# The new process is simulated below by resetting the dispatchers
# and the target context
dict_vs_cache_vs_parametrized(x)
dict_vs_cache_vs_parametrized(y)
x, y = Parametrized(('a', 'b')), Parametrized(('a',))
set_parametrized_data(x, y)
# reset dispatchers and targetctx to force re-load from cache as if a
# new process would jit the function
set_parametrized_data._make_finalizer()()
set_parametrized_data._reset_overloads()
set_parametrized_data.targetctx.init()
for ii in range(50): # <- sometimes works a few times
self.assertIsNone(set_parametrized_data(x, y))
| TestDictImpl |
python | bokeh__bokeh | src/bokeh/core/property/visual.py | {
"start": 3444,
"end": 3762
} | class ____(String):
def validate(self, value: Any, detail: bool = True) -> None:
super().validate(value, detail)
if not (isinstance(value, str) and CSS_LENGTH_RE.match(value)):
msg = "" if not detail else f"{value!r} is not a valid CSS length"
raise ValueError(msg)
| CSSLength |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_to_exist.py | {
"start": 2342,
"end": 12412
} | class ____(BatchExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectColumnToExist is a \
Batch Expectation.
BatchExpectations are one of the most common types of Expectation. They are evaluated for an entire Batch, and answer a semantic question about the Batch itself.
Args:
column (str): {COLUMN_DESCRIPTION}
Other Parameters:
column_index (int or None, optional): {COLUMN_INDEX_DESCRIPTION}
result_format (str or None, optional): \
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, optional): \
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, optional): \
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/)
[{SUPPORTED_DATA_SOURCES[12]}](https://docs.greatexpectations.io/docs/application_integration_support/)
Data Quality Issues:
{DATA_QUALITY_ISSUES[0]}
Example Data:
test test2
0 1.00 2
1 2.30 5
2 4.33 0
Passing Case:
Input:
ExpectColumnToExist(
column="test",
column_index=0
)
Output:
{{
"exception_info": {{
"raised_exception": false,
"exception_traceback": null,
"exception_message": null
}},
"meta": {{}},
"success": true,
"result": {{}}
}}
Failing Case:
Input:
ExpectColumnToExist(
column="missing_column",
)
Output:
{{
"exception_info": {{
"raised_exception": false,
"exception_traceback": null,
"exception_message": null
}},
"meta": {{}},
"success": false,
"result": {{}}
}}
""" # noqa: E501 # FIXME CoP
column: StrictStr = Field(min_length=1, description=COLUMN_DESCRIPTION)
column_index: Union[int, SuiteParameterDict, None] = Field(
default=None, description=COLUMN_INDEX_DESCRIPTION
)
# This dictionary contains metadata for display in the public gallery
library_metadata: ClassVar[Dict[str, Union[str, list, bool]]] = {
"maturity": "production",
"tags": ["core expectation", "table expectation"],
"contributors": ["@great_expectations"],
"requirements": [],
"has_full_test_suite": True,
"manually_reviewed_code": True,
}
_library_metadata = library_metadata
metric_dependencies = ("table.columns",)
success_keys = (
"column",
"column_index",
)
domain_keys = (
"batch_id",
"table",
)
args_keys = ("column", "column_index")
class Config:
title = "Expect column to exist"
@staticmethod
def schema_extra(schema: Dict[str, Any], model: Type[ExpectColumnToExist]) -> None:
BatchExpectation.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,
},
}
)
@classmethod
@override
def _prescriptive_template(
cls,
renderer_configuration: RendererConfiguration,
) -> RendererConfiguration:
add_param_args: AddParamArgs = (
("column", RendererValueType.STRING),
("column_index", RendererValueType.NUMBER),
)
for name, param_type in add_param_args:
renderer_configuration.add_param(name=name, param_type=param_type)
params = renderer_configuration.params
if not params.column_index:
if renderer_configuration.include_column_name:
template_str = "$column is a required field."
else:
template_str = "is a required field."
else:
renderer_configuration.add_param(
name="column_indexth",
param_type=RendererValueType.STRING,
value=ordinal(params.column_index.value),
)
if renderer_configuration.include_column_name:
template_str = "$column must be the $column_indexth field."
else:
template_str = "must be the $column_indexth field."
renderer_configuration.template_str = template_str
return renderer_configuration
@classmethod
@override
@renderer(renderer_type=LegacyRendererType.PRESCRIPTIVE)
@render_suite_parameter_string
def _prescriptive_renderer(
cls,
configuration: Optional[ExpectationConfiguration] = None,
result: Optional[ExpectationValidationResult] = None,
runtime_configuration: Optional[dict] = None,
**kwargs,
) -> list[RenderedStringTemplateContent]:
runtime_configuration = runtime_configuration or {}
include_column_name = runtime_configuration.get("include_column_name") is not False
styling = runtime_configuration.get("styling")
params = substitute_none_for_missing(
configuration.kwargs, # type: ignore[union-attr] # FIXME: could be None
["column", "column_index"],
)
if params["column_index"] is None:
if include_column_name:
template_str = "$column is a required field."
else:
template_str = "is a required field."
else:
params["column_indexth"] = ordinal(params["column_index"])
if include_column_name:
template_str = "$column must be the $column_indexth field."
else:
template_str = "must be the $column_indexth field."
return [
RenderedStringTemplateContent(
content_block_type="string_template",
string_template={
"template": template_str,
"params": params,
"styling": styling,
},
)
]
@override
def _validate(
self,
metrics: Dict,
runtime_configuration: Optional[dict] = None,
execution_engine: Optional[ExecutionEngine] = None,
):
actual_columns = metrics["table.columns"]
expected_column_name = self._get_success_kwargs().get("column")
expected_column_index = self._get_success_kwargs().get("column_index")
if expected_column_index:
try:
success = actual_columns[expected_column_index] == expected_column_name
except IndexError:
success = False
else:
success = expected_column_name in actual_columns
return {"success": success}
| ExpectColumnToExist |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/core_tests/resource_tests/test_with_resources.py | {
"start": 19575,
"end": 20865
} | class ____(PickledObjectFilesystemIOManager):
def __init__(self):
super().__init__(base_dir="/tmp/dagster/foo-io-manager")
io_manager_resource_fn = lambda _: FooIoManager()
foo_io_manager_def = dg.IOManagerDefinition(
resource_fn=io_manager_resource_fn,
config_schema={},
)
def create_asset_job():
@dg.asset
def my_derived_asset():
return 4
return dg.Definitions(
assets=[my_derived_asset], jobs=[dg.define_asset_job("the_job", [my_derived_asset])]
).resolve_job_def("the_job")
def test_source_asset_default_io_manager(instance):
with environ(
{
"DAGSTER_DEFAULT_IO_MANAGER_MODULE": (
"dagster_tests.core_tests.resource_tests.test_with_resources"
),
"DAGSTER_DEFAULT_IO_MANAGER_ATTRIBUTE": "foo_io_manager_def",
}
):
assert dg.execute_job(dg.reconstructable(create_asset_job), instance).success
with environ(
{
"DAGSTER_DEFAULT_IO_MANAGER_MODULE": (
"dagster_tests.core_tests.resource_tests.fake_file"
),
"DAGSTER_DEFAULT_IO_MANAGER_ATTRIBUTE": "foo_io_manager_def",
}
):
assert not dg.execute_job(dg.reconstructable(create_asset_job), instance).success
| FooIoManager |
python | lxml__lxml | doc/s5/ep2008/atom.py | {
"start": 8752,
"end": 9170
} | class ____(object):
def __get__(self, obj, type=None):
if obj is None:
return self
return parse_date(obj.text)
def __set__(self, obj, value):
if not value:
obj.text = None
return
if isinstance(value, datetime):
value = _strftime(value)
obj.text = value
def __del__(self, obj):
obj.text = None
| _date_text_property |
python | paramiko__paramiko | paramiko/agent.py | {
"start": 6658,
"end": 7798
} | class ____(AgentProxyThread):
"""
Class to be used when wanting to ask a remote SSH Agent
"""
def __init__(self, agent, chan):
AgentProxyThread.__init__(self, agent)
self.__chan = chan
def get_connection(self):
return self.__chan, None
def get_agent_connection():
"""
Returns some SSH agent object, or None if none were found/supported.
.. versionadded:: 2.10
"""
if ("SSH_AUTH_SOCK" in os.environ) and (sys.platform != "win32"):
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
conn.connect(os.environ["SSH_AUTH_SOCK"])
return conn
except:
# probably a dangling env var: the ssh agent is gone
return
elif sys.platform == "win32":
from . import win_pageant, win_openssh
conn = None
if win_pageant.can_talk_to_agent():
conn = win_pageant.PageantConnection()
elif win_openssh.can_talk_to_agent():
conn = win_openssh.OpenSSHAgentConnection()
return conn
else:
# no agent support
return
| AgentRemoteProxy |
python | ray-project__ray | python/ray/tune/callback.py | {
"start": 2126,
"end": 11739
} | class ____(metaclass=_CallbackMeta):
"""Tune base callback that can be extended and passed to a ``TrialRunner``
Tune callbacks are called from within the ``TrialRunner`` class. There are
several hooks that can be used, all of which are found in the submethod
definitions of this base class.
The parameters passed to the ``**info`` dict vary between hooks. The
parameters passed are described in the docstrings of the methods.
This example will print a metric each time a result is received:
.. testcode::
from ray import tune
from ray.tune import Callback
class MyCallback(Callback):
def on_trial_result(self, iteration, trials, trial, result,
**info):
print(f"Got result: {result['metric']}")
def train_func(config):
for i in range(10):
tune.report(metric=i)
tuner = tune.Tuner(
train_func,
run_config=tune.RunConfig(
callbacks=[MyCallback()]
)
)
tuner.fit()
.. testoutput::
:hide:
...
"""
# File templates for any artifacts written by this callback
# These files should live in the `trial.local_path` for each trial.
# TODO(ml-team): Make this more visible to users to override. Internal use for now.
_SAVED_FILE_TEMPLATES = []
# arguments here match Experiment.public_spec
def setup(
self,
stop: Optional["Stopper"] = None,
num_samples: Optional[int] = None,
total_num_samples: Optional[int] = None,
**info,
):
"""Called once at the very beginning of training.
Any Callback setup should be added here (setting environment
variables, etc.)
Arguments:
stop: Stopping criteria.
If ``time_budget_s`` was passed to ``tune.RunConfig``, a
``TimeoutStopper`` will be passed here, either by itself
or as a part of a ``CombinedStopper``.
num_samples: Number of times to sample from the
hyperparameter space. Defaults to 1. If `grid_search` is
provided as an argument, the grid will be repeated
`num_samples` of times. If this is -1, (virtually) infinite
samples are generated until a stopping condition is met.
total_num_samples: Total number of samples factoring
in grid search samplers.
**info: Kwargs dict for forward compatibility.
"""
pass
def on_step_begin(self, iteration: int, trials: List["Trial"], **info):
"""Called at the start of each tuning loop step.
Arguments:
iteration: Number of iterations of the tuning loop.
trials: List of trials.
**info: Kwargs dict for forward compatibility.
"""
pass
def on_step_end(self, iteration: int, trials: List["Trial"], **info):
"""Called at the end of each tuning loop step.
The iteration counter is increased before this hook is called.
Arguments:
iteration: Number of iterations of the tuning loop.
trials: List of trials.
**info: Kwargs dict for forward compatibility.
"""
pass
def on_trial_start(
self, iteration: int, trials: List["Trial"], trial: "Trial", **info
):
"""Called after starting a trial instance.
Arguments:
iteration: Number of iterations of the tuning loop.
trials: List of trials.
trial: Trial that just has been started.
**info: Kwargs dict for forward compatibility.
"""
pass
def on_trial_restore(
self, iteration: int, trials: List["Trial"], trial: "Trial", **info
):
"""Called after restoring a trial instance.
Arguments:
iteration: Number of iterations of the tuning loop.
trials: List of trials.
trial: Trial that just has been restored.
**info: Kwargs dict for forward compatibility.
"""
pass
def on_trial_save(
self, iteration: int, trials: List["Trial"], trial: "Trial", **info
):
"""Called after receiving a checkpoint from a trial.
Arguments:
iteration: Number of iterations of the tuning loop.
trials: List of trials.
trial: Trial that just saved a checkpoint.
**info: Kwargs dict for forward compatibility.
"""
pass
def on_trial_result(
self,
iteration: int,
trials: List["Trial"],
trial: "Trial",
result: Dict,
**info,
):
"""Called after receiving a result from a trial.
The search algorithm and scheduler are notified before this
hook is called.
Arguments:
iteration: Number of iterations of the tuning loop.
trials: List of trials.
trial: Trial that just sent a result.
result: Result that the trial sent.
**info: Kwargs dict for forward compatibility.
"""
pass
def on_trial_complete(
self, iteration: int, trials: List["Trial"], trial: "Trial", **info
):
"""Called after a trial instance completed.
The search algorithm and scheduler are notified before this
hook is called.
Arguments:
iteration: Number of iterations of the tuning loop.
trials: List of trials.
trial: Trial that just has been completed.
**info: Kwargs dict for forward compatibility.
"""
pass
def on_trial_recover(
self, iteration: int, trials: List["Trial"], trial: "Trial", **info
):
"""Called after a trial instance failed (errored) but the trial is scheduled
for retry.
The search algorithm and scheduler are not notified.
Arguments:
iteration: Number of iterations of the tuning loop.
trials: List of trials.
trial: Trial that just has errored.
**info: Kwargs dict for forward compatibility.
"""
pass
def on_trial_error(
self, iteration: int, trials: List["Trial"], trial: "Trial", **info
):
"""Called after a trial instance failed (errored).
The search algorithm and scheduler are notified before this
hook is called.
Arguments:
iteration: Number of iterations of the tuning loop.
trials: List of trials.
trial: Trial that just has errored.
**info: Kwargs dict for forward compatibility.
"""
pass
def on_checkpoint(
self,
iteration: int,
trials: List["Trial"],
trial: "Trial",
checkpoint: "ray.tune.Checkpoint",
**info,
):
"""Called after a trial saved a checkpoint with Tune.
Arguments:
iteration: Number of iterations of the tuning loop.
trials: List of trials.
trial: Trial that just has errored.
checkpoint: Checkpoint object that has been saved
by the trial.
**info: Kwargs dict for forward compatibility.
"""
pass
def on_experiment_end(self, trials: List["Trial"], **info):
"""Called after experiment is over and all trials have concluded.
Arguments:
trials: List of trials.
**info: Kwargs dict for forward compatibility.
"""
pass
def get_state(self) -> Optional[Dict]:
"""Get the state of the callback.
This method should be implemented by subclasses to return a dictionary
representation of the object's current state.
This is called automatically by Tune to periodically checkpoint callback state.
Upon :ref:`Tune experiment restoration <tune-experiment-level-fault-tolerance>`,
callback state will be restored via :meth:`~ray.tune.Callback.set_state`.
.. testcode::
from typing import Dict, List, Optional
from ray.tune import Callback
from ray.tune.experiment import Trial
class MyCallback(Callback):
def __init__(self):
self._trial_ids = set()
def on_trial_start(
self, iteration: int, trials: List["Trial"], trial: "Trial", **info
):
self._trial_ids.add(trial.trial_id)
def get_state(self) -> Optional[Dict]:
return {"trial_ids": self._trial_ids.copy()}
def set_state(self, state: Dict) -> Optional[Dict]:
self._trial_ids = state["trial_ids"]
Returns:
dict: State of the callback. Should be `None` if the callback does not
have any state to save (this is the default).
"""
return None
def set_state(self, state: Dict):
"""Set the state of the callback.
This method should be implemented by subclasses to restore the callback's
state based on the given dict state.
This is used automatically by Tune to restore checkpoint callback state
on :ref:`Tune experiment restoration <tune-experiment-level-fault-tolerance>`.
See :meth:`~ray.tune.Callback.get_state` for an example implementation.
Args:
state: State of the callback.
"""
pass
@DeveloperAPI
| Callback |
python | django-compressor__django-compressor | compressor/tests/test_filters.py | {
"start": 23579,
"end": 25221
} | class ____(TestCase):
"""
Test to check the Specializations of filters.
"""
def test_closure_filter(self):
filter = ClosureCompilerFilter("")
self.assertEqual(
filter.options,
(("binary", str("java -jar compiler.jar")), ("args", str(""))),
)
def test_yuglify_filters(self):
filter = YUglifyCSSFilter("")
self.assertEqual(filter.command, "{binary} {args} --type=css")
self.assertEqual(
filter.options, (("binary", str("yuglify")), ("args", str("--terminal")))
)
filter = YUglifyJSFilter("")
self.assertEqual(filter.command, "{binary} {args} --type=js")
self.assertEqual(
filter.options, (("binary", str("yuglify")), ("args", str("--terminal")))
)
def test_yui_filters(self):
filter = YUICSSFilter("")
self.assertEqual(filter.command, "{binary} {args} --type=css")
self.assertEqual(
filter.options,
(("binary", str("java -jar yuicompressor.jar")), ("args", str(""))),
)
filter = YUIJSFilter("", verbose=1)
self.assertEqual(filter.command, "{binary} {args} --type=js --verbose")
self.assertEqual(
filter.options,
(
("binary", str("java -jar yuicompressor.jar")),
("args", str("")),
("verbose", 1),
),
)
def test_clean_css_filter(self):
filter = CleanCSSFilter("")
self.assertEqual(
filter.options, (("binary", str("cleancss")), ("args", str("")))
)
| SpecializedFiltersTest |
python | crytic__slither | slither/tools/properties/properties/properties.py | {
"start": 483,
"end": 929
} | class ____(NamedTuple): # pylint: disable=inherit-non-class,too-few-public-methods
name: str
content: str
type: PropertyType
return_type: PropertyReturn
is_unit_test: bool
caller: PropertyCaller # Only for unit tests. Echidna will try all the callers
is_property_test: bool
description: str
def property_to_solidity(p: Property):
return f"\tfunction {p.name} public returns(bool){{{p.content}\n\t}}\n"
| Property |
python | scrapy__scrapy | scrapy/http/response/html.py | {
"start": 257,
"end": 300
} | class ____(TextResponse):
pass
| HtmlResponse |
python | pytorch__pytorch | torch/backends/cuda/__init__.py | {
"start": 1711,
"end": 2509
} | class ____:
r"""
Represent a specific plan cache for a specific `device_index`.
The attributes `size` and `max_size`, and method `clear`, can fetch and/ or
change properties of the C++ cuFFT plan cache.
"""
def __init__(self, device_index):
self.device_index = device_index
size = cuFFTPlanCacheAttrContextProp(
torch._cufft_get_plan_cache_size,
".size is a read-only property showing the number of plans currently in the "
"cache. To change the cache capacity, set cufft_plan_cache.max_size.",
)
max_size = cuFFTPlanCacheAttrContextProp(
torch._cufft_get_plan_cache_max_size, torch._cufft_set_plan_cache_max_size
)
def clear(self):
return torch._cufft_clear_plan_cache(self.device_index)
| cuFFTPlanCache |
python | pytorch__pytorch | torch/testing/_internal/opinfo/core.py | {
"start": 1693,
"end": 3688
} | class ____:
"""Describes which test, or type of tests, should be wrapped in the given
decorators when testing an operator. Any test that matches all provided
arguments will be decorated. The decorators will only be applied if the
active_if argument is True."""
__slots__ = [
"decorators",
"cls_name",
"test_name",
"device_type",
"dtypes",
"active_if",
]
def __init__(
self,
decorators,
cls_name=None,
test_name=None,
*,
device_type=None,
dtypes=None,
active_if=True,
):
self.decorators = (
list(decorators)
if isinstance(decorators, collections.abc.Sequence)
else [decorators]
)
self.cls_name = cls_name
self.test_name = test_name
self.device_type = device_type
self.dtypes = dtypes
self.active_if = active_if
# Validate dtypes
if self.dtypes is not None:
for dtype in self.dtypes:
assert isinstance(dtype, torch.dtype)
def is_active(self, cls_name, test_name, device_type, dtype, param_kwargs):
return (
self.active_if
and (self.cls_name is None or self.cls_name == cls_name)
and (self.test_name is None or self.test_name == test_name)
and (self.device_type is None or self.device_type == device_type)
and (self.dtypes is None or dtype in self.dtypes)
# Support callables over kwargs to determine if the decorator is active.
and (
self.active_if(param_kwargs)
if isinstance(self.active_if, Callable)
else self.active_if
)
)
# FIXME
# Note: historically the 'input' kwarg had to be a Tensor or TensorList, but we are trying
# to support scalar inputs, too. Some tests still depend on 'input' being a Tensor
# or TensorList, however.
| DecorateInfo |
python | walkccc__LeetCode | solutions/1522. Diameter of N-Ary Tree/1522.py | {
"start": 0,
"end": 626
} | class ____:
def diameter(self, root: 'Node') -> int:
ans = 0
def maxDepth(root: 'Node') -> int:
"""Returns the maximum depth of the subtree rooted at `root`."""
nonlocal ans
maxSubDepth1 = 0
maxSubDepth2 = 0
for child in root.children:
maxSubDepth = maxDepth(child)
if maxSubDepth > maxSubDepth1:
maxSubDepth2 = maxSubDepth1
maxSubDepth1 = maxSubDepth
elif maxSubDepth > maxSubDepth2:
maxSubDepth2 = maxSubDepth
ans = max(ans, maxSubDepth1 + maxSubDepth2)
return 1 + maxSubDepth1
maxDepth(root)
return ans
| Solution |
python | django__django | tests/admin_views/models.py | {
"start": 4169,
"end": 4229
} | class ____(Color):
class Meta:
proxy = True
| Color2 |
python | langchain-ai__langchain | libs/langchain/tests/mock_servers/robot/server.py | {
"start": 1234,
"end": 1365
} | class ____(str, Enum):
"""The style of walking."""
normal = "normal"
casual = "casual"
energetic = "energetic"
| Style |
python | tartley__colorama | colorama/ansi.py | {
"start": 1789,
"end": 2321
} | class ____(AnsiCodes):
BLACK = 40
RED = 41
GREEN = 42
YELLOW = 43
BLUE = 44
MAGENTA = 45
CYAN = 46
WHITE = 47
RESET = 49
# These are fairly well supported, but not part of the standard.
LIGHTBLACK_EX = 100
LIGHTRED_EX = 101
LIGHTGREEN_EX = 102
LIGHTYELLOW_EX = 103
LIGHTBLUE_EX = 104
LIGHTMAGENTA_EX = 105
LIGHTCYAN_EX = 106
LIGHTWHITE_EX = 107
| AnsiBack |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/resources.py | {
"start": 28312,
"end": 32896
} | class ____(BaseAirbyteWorkspace):
"""This resource allows users to programatically interface with the Airbyte REST API to launch
syncs and monitor their progress for a given Airbyte workspace.
**Examples:**
Using OAuth client credentials:
.. code-block:: python
import dagster as dg
from dagster_airbyte import AirbyteWorkspace, build_airbyte_assets_definitions
airbyte_workspace = AirbyteWorkspace(
rest_api_base_url=dg.EnvVar("AIRBYTE_REST_API_BASE_URL"),
configuration_api_base_url=dg.EnvVar("AIRBYTE_CONFIGURATION_API_BASE_URL"),
workspace_id=dg.EnvVar("AIRBYTE_WORKSPACE_ID"),
client_id=dg.EnvVar("AIRBYTE_CLIENT_ID"),
client_secret=dg.EnvVar("AIRBYTE_CLIENT_SECRET"),
)
all_airbyte_assets = build_airbyte_assets_definitions(workspace=airbyte_workspace)
defs = dg.Definitions(
assets=all_airbyte_assets,
resources={"airbyte": airbyte_workspace},
)
Using basic Authentication:
.. code-block:: python
import dagster as dg
from dagster_airbyte import AirbyteWorkspace, build_airbyte_assets_definitions
airbyte_workspace = AirbyteWorkspace(
rest_api_base_url=dg.EnvVar("AIRBYTE_REST_API_BASE_URL"),
configuration_api_base_url=dg.EnvVar("AIRBYTE_CONFIGURATION_API_BASE_URL"),
workspace_id=dg.EnvVar("AIRBYTE_WORKSPACE_ID"),
username=dg.EnvVar("AIRBYTE_USERNAME"),
password=dg.EnvVar("AIRBYTE_PASSWORD"),
)
all_airbyte_assets = build_airbyte_assets_definitions(workspace=airbyte_workspace)
defs = dg.Definitions(
assets=all_airbyte_assets,
resources={"airbyte": airbyte_workspace},
)
Using no authentication:
.. code-block:: python
import dagster as dg
from dagster_airbyte import AirbyteWorkspace, build_airbyte_assets_definitions
airbyte_workspace = AirbyteWorkspace(
rest_api_base_url=dg.EnvVar("AIRBYTE_REST_API_BASE_URL"),
configuration_api_base_url=dg.EnvVar("AIRBYTE_CONFIGURATION_API_BASE_URL"),
workspace_id=dg.EnvVar("AIRBYTE_WORKSPACE_ID"),
)
all_airbyte_assets = build_airbyte_assets_definitions(workspace=airbyte_workspace)
defs = dg.Definitions(
assets=all_airbyte_assets,
resources={"airbyte": airbyte_workspace},
)
"""
rest_api_base_url: str = Field(
...,
description="The base URL for the Airbyte REST API.",
examples=[
"http://localhost:8000/api/public/v1",
"https://my-airbyte-server.com/api/public/v1",
"http://airbyte-airbyte-server-svc.airbyte.svc.cluster.local:8001/api/public/v1",
],
)
configuration_api_base_url: str = Field(
...,
description="The base URL for the Airbyte Configuration API.",
examples=[
"http://localhost:8000/api/v1",
"https://my-airbyte-server.com/api/v1",
"http://airbyte-airbyte-server-svc.airbyte.svc.cluster.local:8001/api/v1",
],
)
workspace_id: str = Field(..., description="The Airbyte workspace ID")
client_id: Optional[str] = Field(default=None, description="The Airbyte client ID.")
client_secret: Optional[str] = Field(default=None, description="The Airbyte client secret.")
username: Optional[str] = Field(
default=None, description="The Airbyte username for authentication."
)
password: Optional[str] = Field(
default=None, description="The Airbyte password for authentication."
)
@cached_method
def get_client(self) -> AirbyteClient:
return AirbyteClient(
rest_api_base_url=self.rest_api_base_url,
configuration_api_base_url=self.configuration_api_base_url,
workspace_id=self.workspace_id,
client_id=self.client_id,
client_secret=self.client_secret,
username=self.username,
password=self.password,
request_max_retries=self.request_max_retries,
request_retry_delay=self.request_retry_delay,
request_timeout=self.request_timeout,
max_items_per_page=self.max_items_per_page,
poll_interval=self.poll_interval,
poll_timeout=self.poll_timeout,
cancel_on_termination=self.cancel_on_termination,
poll_previous_running_sync=self.poll_previous_running_sync,
)
@beta
| AirbyteWorkspace |
python | kamyu104__LeetCode-Solutions | Python/substrings-of-size-three-with-distinct-characters.py | {
"start": 50,
"end": 527
} | class ____(object):
def countGoodSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
K = 3
result = 0
count = collections.Counter()
for i in xrange(len(s)):
if i >= K:
count[s[i-K]] -= 1
if not count[s[i-K]]:
del count[s[i-K]]
count[s[i]] += 1
if len(count) == K:
result += 1
return result
| Solution |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 1562,
"end": 1855
} | class ____(StrEnum):
"""
ActionFieldMappingKeys is an enum that represents the keys of an action field mapping.
"""
INTEGRATION_ID_KEY = "integration_id_key"
TARGET_IDENTIFIER_KEY = "target_identifier_key"
TARGET_DISPLAY_KEY = "target_display_key"
| ActionFieldMappingKeys |
python | marshmallow-code__marshmallow | src/marshmallow/fields.py | {
"start": 62611,
"end": 64036
} | class ____(Field[ipaddress.IPv4Interface | ipaddress.IPv6Interface]):
"""A IPInterface field.
IP interface is the non-strict form of the IPNetwork type where arbitrary host
addresses are always accepted.
IPAddress and mask e.g. '192.168.0.2/24' or '192.168.0.2/255.255.255.0'
see https://python.readthedocs.io/en/latest/library/ipaddress.html#interface-objects
:param exploded: If `True`, serialize ipv6 interface in long form, ie. with groups
consisting entirely of zeros included.
"""
default_error_messages = {"invalid_ip_interface": "Not a valid IP interface."}
DESERIALIZATION_CLASS: type | None = None
def __init__(self, *, exploded: bool = False, **kwargs: Unpack[_BaseFieldKwargs]):
super().__init__(**kwargs)
self.exploded = exploded
def _serialize(self, value, attr, obj, **kwargs) -> str | None:
if value is None:
return None
if self.exploded:
return value.exploded
return value.compressed
def _deserialize(
self, value, attr, data, **kwargs
) -> ipaddress.IPv4Interface | ipaddress.IPv6Interface:
try:
return (self.DESERIALIZATION_CLASS or ipaddress.ip_interface)(
utils.ensure_text_type(value)
)
except (ValueError, TypeError) as error:
raise self.make_error("invalid_ip_interface") from error
| IPInterface |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/seq2seq_lstm.py | {
"start": 4069,
"end": 5229
} | class ____(nn.Module):
"""LSTM decoder.
Attributes:
init_state: [batch_size, hidden_size]
Initial state of the decoder (i.e., the final state of the encoder).
teacher_force: See docstring on Seq2seq module.
vocab_size: Size of the vocabulary.
"""
init_state: tuple[Any, ...]
teacher_force: bool
vocab_size: int
@nn.compact
def __call__(self, inputs: Array) -> tuple[Array, Array]:
"""Applies the decoder model.
Args:
inputs: [batch_size, max_output_len-1, vocab_size]
Contains the inputs to the decoder at each time step (only used when not
using teacher forcing). Since each token at position i is fed as input
to the decoder at position i+1, the last token is not provided.
Returns:
Pair (logits, predictions), which are two arrays of respectively decoded
logits and predictions (in one hot-encoding format).
"""
lstm = DecoderLSTM(teacher_force=self.teacher_force,
vocab_size=self.vocab_size)
init_carry = (self.init_state, inputs[:, 0])
_, (logits, predictions) = lstm(init_carry, inputs)
return logits, predictions
| Decoder |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass10.py | {
"start": 361,
"end": 404
} | class ____(Generic[T]):
pass
@dataclass
| B |
python | coleifer__peewee | tests/models.py | {
"start": 173807,
"end": 174515
} | class ____(ModelTestCase):
database = get_in_memory_db()
requires = [Person]
def test_column_name_stripping(self):
d1 = datetime.date(1990, 1, 1)
d2 = datetime.date(1990, 1, 1)
p1 = Person.create(first='f1', last='l1', dob=d1)
p2 = Person.create(first='f2', last='l2', dob=d2)
query = Person.select(
fn.MIN(Person.dob),
fn.MAX(Person.dob).alias('mdob'))
# Get the row as a model.
row = query.get()
self.assertEqual(row.dob, d1)
self.assertEqual(row.mdob, d2)
row = query.dicts().get()
self.assertEqual(row['dob'], d1)
self.assertEqual(row['mdob'], d2)
| TestColumnNameStripping |
python | keras-team__keras | keras/src/losses/losses.py | {
"start": 6499,
"end": 8162
} | class ____(LossFunctionWrapper):
"""Computes the mean squared logarithmic error between `y_true` & `y_pred`.
Formula:
```python
loss = mean(square(log(y_true + 1) - log(y_pred + 1)))
```
Args:
reduction: Type of reduction to apply to the loss. In almost all cases
this should be `"sum_over_batch_size"`. Supported options are
`"sum"`, `"sum_over_batch_size"`, `"mean"`,
`"mean_with_sample_weight"` or `None`. `"sum"` sums the loss,
`"sum_over_batch_size"` and `"mean"` sum the loss and divide by the
sample size, and `"mean_with_sample_weight"` sums the loss and
divides by the sum of the sample weights. `"none"` and `None`
perform no aggregation. Defaults to `"sum_over_batch_size"`.
name: Optional name for the loss instance.
dtype: The dtype of the loss's computations. Defaults to `None`, which
means using `keras.backend.floatx()`. `keras.backend.floatx()` is a
`"float32"` unless set to different value
(via `keras.backend.set_floatx()`). If a `keras.DTypePolicy` is
provided, then the `compute_dtype` will be utilized.
"""
def __init__(
self,
reduction="sum_over_batch_size",
name="mean_squared_logarithmic_error",
dtype=None,
):
super().__init__(
mean_squared_logarithmic_error,
name=name,
reduction=reduction,
dtype=dtype,
)
def get_config(self):
return Loss.get_config(self)
@keras_export("keras.losses.CosineSimilarity")
| MeanSquaredLogarithmicError |
python | pytorch__pytorch | test/nn/test_load_state_dict.py | {
"start": 489,
"end": 20321
} | class ____(NNTestCase):
_do_cuda_memory_leak_check = True
_do_cuda_non_default_stream = True
@unittest.skipIf(not TEST_NUMPY, "numpy not found")
@swap([True, False])
def test_load_state_dict_invalid(self):
m = torch.nn.Linear(2, 2, bias=False)
state_dict = {"weight": np.random.randn(2, 2)}
with self.assertRaisesRegex(
RuntimeError,
"expected torch.Tensor or Tensor-like object from checkpoint but received",
):
m.load_state_dict(state_dict)
state_dict = {"weight": ((1.0, 1.0), (2.0, 2.0))}
with self.assertRaisesRegex(
RuntimeError,
"expected torch.Tensor or Tensor-like object from checkpoint but received",
):
m.load_state_dict(state_dict)
@swap([True, False])
def test_load_state_dict_type(self):
m = nn.Module()
with self.assertRaisesRegex(
TypeError, "Expected state_dict to be dict-like, got"
):
m.load_state_dict("")
with self.assertRaisesRegex(
TypeError, "Expected state_dict to be dict-like, got"
):
m.load_state_dict(2)
@swap([True, False])
@skipIfTorchDynamo("dynamo installs weakrefs on some params")
def test_scalar_param_1d_tensor_raises(self):
class SimpleModule(nn.Module):
def __init__(self):
super().__init__()
self.threshold = nn.Parameter(torch.tensor(0.0))
def forward(self, x):
return x
m = SimpleModule()
# Test that [3] -> scalar raises error
sd = {"threshold": torch.randn(3)}
with self.assertRaisesRegex(RuntimeError, "size mismatch for threshold"):
m.load_state_dict(sd)
# Test that [1] -> scalar is allowed (backward compatibility)
sd = {"threshold": torch.tensor([1.0])}
m.load_state_dict(sd)
self.assertEqual(m.threshold.item(), 1.0)
@swap([True, False])
@skipIfTorchDynamo("dynamo installs weakrefs on some params")
def test_load_state_dict(self):
l = nn.Linear(5, 5)
block = nn.Module()
block.conv1 = nn.Conv2d(3, 3, 3, bias=True)
block.conv2 = nn.Conv2d(3, 3, 3, bias=False)
net = nn.Module()
net.linear1 = l
net.linear2 = l
net.bn = nn.BatchNorm2d(2)
net.block = block
net.add_module("empty", None)
conv1_bias_dtype = block.conv1.bias.dtype
state_dict = net.state_dict()
state_dict.update(
{
"linear1.weight": torch.ones(5, 5),
"block.conv1.bias": torch.arange(1, 4, dtype=conv1_bias_dtype),
"bn.running_mean": torch.randn(2),
}
)
# Also test if a DDP state_dict can be loaded from a local model.
ddp_state_dict = net.state_dict()
ddp_state_dict.update(
{
"module.linear1.weight": torch.ones(5, 5),
"module.block.conv1.bias": torch.arange(1, 4, dtype=conv1_bias_dtype),
"module.bn.running_mean": torch.randn(2),
}
)
torch.nn.modules.utils.consume_prefix_in_state_dict_if_present(
ddp_state_dict, "module."
)
for sd in [state_dict, ddp_state_dict]:
incompatible_keys = net.load_state_dict(sd)
self.assertEqual(len(incompatible_keys.missing_keys), 0)
self.assertEqual(len(incompatible_keys.unexpected_keys), 0)
self.assertNotIn("Incompatible", str(incompatible_keys))
self.assertEqual(net.linear1.weight, sd["linear1.weight"])
self.assertEqual(net.block.conv1.bias, sd["block.conv1.bias"])
self.assertEqual(net.bn.running_mean, sd["bn.running_mean"])
state_dict = net.state_dict()
state_dict.update({"extra": torch.ones(5)})
self.assertRaises(RuntimeError, lambda: net.load_state_dict(state_dict))
incompatible_keys = net.load_state_dict(state_dict, strict=False)
self.assertEqual(len(incompatible_keys.missing_keys), 0)
self.assertEqual(len(incompatible_keys.unexpected_keys), 1)
self.assertIn("extra", incompatible_keys.unexpected_keys)
self.assertIn("Incompatible", str(incompatible_keys))
state_dict = net.state_dict()
state_dict.update({"extra.param": torch.ones(5)})
self.assertRaises(RuntimeError, lambda: net.load_state_dict(state_dict))
incompatible_keys = net.load_state_dict(state_dict, strict=False)
self.assertEqual(len(incompatible_keys.missing_keys), 0)
self.assertEqual(len(incompatible_keys.unexpected_keys), 1)
self.assertIn("extra.param", incompatible_keys.unexpected_keys)
state_dict = net.state_dict()
del state_dict["linear1.weight"]
self.assertRaises(RuntimeError, lambda: net.load_state_dict(state_dict))
incompatible_keys = net.load_state_dict(state_dict, strict=False)
self.assertEqual(len(incompatible_keys.missing_keys), 1)
self.assertEqual(len(incompatible_keys.unexpected_keys), 0)
self.assertIn("linear1.weight", incompatible_keys.missing_keys)
state_dict.update({"extra.param": torch.ones(5)})
self.assertRaises(RuntimeError, lambda: net.load_state_dict(state_dict))
incompatible_keys = net.load_state_dict(state_dict, strict=False)
self.assertEqual(len(incompatible_keys.missing_keys), 1)
self.assertEqual(len(incompatible_keys.unexpected_keys), 1)
self.assertIn("linear1.weight", incompatible_keys.missing_keys)
self.assertIn("extra.param", incompatible_keys.unexpected_keys)
state_dict = net.state_dict()
state_dict.update({"bn.running_mean": torch.rand(14, 4)}) # wrong size
self.assertRaises(RuntimeError, lambda: net.load_state_dict(state_dict))
self.assertRaises(
RuntimeError, lambda: net.load_state_dict(state_dict, strict=False)
)
state_dict = net.state_dict()
old_state_dict = deepcopy(state_dict)
state_dict = {
"linear1.weight": torch.ones(5, 5),
"block.conv1.bias": torch.arange(1, 4, dtype=conv1_bias_dtype),
"bn.running_mean": torch.randn(2),
"nonexistent_key": torch.rand(3),
}
net.load_state_dict(state_dict, strict=False)
self.assertEqual(net.linear1.weight, state_dict["linear1.weight"])
self.assertEqual(net.block.conv1.bias, state_dict["block.conv1.bias"])
self.assertEqual(net.bn.running_mean, state_dict["bn.running_mean"])
new_state_dict = net.state_dict()
del old_state_dict["linear1.weight"]
del old_state_dict["block.conv1.bias"]
del old_state_dict["bn.running_mean"]
for (
k,
v,
) in old_state_dict.items():
self.assertTrue(v.equal(new_state_dict[k]))
@swap([True, False])
def test_load_state_dict_BC(self):
# BatchNormNd
# Added num_batches_tracked buffer at version 2. For state dict with
# earlier versions or no versions, it should provide default value of 0.
bn = nn.BatchNorm2d(3)
state_dict = bn.state_dict()
del state_dict["num_batches_tracked"]
state_dict._metadata[""]["version"] = 1 # version 1
bn.load_state_dict(state_dict)
self.assertEqual(bn.num_batches_tracked.dtype, torch.long)
self.assertEqual(bn.num_batches_tracked.item(), 0)
del state_dict._metadata[""]["version"] # no version
bn.load_state_dict(state_dict)
self.assertEqual(bn.num_batches_tracked.dtype, torch.long)
self.assertEqual(bn.num_batches_tracked.item(), 0)
@swap([True, False])
def test_load_state_dict_child(self):
base_module = nn.Linear(1, 1)
model = base_module
for _ in range(3):
model = nn.Sequential(*[deepcopy(model) for _ in range(10)])
def hook_fn(
module,
state_dict,
prefix,
local_metadata,
strict,
missing_keys,
unexpected_keys,
error_msgs,
):
module_state_dict = module.state_dict()
self.assertEqual(len(module_state_dict.keys()), len(state_dict.keys()))
model[0][0].register_load_state_dict_pre_hook(hook_fn)
model.load_state_dict(model.state_dict(), strict=True)
# fails swapping as LSTM installs weak references on the parameters
@swap([False])
@skipIfTorchDynamo("TorchDynamo fails here for unknown reasons")
def test_load_state_dict_ref_cycle(self):
# load_state_dict shouldn't cause a reference cycle involving Tensors
import gc
m = torch.nn.LSTM(16, 16, bidirectional=True)
gc.collect()
m.load_state_dict(deepcopy(m).state_dict())
refcycles = gc.collect()
self.assertEqual(refcycles, 0)
@swap([True, False])
def test_load_state_dict_custom(self):
class CustomState(nn.Module):
def __init__(self) -> None:
super().__init__()
self.param = torch.nn.Parameter(torch.ones(1))
self.sub = torch.nn.Linear(5, 5)
def _save_to_state_dict(self, destination, prefix, keep_vars):
destination[prefix + "serialized"] = self.param.data + 1
def _load_from_state_dict(
self,
state_dict,
prefix,
local_metadata,
strict,
missing_keys,
unexpected_keys,
error_msgs,
):
# skip some of the error handling
self.param.data.copy_(state_dict[prefix + "serialized"] - 1)
# use sequential to verify nesting
m = nn.Sequential(CustomState())
with torch.no_grad():
m[0].param[0] = 10
m[0].sub.weight[0, 0] = 555
state_dict = m.state_dict()
self.assertEqual(state_dict["0.serialized"].item(), 11)
self.assertIn("0.sub.weight", state_dict)
self.assertNotIn("0.param", state_dict)
del m
mm = nn.Sequential(CustomState())
self.assertEqual(mm[0].param[0].item(), 1)
mm.load_state_dict(state_dict)
self.assertEqual(mm[0].param[0].item(), 10)
self.assertEqual(mm[0].sub.weight[0, 0].item(), 555)
@swap([True, False])
@parametrize("keep_vars", [True, False])
def test_load_state_dict_assign_meta(self, keep_vars):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = nn.Linear(3, 5)
self.bn = nn.BatchNorm1d(5)
self.x = nn.Parameter(torch.rand(5), requires_grad=False)
def forward(self, input):
return self.x + self.bn(self.fc1(input))
swap = torch.__future__.get_swap_module_params_on_conversion()
net = MyModule()
state_dict = net.state_dict(keep_vars=keep_vars)
for v in state_dict.values():
v.requires_grad_(False)
with torch.device("meta"):
net_meta = MyModule()
net_meta_state_dict_old = net_meta.state_dict(keep_vars=True)
net_meta.load_state_dict(state_dict, assign=True)
# Make sure parameters and persistent buffers were assigned
net_meta_state_dict = net_meta.state_dict(keep_vars=True)
for key in state_dict:
if key in net_meta._parameters:
if keep_vars and not swap:
# state_dict[key] is an nn.Parameter
self.assertTrue(state_dict[key] is net_meta_state_dict[key])
else:
if swap:
self.assertTrue(
net_meta_state_dict[key] is net_meta_state_dict_old[key]
)
else:
# state_dict[key] is not an nn.Parameter so it will be detached when wrapping with a Parameter
self.assertTrue(
net_meta_state_dict[key] is not net_meta_state_dict_old[key]
)
self.assertEqual(
net_meta_state_dict_old[key].requires_grad,
net_meta_state_dict[key].requires_grad,
)
self.assertEqual(
net_meta_state_dict_old[key].requires_grad,
net_meta_state_dict[key].requires_grad,
)
self.assertEqual(state_dict[key], net_meta_state_dict[key])
elif (
key in net_meta._buffers
and key not in net_meta._non_persistent_buffers_set
):
self.assertTrue(state_dict[key] is net_meta_state_dict[key])
self.assertEqual(state_dict[key], net_meta_state_dict[key])
# Make sure that ordering of parameters and buffers is preserved
net_named_parameters = net.named_parameters()
net_named_buffers = net.named_buffers()
net_meta_named_parameters = net_meta.named_parameters()
net_meta_named_buffers = net_meta.named_buffers()
for (n1, _), (n2, _) in zip(net_named_parameters, net_meta_named_parameters):
self.assertEqual(n1, n2)
for (n1, _), (n2, _) in zip(net_named_buffers, net_meta_named_buffers):
self.assertEqual(n1, n2)
# Make sure outputs are the same
t = torch.randn(4, 3)
out_net = net(t)
out_net_meta = net_meta(t.clone())
self.assertEqual(out_net, out_net_meta)
@swap([True, False])
def test_load_state_dict_assign_with_optimizer(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = nn.Linear(3, 5)
self.bn = nn.BatchNorm1d(5)
def forward(self, input):
return self.bn(self.fc1(input))
net = MyModule()
opt = torch.optim.Adam(net.parameters(), lr=1000)
x = torch.randn(4, 3)
num_iters = 3
for _ in range(num_iters):
opt.zero_grad()
out = net(x)
out.sum().backward()
opt.step()
opt_state_dict = deepcopy(opt.state_dict())
net_state_dict = deepcopy(net.state_dict())
with torch.device("meta"):
net_meta = MyModule()
net_meta.load_state_dict(net_state_dict, assign=True)
# must create optimizer only after loading state_dict when assign=True
opt2 = torch.optim.Adam(net_meta.parameters(), lr=1000)
opt2.load_state_dict(opt_state_dict)
y = x.clone()
for _ in range(num_iters):
opt.zero_grad()
out = net(x)
out.sum().backward()
opt.step()
opt2.zero_grad()
out2 = net_meta(y)
out2.sum().backward()
opt2.step()
self.assertEqual(opt.state_dict(), opt2.state_dict())
self.assertEqual(net.state_dict(), net_meta.state_dict())
@swap([True, False])
def test_load_state_dict_assign_shape_stride(self):
# Assigned tensor is allowed to have different properties than initial
# tensor except for shape
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = nn.Linear(3, 5)
self.bn = nn.BatchNorm1d(5)
def forward(self, input):
return self.bn(self.fc1(input))
net = MyModule()
state_dict = net.state_dict()
# loading should be ok if stride is different
state_dict["fc1.weight"] = torch.randn(3, 5).transpose(0, 1)
net2 = MyModule()
net2.load_state_dict(state_dict, strict=False, assign=True)
state_dict["fc1.weight"] = torch.randn(2, 4)
with self.assertRaisesRegex(
RuntimeError, "size mismatch for fc1.weight: copying a param with shape"
):
net2.load_state_dict(state_dict, strict=False, assign=True)
@swap([True, False])
def test_load_state_dict_warn_assign(self):
with torch.device("meta"):
m = torch.nn.Linear(3, 5)
state_dict = m.state_dict()
state_dict["weight"] = torch.empty_like(state_dict["weight"], device="cpu")
with self.assertWarnsRegex(
UserWarning,
"for weight: copying from a non-meta parameter in the checkpoint to a meta",
):
m.load_state_dict(state_dict)
@swap([True, False])
def test_load_state_dict_with_unexpected_key(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = torch.nn.Linear(5, 10)
m = MyModule()
# Unexpected key & strict = True
with self.assertRaisesRegex(RuntimeError, "Unexpected key"):
state_dict = m.state_dict()
state_dict["fc1.bad_suffix"] = torch.randn(5, 10)
m.load_state_dict(state_dict)
# Unexpected key & strict = False
state_dict = m.load_state_dict(state_dict, strict=False)
self.assertIn("fc1.bad_suffix", state_dict.unexpected_keys)
# Unexpected key whose prefix matches a valid key & strict = True
with self.assertRaisesRegex(RuntimeError, "Unexpected key"):
state_dict = m.state_dict()
state_dict["fc1.weight.bad_suffix"] = torch.randn(5, 10)
m.load_state_dict(state_dict)
# Unexpected key whose prefix matches a valid key & strict = False
state_dict = m.load_state_dict(state_dict, strict=False)
self.assertIn("fc1.weight.bad_suffix", state_dict.unexpected_keys)
def load_torch_function_handler(cls, func, types, args=(), kwargs=None):
kwargs = {} if kwargs is None else kwargs
def module_load(dest, src, assign=False):
if isinstance(dest, cls):
if assign:
return src.detach()
else:
if type(src) is torch.Tensor:
return cls(src)
elif type(src) is cls:
return src.detach()
else:
if isinstance(src, MyWrapperLoadTensor):
return cls(src._data)
return cls(src)
else:
assert isinstance(src, cls), (
f"Expected isinstance(src, {cls}) but got {type(src)}"
)
assert (
type(dest) is torch.Tensor
or type(dest) is torch.nn.Parameter
or issubclass(cls, type(dest))
)
if assign:
return src.detach()
else:
if isinstance(src, MyWrapperLoadTensor):
if type(dest) not in {torch.Tensor, torch.nn.Parameter}:
return type(dest)(src._data)
else:
return src._data.detach()
else:
return torch.Tensor(src)
if func is torch.Tensor.module_load:
return module_load(*args, **kwargs)
else:
with torch._C.DisableTorchFunctionSubclass():
# detach must return instance of same subclass for nn.Parameter()
if func == torch.Tensor.detach:
ret = func(*args, **kwargs)
if not isinstance(ret, cls):
return cls(ret)
return ret
return func(*args, **kwargs)
| TestLoadStateDict |
python | tensorflow__tensorflow | tensorflow/python/distribute/collective_all_reduce_strategy_test.py | {
"start": 11642,
"end": 17316
} | class ____(
CollectiveAllReduceStrategyTestBase,
strategy_test_lib.DistributionTestBase,
parameterized.TestCase):
@classmethod
def setUpClass(cls):
"""Create a local cluster with 3 workers."""
cls._cluster_spec = multi_worker_test_base.create_in_process_cluster(
num_workers=3, num_ps=0)
@combinations.generate(combinations.combine(mode=['graph']))
def test_num_replicas_in_sync(self):
distribution, _ = create_test_objects(
cluster_spec=self._cluster_spec,
task_type='worker',
task_id=0,
num_gpus=2)
num_workers = len(self._cluster_spec.get('chief', []) +
self._cluster_spec.get('worker', []))
self.assertEqual(2 * num_workers,
distribution.num_replicas_in_sync)
@combinations.generate(combinations.combine(
mode=['graph'],
prefetch_to_device=[None, True]))
def test_prefetch_to_device_dataset(self, prefetch_to_device):
distribution, _ = self._get_test_object(
task_type='worker', task_id=0, num_gpus=2)
if prefetch_to_device is None:
input_options = None
else:
input_options = distribute_lib.InputOptions(
experimental_fetch_to_device=prefetch_to_device)
dataset = dataset_ops.Dataset.range(100)
dataset = dataset.batch(distribution.num_replicas_in_sync)
dataset = distribution.experimental_distribute_dataset(
dataset, options=input_options)
if isinstance(dataset, input_lib_v1.DistributedDatasetV1):
item = dataset.make_initializable_iterator().get_next()
else:
self.skipTest('unsupported test combination')
device_types = {
tf_device.DeviceSpec.from_string(tensor.device).device_type for
tensor in item.values}
self.assertAllEqual(list(device_types), ['GPU'])
@combinations.generate(combinations.combine(mode=['graph']))
def test_prefetch_to_host_dataset(self):
distribution, _ = self._get_test_object(
task_type='worker', task_id=0, num_gpus=2)
input_options = distribute_lib.InputOptions(
experimental_fetch_to_device=False)
dataset = dataset_ops.Dataset.range(100)
dataset = dataset.batch(distribution.num_replicas_in_sync)
dataset = distribution.experimental_distribute_dataset(
dataset, options=input_options)
if isinstance(dataset, input_lib_v1.DistributedDatasetV1):
item = dataset.make_initializable_iterator().get_next()
else:
self.skipTest('unsupported test combination')
device_types = {
tf_device.DeviceSpec.from_string(tensor.device).device_type for
tensor in item.values}
self.assertAllEqual(list(device_types), ['CPU'])
@combinations.generate(
combinations.combine(mode=['graph'], required_gpus=[0, 1, 2]))
def testMinimizeLossGraph(self, required_gpus):
self._run_between_graph_clients(self._test_minimize_loss_graph,
self._cluster_spec, required_gpus)
@combinations.generate(
combinations.combine(mode=['graph'], required_gpus=[0, 1, 2]))
def testVariableInitialization(self, required_gpus):
self._run_between_graph_clients(
self._test_variable_initialization,
self._cluster_spec,
num_gpus=required_gpus)
@combinations.generate(
combinations.combine(
mode=['graph'], required_gpus=[0, 1, 2], use_dataset=[True, False]))
def testMakeInputFnIterator(self, required_gpus, use_dataset):
def _worker_fn(task_type, task_id, required_gpus):
if use_dataset:
fn = lambda: dataset_ops.Dataset.range(20)
else:
def fn():
dataset = dataset_ops.Dataset.range(20)
it = dataset_ops.make_one_shot_iterator(dataset)
return it.get_next
# We use CPU as the device when required_gpus = 0
devices_per_worker = max(1, required_gpus)
expected_values = [[i+j for j in range(devices_per_worker)]
for i in range(0, 20, devices_per_worker)]
input_fn = self._input_fn_to_test_input_context(
fn,
expected_num_replicas_in_sync=3*devices_per_worker,
expected_num_input_pipelines=3,
expected_input_pipeline_id=task_id)
self._test_input_fn_iterator(
task_type,
task_id,
required_gpus,
input_fn,
expected_values,
test_reinitialize=use_dataset,
ignore_order=not use_dataset)
self._run_between_graph_clients(_worker_fn, self._cluster_spec,
required_gpus)
@combinations.generate(combinations.combine(mode=['graph']))
def testUpdateConfigProto(self):
strategy, _ = self._get_test_object(
task_type='worker', task_id=1, num_gpus=2)
config_proto = config_pb2.ConfigProto(device_filters=['to_be_overridden'])
rewrite_options = config_proto.graph_options.rewrite_options
rewrite_options.scoped_allocator_opts.enable_op.append('to_be_removed')
new_config = strategy.update_config_proto(config_proto)
# Verify group leader
self.assertEqual('/job:worker/replica:0/task:0',
new_config.experimental.collective_group_leader)
# Verify device filters.
self.assertEqual(['/job:worker/task:1'], new_config.device_filters)
# Verify rewrite options.
new_rewrite_options = new_config.graph_options.rewrite_options
self.assertEqual(rewriter_config_pb2.RewriterConfig.ON,
new_rewrite_options.scoped_allocator_optimization)
self.assertEqual(['CollectiveReduce'],
new_rewrite_options.scoped_allocator_opts.enable_op)
| DistributedCollectiveAllReduceStrategyTest |
python | huggingface__transformers | src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py | {
"start": 4942,
"end": 5982
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, attn_implementation: str = "sdpa") -> None:
super().__init__()
self.norm1 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
self.norm2 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
self.attn = Qwen2_5_VLVisionAttention(config=config)
self.mlp = Qwen2_5_VLMLP(config, bias=True)
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.Tensor,
rotary_pos_emb: Optional[torch.Tensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs,
) -> torch.Tensor:
hidden_states = hidden_states + self.attn(
self.norm1(hidden_states),
cu_seqlens=cu_seqlens,
rotary_pos_emb=rotary_pos_emb,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
return hidden_states
| Qwen2_5_VLVisionBlock |
python | scipy__scipy | scipy/integrate/_rules/_genz_malik.py | {
"start": 184,
"end": 7308
} | class ____(NestedFixedRule):
"""
Genz-Malik cubature.
Genz-Malik is only defined for integrals of dimension >= 2.
Parameters
----------
ndim : int
The spatial dimension of the integrand.
xp : array_namespace, optional
The namespace for the node and weight arrays. Default is None, where NumPy is
used.
Attributes
----------
higher : Cubature
Higher-order rule.
lower : Cubature
Lower-order rule.
References
----------
.. [1] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
numerical integration over an N-dimensional rectangular region, Journal of
Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
ISSN 0377-0427, https://doi.org/10.1016/0771-050X(80)90039-X.
Examples
--------
Evaluate a 3D integral:
>>> import numpy as np
>>> from scipy.integrate import cubature
>>> from scipy.integrate._rules import GenzMalikCubature
>>> def f(x):
... # f(x) = cos(x_1) + cos(x_2) + cos(x_3)
... return np.sum(np.cos(x), axis=-1)
>>> rule = GenzMalikCubature(3) # Use 3D Genz-Malik
>>> a, b = np.array([0, 0, 0]), np.array([1, 1, 1])
>>> rule.estimate(f, a, b) # True value 3*sin(1), approximately 2.5244
np.float64(2.5244129547230862)
>>> rule.estimate_error(f, a, b)
np.float64(1.378269656626685e-06)
"""
def __init__(self, ndim, degree=7, lower_degree=5, xp=None):
if ndim < 2:
raise ValueError("Genz-Malik cubature is only defined for ndim >= 2")
if degree != 7 or lower_degree != 5:
raise NotImplementedError("Genz-Malik cubature is currently only supported"
"for degree=7, lower_degree=5")
self.ndim = ndim
self.degree = degree
self.lower_degree = lower_degree
if xp is None:
xp = np_compat
self.xp = array_namespace(xp.empty(0))
@cached_property
def nodes_and_weights(self):
# TODO: Currently only support for degree 7 Genz-Malik cubature, should aim to
# support arbitrary degree
l_2 = math.sqrt(9/70)
l_3 = math.sqrt(9/10)
l_4 = math.sqrt(9/10)
l_5 = math.sqrt(9/19)
its = itertools.chain(
[(0,) * self.ndim],
_distinct_permutations((l_2,) + (0,) * (self.ndim - 1)),
_distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)),
_distinct_permutations((l_3,) + (0,) * (self.ndim - 1)),
_distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)),
_distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)),
_distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)),
_distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)),
itertools.product((l_5, -l_5), repeat=self.ndim),
)
nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim) + 2**self.ndim
nodes = self.xp.asarray(
list(zip(*its)),
dtype=self.xp.float64,
)
nodes = self.xp.reshape(nodes, (self.ndim, nodes_size))
# It's convenient to generate the nodes as a sequence of evaluation points
# as an array of shape (npoints, ndim), but nodes needs to have shape
# (ndim, npoints)
nodes = nodes.T
w_1 = (
(2**self.ndim) * (12824 - 9120*self.ndim + (400 * self.ndim**2)) / 19683
)
w_2 = (2**self.ndim) * 980/6561
w_3 = (2**self.ndim) * (1820 - 400 * self.ndim) / 19683
w_4 = (2**self.ndim) * (200 / 19683)
w_5 = 6859 / 19683
weights = self.xp.concat([
self.xp.asarray([w_1] * 1, dtype=self.xp.float64),
self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64),
self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64),
self.xp.asarray(
[w_4] * (2 * (self.ndim - 1) * self.ndim),
dtype=self.xp.float64,
),
self.xp.asarray([w_5] * (2**self.ndim), dtype=self.xp.float64),
])
return nodes, weights
@cached_property
def lower_nodes_and_weights(self):
# TODO: Currently only support for the degree 5 lower rule, in the future it
# would be worth supporting arbitrary degree
# Nodes are almost the same as the full rule, but there are no nodes
# corresponding to l_5.
l_2 = math.sqrt(9/70)
l_3 = math.sqrt(9/10)
l_4 = math.sqrt(9/10)
its = itertools.chain(
[(0,) * self.ndim],
_distinct_permutations((l_2,) + (0,) * (self.ndim - 1)),
_distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)),
_distinct_permutations((l_3,) + (0,) * (self.ndim - 1)),
_distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)),
_distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)),
_distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)),
_distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)),
)
nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim)
nodes = self.xp.asarray(list(zip(*its)), dtype=self.xp.float64)
nodes = self.xp.reshape(nodes, (self.ndim, nodes_size))
nodes = nodes.T
# Weights are different from those in the full rule.
w_1 = (2**self.ndim) * (729 - 950*self.ndim + 50*self.ndim**2) / 729
w_2 = (2**self.ndim) * (245 / 486)
w_3 = (2**self.ndim) * (265 - 100*self.ndim) / 1458
w_4 = (2**self.ndim) * (25 / 729)
weights = self.xp.concat([
self.xp.asarray([w_1] * 1, dtype=self.xp.float64),
self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64),
self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64),
self.xp.asarray(
[w_4] * (2 * (self.ndim - 1) * self.ndim),
dtype=self.xp.float64,
),
])
return nodes, weights
def _distinct_permutations(iterable):
"""
Find the number of distinct permutations of elements of `iterable`.
"""
# Algorithm: https://w.wiki/Qai
items = sorted(iterable)
size = len(items)
while True:
# Yield the permutation we have
yield tuple(items)
# Find the largest index i such that A[i] < A[i + 1]
for i in range(size - 2, -1, -1):
if items[i] < items[i + 1]:
break
# If no such index exists, this permutation is the last one
else:
return
# Find the largest index j greater than j such that A[i] < A[j]
for j in range(size - 1, i, -1):
if items[i] < items[j]:
break
# Swap the value of A[i] with that of A[j], then reverse the
# sequence from A[i + 1] to form the new permutation
items[i], items[j] = items[j], items[i]
items[i+1:] = items[:i-size:-1] # A[i + 1:][::-1]
| GenzMalikCubature |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vector_index.py | {
"start": 1342,
"end": 1567
} | class ____(_MultiVectorEncodingConfigCreate):
ksim: Optional[int]
dprojections: Optional[int]
repetitions: Optional[int]
@staticmethod
def encoding_name() -> str:
return "muvera"
| _MuveraConfigCreate |
python | django-debug-toolbar__django-debug-toolbar | debug_toolbar/panels/__init__.py | {
"start": 300,
"end": 9438
} | class ____:
"""
Base class for panels.
"""
is_async = False
def __init__(self, toolbar, get_response: GetResponse):
self.toolbar = toolbar
self.get_response = get_response
self.from_store = False
# Private panel properties
@classproperty
def panel_id(cls):
return cls.__name__
@property
def enabled(self) -> bool:
# Check if the panel is async compatible
if not self.is_async and isinstance(self.toolbar.request, ASGIRequest):
return False
if self.from_store:
# If the toolbar was loaded from the store the existence of
# recorded data indicates whether it was enabled or not.
# We can't use the remainder of the logic since we don't have
# a request to work off of.
return bool(self.get_stats())
# The user's cookies should override the default value
cookie_value = self.toolbar.request.COOKIES.get("djdt" + self.panel_id)
if cookie_value is not None:
return cookie_value == "on"
# Check to see if settings has a default value for it
disabled_panels = dt_settings.get_config()["DISABLE_PANELS"]
panel_path = get_name_from_obj(self)
# Some panels such as the SQLPanel and TemplatesPanel exist in a
# panel module, but can be disabled without panel in the path.
# For that reason, replace .panel. in the path and check for that
# value in the disabled panels as well.
return (
panel_path not in disabled_panels
and panel_path.replace(".panel.", ".") not in disabled_panels
)
# Titles and content
@property
def nav_title(self):
"""
Title shown in the side bar. Defaults to :attr:`title`.
"""
return self.title
@property
def nav_subtitle(self):
"""
Subtitle shown in the side bar. Defaults to the empty string.
"""
return ""
@property
def has_content(self):
"""
``True`` if the panel can be displayed in full screen, ``False`` if
it's only shown in the side bar. Defaults to ``True``.
"""
return True
@property
def is_historical(self):
"""
Panel supports rendering historical values.
Defaults to :attr:`has_content`.
"""
return self.has_content
@property
def title(self):
"""
Title shown in the panel when it's displayed in full screen.
Mandatory, unless the panel sets :attr:`has_content` to ``False``.
"""
raise NotImplementedError
@property
def template(self):
"""
Template used to render :attr:`content`.
Mandatory, unless the panel sets :attr:`has_content` to ``False`` or
overrides :attr:`content`.
"""
raise NotImplementedError
@property
def content(self):
"""
Content of the panel when it's displayed in full screen.
By default this renders the template defined by :attr:`template`.
Statistics stored with :meth:`record_stats` are available in the
template's context.
"""
if self.has_content:
return render_to_string(self.template, self.get_stats())
@property
def scripts(self):
"""
Scripts used by the HTML content of the panel when it's displayed.
When a panel is rendered on the frontend, the ``djdt.panel.render``
JavaScript event will be dispatched. The scripts can listen for
this event to support dynamic functionality.
"""
return []
# Panel early initialization
@classmethod
def ready(cls):
"""
Perform early initialization for the panel.
This should only include initialization or instrumentation that needs to
be done unconditionally for the panel regardless of whether it is
enabled for a particular request. It should be idempotent.
"""
# URLs for panel-specific views
@classmethod
def get_urls(cls):
"""
Return URLpatterns, if the panel has its own views.
"""
return []
# Enable and disable (expensive) instrumentation, must be idempotent
def enable_instrumentation(self):
"""
Enable instrumentation to gather data for this panel.
This usually means monkey-patching (!) or registering signal
receivers. Any instrumentation with a non-negligible effect on
performance should be installed by this method rather than at import
time.
Unless the toolbar or this panel is disabled, this method will be
called early in ``DebugToolbarMiddleware``. It should be idempotent.
Add the ``aenable_instrumentation`` method to a panel subclass
to support async logic for instrumentation.
"""
def disable_instrumentation(self):
"""
Disable instrumentation to gather data for this panel.
This is the opposite of :meth:`enable_instrumentation`.
Unless the toolbar or this panel is disabled, this method will be
called late in the middleware. It should be idempotent.
"""
# Store and retrieve stats (shared between panels for no good reason)
def record_stats(self, stats):
"""
Store data gathered by the panel. ``stats`` is a :class:`dict`.
Each call to ``record_stats`` updates the store's data for
the panel.
To support backwards compatibility, it will also update the
panel's statistics dictionary.
"""
self.toolbar.stats.setdefault(self.panel_id, {}).update(stats)
self.toolbar.store.save_panel(
self.toolbar.request_id, self.panel_id, self.toolbar.stats[self.panel_id]
)
def get_stats(self):
"""
Access data stored by the panel. Returns a :class:`dict`.
"""
return self.toolbar.stats.get(self.panel_id, {})
def record_server_timing(self, key, title, value):
"""
Store data gathered by the panel. ``stats`` is a :class:`dict`.
Each call to ``record_stats`` updates the statistics dictionary.
"""
data = {key: {"title": title, "value": value}}
self.toolbar.server_timing_stats.setdefault(self.panel_id, {}).update(data)
def get_server_timing_stats(self):
"""
Access data stored by the panel. Returns a :class:`dict`.
"""
return self.toolbar.server_timing_stats.get(self.panel_id, {})
# Standard middleware methods
def process_request(self, request):
"""
Like __call__ in Django's middleware.
Write panel logic related to the request there. Save data with
:meth:`record_stats`.
Return the existing response or overwrite it.
"""
return self.get_response(request)
def get_headers(self, request):
"""
Get headers the panel needs to set.
Called after :meth:`process_request
<debug_toolbar.panels.Panel.generate_stats>` and
:meth:`process_request<debug_toolbar.panels.Panel.generate_stats>`
Header values will be appended if multiple panels need to set it.
By default it sets the Server-Timing header.
Return dict of headers to be appended.
"""
headers = {}
stats = self.get_server_timing_stats()
if stats:
headers["Server-Timing"] = ", ".join(
# example: `SQLPanel_sql_time;dur=0;desc="SQL 0 queries"`
'{}_{};dur={};desc="{}"'.format(
self.panel_id, key, record.get("value"), record.get("title")
)
for key, record in stats.items()
)
return headers
def generate_stats(self, request, response):
"""
Write panel logic related to the response there. Post-process data
gathered while the view executed. Save data with :meth:`record_stats`.
Called after :meth:`process_request
<debug_toolbar.panels.Panel.process_request>`.
Does not return a value.
"""
def generate_server_timing(self, request, response):
"""
Similar to :meth:`generate_stats
<debug_toolbar.panels.Panel.generate_stats>`,
Generate stats for Server Timing https://w3c.github.io/server-timing/
Does not return a value.
"""
def load_stats_from_store(self, data):
"""
Instantiate the panel from serialized data.
Return the panel instance.
"""
self.toolbar.stats.setdefault(self.panel_id, {}).update(data)
self.from_store = True
@classmethod
def run_checks(cls):
"""
Check that the integration is configured correctly for the panel.
This will be called as a part of the Django checks system when the
application is being setup.
Return a list of :class:`django.core.checks.CheckMessage` instances.
"""
return []
| Panel |
python | jpadilla__pyjwt | jwt/exceptions.py | {
"start": 1788,
"end": 1945
} | class ____(PyJWKError):
"""Raised if the algorithm requires ``cryptography`` to be installed and it is not available."""
pass
| MissingCryptographyError |
python | cython__cython | tests/run/pep3135_class_cell.py | {
"start": 3914,
"end": 4075
} | class ____:
"""
>>> M().method()
'overwritten'
"""
def method(self):
__class__ = 'overwritten'
return __class__
@cython.cclass
| M |
python | mozilla__bleach | bleach/_vendor/html5lib/filters/inject_meta_charset.py | {
"start": 89,
"end": 2945
} | class ____(base.Filter):
"""Injects ``<meta charset=ENCODING>`` tag into head of document"""
def __init__(self, source, encoding):
"""Creates a Filter
:arg source: the source token stream
:arg encoding: the encoding to set
"""
base.Filter.__init__(self, source)
self.encoding = encoding
def __iter__(self):
state = "pre_head"
meta_found = (self.encoding is None)
pending = []
for token in base.Filter.__iter__(self):
type = token["type"]
if type == "StartTag":
if token["name"].lower() == "head":
state = "in_head"
elif type == "EmptyTag":
if token["name"].lower() == "meta":
# replace charset with actual encoding
has_http_equiv_content_type = False
for (namespace, name), value in token["data"].items():
if namespace is not None:
continue
elif name.lower() == 'charset':
token["data"][(namespace, name)] = self.encoding
meta_found = True
break
elif name == 'http-equiv' and value.lower() == 'content-type':
has_http_equiv_content_type = True
else:
if has_http_equiv_content_type and (None, "content") in token["data"]:
token["data"][(None, "content")] = 'text/html; charset=%s' % self.encoding
meta_found = True
elif token["name"].lower() == "head" and not meta_found:
# insert meta into empty head
yield {"type": "StartTag", "name": "head",
"data": token["data"]}
yield {"type": "EmptyTag", "name": "meta",
"data": {(None, "charset"): self.encoding}}
yield {"type": "EndTag", "name": "head"}
meta_found = True
continue
elif type == "EndTag":
if token["name"].lower() == "head" and pending:
# insert meta into head (if necessary) and flush pending queue
yield pending.pop(0)
if not meta_found:
yield {"type": "EmptyTag", "name": "meta",
"data": {(None, "charset"): self.encoding}}
while pending:
yield pending.pop(0)
meta_found = True
state = "post_head"
if state == "in_head":
pending.append(token)
else:
yield token
| Filter |
python | django__django | tests/auth_tests/test_models.py | {
"start": 23971,
"end": 24105
} | class ____(SimpleTestCase):
def test_str(self):
g = Group(name="Users")
self.assertEqual(str(g), "Users")
| GroupTests |
python | nedbat__coveragepy | tests/test_context.py | {
"start": 8407,
"end": 8826
} | class ____(SomethingElse, Child):
pass
def no_arguments() -> str | None:
return get_qualname()
def plain_old_function(a: Any, b: Any) -> str | None:
return get_qualname()
def fake_out(self: Any) -> str | None:
return get_qualname()
def patch_meth(self: Any) -> str | None:
return get_qualname()
# pylint: enable=missing-class-docstring, missing-function-docstring, unused-argument
| MultiChild |
python | fluentpython__example-code-2e | 15-more-types/cafeteria/invariant.py | {
"start": 160,
"end": 262
} | class ____(Juice):
"""Delicious juice from Brazilian oranges."""
T = TypeVar('T') # <2>
| OrangeJuice |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 74471,
"end": 74995
} | class ____(CType):
#
# C "void" type
#
is_void = 1
to_py_function = "__Pyx_void_to_None"
def __repr__(self):
return "<CVoidType>"
def declaration_code(self, entity_code,
for_display = 0, dll_linkage = None, pyrex = 0):
if pyrex or for_display:
base_code = "void"
else:
base_code = public_decl("void", dll_linkage)
return self.base_declaration_code(base_code, entity_code)
def is_complete(self):
return 0
| CVoidType |
python | getsentry__sentry | tests/snuba/metrics/naming_layer/test_mri.py | {
"start": 218,
"end": 977
} | class ____(TestCase):
def test_format_mri_field(self) -> None:
assert format_mri_field("max(s:spans/user@none)") == "max(user)"
assert format_mri_field("sum(d:spans/exclusive_time@millisecond)") == "sum(exclusive_time)"
assert format_mri_field("invalid_mri_field") == "invalid_mri_field"
assert format_mri_field(cast(str, None)) is None
def test_format_mri_field_value(self) -> None:
assert format_mri_field_value("count(s:spans/user@none)", "100") == "100"
assert format_mri_field_value("sum(d:spans/exclusive_time@millisecond)", "1000") == "1 s"
assert format_mri_field_value("invalid_mri_field", "100") == "100"
assert format_mri_field_value(cast(str, None), "100") == "100"
| TestMRIUtils |
python | doocs__leetcode | solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.py | {
"start": 0,
"end": 187
} | class ____:
def countTestedDevices(self, batteryPercentages: List[int]) -> int:
ans = 0
for x in batteryPercentages:
ans += x > ans
return ans
| Solution |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/expressions/rolling.py | {
"start": 1279,
"end": 1420
} | class ____(UnaryOp):
policy: plc.replace.ReplacePolicy = plc.replace.ReplacePolicy.PRECEDING
@dataclass(frozen=True)
| FillNullWithStrategyOp |
python | PyCQA__bandit | tests/functional/test_runtime.py | {
"start": 122,
"end": 4469
} | class ____(testtools.TestCase):
def _test_runtime(self, cmdlist, infile=None):
process = subprocess.Popen(
cmdlist,
stdin=infile if infile else subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
close_fds=True,
)
stdout, stderr = process.communicate()
retcode = process.poll()
return (retcode, stdout.decode("utf-8"))
def _test_example(self, cmdlist, targets):
for t in targets:
cmdlist.append(os.path.join(os.getcwd(), "examples", t))
return self._test_runtime(cmdlist)
def test_no_arguments(self):
(retcode, output) = self._test_runtime(
[
"bandit",
]
)
self.assertEqual(2, retcode)
self.assertIn("usage: bandit [-h]", output)
def test_piped_input(self):
with open("examples/imports.py") as infile:
(retcode, output) = self._test_runtime(["bandit", "-"], infile)
self.assertEqual(1, retcode)
self.assertIn("Total lines of code: 4", output)
self.assertIn("Low: 2", output)
self.assertIn("High: 2", output)
self.assertIn("Files skipped (0):", output)
self.assertIn("Issue: [B403:blacklist] Consider possible", output)
self.assertIn("<stdin>:2", output)
self.assertIn("<stdin>:4", output)
def test_nonexistent_config(self):
(retcode, output) = self._test_runtime(
["bandit", "-c", "nonexistent.yml", "xx.py"]
)
self.assertEqual(2, retcode)
self.assertIn("nonexistent.yml : Could not read config file.", output)
def test_help_arg(self):
(retcode, output) = self._test_runtime(["bandit", "-h"])
self.assertEqual(0, retcode)
self.assertIn(
"Bandit - a Python source code security analyzer", output
)
self.assertIn("usage: bandit [-h]", output)
self.assertIn("positional arguments:", output)
self.assertIn("tests were discovered and loaded:", output)
# test examples (use _test_example() to wrap in config location argument
def test_example_nonexistent(self):
(retcode, output) = self._test_example(
[
"bandit",
],
[
"nonexistent.py",
],
)
self.assertEqual(0, retcode)
self.assertIn("Files skipped (1):", output)
self.assertIn("nonexistent.py (No such file or directory", output)
def test_example_okay(self):
(retcode, output) = self._test_example(
[
"bandit",
],
[
"okay.py",
],
)
self.assertEqual(0, retcode)
self.assertIn("Total lines of code: 1", output)
self.assertIn("Files skipped (0):", output)
self.assertIn("No issues identified.", output)
def test_example_nonsense(self):
(retcode, output) = self._test_example(
[
"bandit",
],
[
"nonsense.py",
],
)
self.assertEqual(0, retcode)
self.assertIn("Files skipped (1):", output)
self.assertIn("nonsense.py (syntax error while parsing AST", output)
def test_example_nonsense2(self):
(retcode, output) = self._test_example(
[
"bandit",
],
[
"nonsense2.py",
],
)
self.assertEqual(0, retcode)
self.assertIn("Files skipped (1):", output)
self.assertIn("nonsense2.py (syntax error while parsing AST", output)
def test_example_imports(self):
(retcode, output) = self._test_example(
[
"bandit",
],
[
"imports.py",
],
)
self.assertEqual(1, retcode)
self.assertIn("Total lines of code: 4", output)
self.assertIn("Low: 2", output)
self.assertIn("High: 2", output)
self.assertIn("Files skipped (0):", output)
self.assertIn("Issue: [B403:blacklist] Consider possible", output)
self.assertIn("imports.py:2", output)
self.assertIn("imports.py:4", output)
| RuntimeTests |
python | pytorch__pytorch | torch/nn/parameter.py | {
"start": 10945,
"end": 12217
} | class ____(UninitializedTensorMixin, torch.Tensor):
r"""A buffer that is not initialized.
Uninitialized Buffer is a a special case of :class:`torch.Tensor`
where the shape of the data is still unknown.
Unlike a :class:`torch.Tensor`, uninitialized parameters
hold no data and attempting to access some properties, like their shape,
will throw a runtime error. The only operations that can be performed on a uninitialized
parameter are changing its datatype, moving it to a different device and
converting it to a regular :class:`torch.Tensor`.
The default device or dtype to use when the buffer is materialized can be set
during construction using e.g. ``device='cuda'``.
"""
cls_to_become = torch.Tensor
def __new__(
cls, requires_grad=False, device=None, dtype=None, persistent=True
) -> None:
factory_kwargs = {"device": device, "dtype": dtype}
data = torch.empty(0, **factory_kwargs)
ret = torch.Tensor._make_subclass(cls, data, requires_grad)
# pyrefly: ignore [missing-attribute]
ret.persistent = persistent
# pyrefly: ignore [missing-attribute]
ret._is_buffer = True
# pyrefly: ignore [bad-return]
return ret
| UninitializedBuffer |
python | apache__airflow | devel-common/src/sphinx_exts/providers_extensions.py | {
"start": 14937,
"end": 15460
} | class ____(BaseJinjaReferenceDirective):
"""Generate list of classes supporting OpenLineage"""
def render_content(self, *, tags: set[str] | None, header_separator: str = DEFAULT_HEADER_SEPARATOR):
return _render_openlineage_supported_classes_content()
def setup(app):
"""Setup plugin"""
app.add_directive("airflow-providers-openlineage-supported-classes", OpenLineageSupportedClassesDirective)
return {"parallel_read_safe": True, "parallel_write_safe": True}
| OpenLineageSupportedClassesDirective |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_backend.py | {
"start": 965,
"end": 14515
} | class ____(TestCase):
def setUp(self):
git_repo = make_test_git()
super().setUp()
self.eric = User(username="eric")
self.eric.set_password("test")
self.eric.save()
self.project = Project.objects.create(
name="Test Project",
repo_type="git",
# Our top-level checkout
repo=git_repo,
)
self.project.users.add(self.eric)
self.dummy_conf = Mock()
# These are the default values from v1
self.dummy_conf.submodules.include = ALL
self.dummy_conf.submodules.exclude = []
self.build_environment = LocalBuildEnvironment(api_client=mock.MagicMock())
def tearDown(self):
# Remove all the files created by the test for this project.
safe_rmtree(self.project.doc_path)
super().tearDown()
def test_git_lsremote(self):
repo_path = self.project.repo
default_branches = [
# comes from ``make_test_git`` function
"submodule",
"invalidsubmodule",
]
branches = [
"develop",
"master",
"2.0.X",
"release/2.0.0",
"release/foo/bar",
"with\xa0space",
]
for branch in branches:
create_git_branch(repo_path, branch)
create_git_tag(repo_path, "v01")
create_git_tag(repo_path, "v02", annotated=True)
create_git_tag(repo_path, "release-ünîø∂é")
version = self.project.versions.first()
repo = self.project.vcs_repo(environment=self.build_environment, version=version)
# create the working dir if it not exists. It's required to ``cwd`` to
# execute the command
repo.check_working_dir()
commit = get_current_commit(repo_path)
repo_branches, repo_tags = repo.lsremote()
self.assertEqual(
{branch: branch for branch in default_branches + branches},
{branch.verbose_name: branch.identifier for branch in repo_branches},
)
self.assertEqual(
{"v01": commit, "v02": commit, "release-ünîø∂é": commit},
{tag.verbose_name: tag.identifier for tag in repo_tags},
)
def test_git_lsremote_tags_only(self):
repo_path = self.project.repo
create_git_tag(repo_path, "v01")
create_git_tag(repo_path, "v02", annotated=True)
create_git_tag(repo_path, "release-ünîø∂é")
version = self.project.versions.first()
repo = self.project.vcs_repo(environment=self.build_environment, version=version)
# create the working dir if it not exists. It's required to ``cwd`` to
# execute the command
repo.check_working_dir()
commit = get_current_commit(repo_path)
repo_branches, repo_tags = repo.lsremote(
include_tags=True, include_branches=False
)
self.assertEqual(repo_branches, [])
self.assertEqual(
{"v01": commit, "v02": commit, "release-ünîø∂é": commit},
{tag.verbose_name: tag.identifier for tag in repo_tags},
)
def test_git_lsremote_branches_only(self):
repo_path = self.project.repo
default_branches = [
# comes from ``make_test_git`` function
"submodule",
"invalidsubmodule",
]
branches = [
"develop",
"master",
"2.0.X",
"release/2.0.0",
"release/foo/bar",
]
for branch in branches:
create_git_branch(repo_path, branch)
version = self.project.versions.first()
repo = self.project.vcs_repo(environment=self.build_environment, version=version)
# create the working dir if it not exists. It's required to ``cwd`` to
# execute the command
repo.check_working_dir()
repo_branches, repo_tags = repo.lsremote(
include_tags=False, include_branches=True
)
self.assertEqual(repo_tags, [])
self.assertEqual(
{branch: branch for branch in default_branches + branches},
{branch.verbose_name: branch.identifier for branch in repo_branches},
)
def test_git_lsremote_fails(self):
version = self.project.versions.first()
repo = self.project.vcs_repo(environment=self.build_environment, version=version)
with mock.patch(
"readthedocs.vcs_support.backends.git.Backend.run",
return_value=(1, "Error", ""),
):
with self.assertRaises(RepositoryError) as e:
repo.lsremote(
include_tags=True,
include_branches=True,
)
self.assertEqual(
e.exception.message_id,
RepositoryError.FAILED_TO_GET_VERSIONS,
)
def test_git_update_and_checkout(self):
version = self.project.versions.first()
repo = self.project.vcs_repo(environment=self.build_environment, version=version)
code, _, _ = repo.update()
self.assertEqual(code, 0)
# Returns `None` because there is no `identifier`,
# so it uses the default branch
self.assertIsNone(repo.checkout())
self.assertTrue(exists(repo.working_dir))
def test_git_checkout_invalid_revision(self):
version = self.project.versions.first()
repo = self.project.vcs_repo(environment=self.build_environment, version=version)
repo.update()
branch = "invalid-revision"
with self.assertRaises(RepositoryError) as e:
repo.checkout(branch)
self.assertEqual(
e.exception.message_id,
RepositoryError.FAILED_TO_CHECKOUT,
)
def test_check_for_submodules(self):
"""
Test that we can get a branch called 'submodule' containing a valid submodule.
"""
version = get(
Version,
project=self.project,
type=BRANCH,
identifier="submodule",
verbose_name="submodule",
)
repo = self.project.vcs_repo(
environment=self.build_environment,
version=version,
)
repo.update()
self.assertFalse(repo.are_submodules_available(self.dummy_conf))
# The submodule branch contains one submodule
repo.checkout("submodule")
self.assertTrue(repo.are_submodules_available(self.dummy_conf))
def test_check_submodule_urls(self):
"""Test that a valid submodule is found in the 'submodule' branch."""
version = get(
Version,
project=self.project,
type=BRANCH,
identifier="submodule",
verbose_name="submodule",
)
repo = self.project.vcs_repo(
environment=self.build_environment,
version=version,
)
repo.update()
repo.checkout("submodule")
valid, _ = repo.get_available_submodules(self.dummy_conf)
self.assertTrue(valid)
@patch("readthedocs.vcs_support.backends.git.Backend.fetch")
def test_git_update_with_external_version(self, fetch):
"""Test that an external Version (PR) is correctly cloned and fetched."""
version = fixture.get(
Version,
project=self.project,
type=EXTERNAL,
active=True,
identifier="84492ad53ff8aba83015123f4e68d5897a1fd5bc", # commit hash
verbose_name="1234", # pr number
)
repo = self.project.vcs_repo(
version=version,
environment=self.build_environment,
)
repo.update()
fetch.assert_called_once()
def test_submodule_without_url_is_included(self):
"""Test that an invalid submodule isn't listed."""
version = get(
Version,
project=self.project,
type=BRANCH,
identifier="submodule",
verbose_name="submodule",
)
repo = self.project.vcs_repo(
environment=self.build_environment,
version=version,
)
repo.update()
repo.checkout("submodule")
gitmodules_path = os.path.join(repo.working_dir, ".gitmodules")
with open(gitmodules_path, "a") as f:
content = textwrap.dedent(
"""
[submodule "not-valid-path"]
path = not-valid-path
url =
"""
)
f.write(content)
submodules = list(repo.submodules)
self.assertEqual(submodules, ["foobar", "not-valid-path"])
def test_parse_submodules(self):
version = get(
Version,
project=self.project,
type=BRANCH,
identifier="submodule",
verbose_name="submodule",
)
repo = self.project.vcs_repo(
environment=self.build_environment,
version=version,
)
repo.update()
repo.checkout("submodule")
gitmodules_path = os.path.join(repo.working_dir, ".gitmodules")
with open(gitmodules_path, "a") as f:
content = textwrap.dedent(
"""
[submodule "not-valid-path"]
path = not-valid-path
url =
[submodule "path with spaces"]
path = path with spaces
url = https://github.com
[submodule "another-submodule"]
url = https://github.com
path = another-submodule
[ssubmodule "invalid-submodule-key"]
url = https://github.com
path = invalid-submodule-key
[submodule "invalid-path-key"]
url = https://github.com
paths = invalid-submodule-key
[submodule "invalid-url-key"]
uurl = https://github.com
path = invalid-submodule-key
"""
)
f.write(content)
submodules = list(repo.submodules)
self.assertEqual(
submodules,
[
"foobar",
"not-valid-path",
"path with spaces",
"another-submodule",
"invalid-submodule-key",
],
)
def test_skip_submodule_checkout(self):
"""Test that a submodule is listed as available."""
version = get(
Version,
project=self.project,
type=BRANCH,
identifier="submodule",
verbose_name="submodule",
)
repo = self.project.vcs_repo(
environment=self.build_environment,
version=version,
)
repo.update()
repo.checkout("submodule")
self.assertTrue(repo.are_submodules_available(self.dummy_conf))
def test_git_fetch_with_external_version(self):
"""Test that fetching an external build (PR branch) correctly executes."""
version = fixture.get(Version, project=self.project, type=EXTERNAL, active=True)
repo = self.project.vcs_repo(
version=version,
environment=self.build_environment,
)
repo.update()
code, _, _ = repo.fetch()
self.assertEqual(code, 0)
def test_update_without_branch_name(self):
"""
Test that we get expected default branch when not specifying a branch name.
Covers:
* Manually imported projects +
* Automatically imported projects that had their default branch name deliberately removed
during import wizard (and before the first branch sync from webhook)
"""
repo_path = self.project.repo
create_git_branch(repo_path, "develop")
version = get(
Version,
project=self.project,
type=BRANCH,
identifier="develop",
verbose_name="develop",
)
repo = self.project.vcs_repo(
environment=self.build_environment,
version=version,
)
repo.update()
# Check that the README file from the fixture exists
self.assertTrue(os.path.isfile(os.path.join(repo.working_dir, "README")))
# Check that "only-on-default-branch" exists (it doesn't exist on other branches)
self.assertTrue(
os.path.exists(os.path.join(repo.working_dir, "only-on-default-branch"))
)
# Check that we don't for instance have foobar
self.assertFalse(os.path.isfile(os.path.join(repo.working_dir, "foobar")))
def test_special_tag_stable(self):
"""Test that an auto-generated 'stable' tag works."""
repo_path = self.project.repo
latest_actual_commit_hash = get_git_latest_commit_hash(repo_path, "master")
version = get(
Version,
project=self.project,
type=TAG,
identifier=latest_actual_commit_hash,
verbose_name="stable",
slug=STABLE,
machine=True,
)
repo = self.project.vcs_repo(
environment=self.build_environment,
version=version,
)
repo.update()
# Checkout the master branch to verify that we can checkout something
# from the above clone+fetch
repo.checkout("master")
| TestGitBackend |
python | readthedocs__readthedocs.org | readthedocs/profiles/tests/test_views.py | {
"start": 1234,
"end": 36963
} | class ____(TestCase):
def setUp(self):
self.user = get(User)
self.social_account_github = get(
SocialAccount,
provider=GitHubProvider.id,
user=self.user,
uid="1234",
extra_data={"login": "user"},
)
get(
SocialToken,
account=self.social_account_github,
)
self.social_account_github_app = get(
SocialAccount,
provider=GitHubAppProvider.id,
user=self.user,
uid="1234",
extra_data={"login": "user"},
)
self.github_app_installation = get(
GitHubAppInstallation,
installation_id=1111,
target_id=int(self.social_account_github_app.uid),
target_type=GitHubAccountType.USER,
)
# Project with remote repository where the user is admin.
self.remote_repository_a = get(
RemoteRepository,
name="repo-a",
full_name="user/repo-a",
html_url="https://github.com/user/repo-a",
remote_id="1111",
vcs_provider=GITHUB,
)
get(
RemoteRepositoryRelation,
user=self.user,
account=self.social_account_github,
remote_repository=self.remote_repository_a,
admin=True,
)
self.project_with_remote_repository = get(
Project,
users=[self.user],
remote_repository=self.remote_repository_a,
)
# Project with remote repository where the user is not admin.
self.remote_repository_b = get(
RemoteRepository,
name="repo-b",
full_name="user/repo-b",
html_url="https://github.com/user/repo-b",
remote_id="2222",
vcs_provider=GITHUB,
)
get(
RemoteRepositoryRelation,
user=self.user,
account=self.social_account_github,
remote_repository=self.remote_repository_b,
admin=False,
)
self.project_with_remote_repository_no_admin = get(
Project,
users=[self.user],
remote_repository=self.remote_repository_b,
)
# Project with remote repository where the user doesn't have permissions at all.
self.remote_repository_c = get(
RemoteRepository,
name="repo-c",
full_name="user2/repo-c",
html_url="https://github.com/user2/repo-c",
remote_id="3333",
vcs_provider=GITHUB,
)
get(
RemoteRepositoryRelation,
user=self.user,
account=self.social_account_github,
remote_repository=self.remote_repository_c,
admin=False,
)
self.project_with_remote_repository_no_member = get(
Project,
users=[self.user],
remote_repository=self.remote_repository_c,
)
# Project connected to a remote repository that belongs to an organization.
self.remote_organization = get(
RemoteOrganization,
slug="org",
name="Organization",
remote_id="9999",
vcs_provider=GITHUB,
)
get(
RemoteOrganizationRelation,
user=self.user,
account=self.social_account_github,
)
self.remote_repository_d = get(
RemoteRepository,
name="repo-d",
full_name="org/repo-d",
html_url="https://github.com/org/repo-d",
remote_id="4444",
organization=self.remote_organization,
)
get(
RemoteRepositoryRelation,
user=self.user,
account=self.social_account_github,
remote_repository=self.remote_repository_d,
admin=True,
)
self.project_with_remote_organization = get(
Project,
users=[self.user],
remote_repository=self.remote_repository_d,
)
self.github_app_organization_installation = get(
GitHubAppInstallation,
installation_id=2222,
target_id=int(self.remote_organization.remote_id),
target_type=GitHubAccountType.ORGANIZATION,
)
# Project without a remote repository.
self.project_without_remote_repository = get(
Project,
users=[self.user],
repo="https://github.com/user/repo-e",
)
# Make tests work on .com.
if settings.RTD_ALLOW_ORGANIZATIONS:
self.organization = get(
Organization,
owners=[self.user],
projects=[
self.project_with_remote_repository,
self.project_with_remote_repository_no_admin,
self.project_with_remote_repository_no_member,
self.project_with_remote_organization,
self.project_without_remote_repository,
],
)
self.url = reverse("migrate_to_github_app")
self.client.force_login(self.user)
def _create_github_app_remote_repository(self, remote_repository):
new_remote_repository = get(
RemoteRepository,
name=remote_repository.name,
full_name=remote_repository.full_name,
html_url=remote_repository.html_url,
remote_id=remote_repository.remote_id,
vcs_provider=GITHUB_APP,
github_app_installation=self.github_app_installation,
)
if remote_repository.organization:
new_remote_repository.organization = get(
RemoteOrganization,
slug=remote_repository.organization.slug,
name=remote_repository.organization.name,
remote_id=remote_repository.organization.remote_id,
vcs_provider=GITHUB_APP,
)
new_remote_repository.github_app_installation = (
self.github_app_organization_installation
)
new_remote_repository.save()
for relation in remote_repository.remote_repository_relations.all():
github_app_account = relation.user.socialaccount_set.get(
provider=GitHubAppProvider.id
)
get(
RemoteRepositoryRelation,
user=relation.user,
account=github_app_account,
remote_repository=new_remote_repository,
admin=relation.admin,
)
return new_remote_repository
def test_user_without_github_account(self):
self.user.socialaccount_set.all().delete()
response = self.client.get(self.url)
assert response.status_code == 302
response = self.client.get(reverse("projects_dashboard"))
content = response.content.decode()
print(content)
assert (
"You don\\u0026#x27\\u003Bt have any GitHub account connected." in content
)
def test_user_without_github_account_but_with_github_app_account(self):
self.user.socialaccount_set.exclude(provider=GitHubAppProvider.id).delete()
response = self.client.get(self.url)
assert response.status_code == 302
response = self.client.get(reverse("projects_dashboard"))
assert (
"You have already migrated your account to the new GitHub App"
in response.content.decode()
)
@requests_mock.Mocker(kw="request")
def test_migration_page_initial_state(self, request):
request.get("https://api.github.com/user", status_code=200)
self.user.socialaccount_set.filter(provider=GitHubAppProvider.id).delete()
response = self.client.get(self.url)
assert response.status_code == 200
context = response.context
assert context["step"] == "overview"
assert context["step_connect_completed"] is False
assert list(context["migrated_projects"]) == []
assert (
context["old_application_link"]
== "https://github.com/settings/connections/applications/123"
)
assert context["step_revoke_completed"] is False
assert list(context["old_github_accounts"]) == [self.social_account_github]
assert "installation_target_groups" not in context
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "install"})
assert response.status_code == 200
context = response.context
assert context["installation_target_groups"] == [
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.social_account_github.uid),
login="user",
type=GitHubAccountType.USER,
avatar_url=self.social_account_github.get_avatar_url(),
profile_url=self.social_account_github.get_profile_url(),
),
repository_ids={1111, 2222, 3333},
),
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.remote_organization.remote_id),
login="org",
type=GitHubAccountType.ORGANIZATION,
avatar_url=self.remote_organization.avatar_url,
profile_url=self.remote_organization.url,
),
repository_ids={4444},
),
]
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "migrate"})
assert response.status_code == 200
context = response.context
assert context["migration_targets"] == [
MigrationTarget(
project=self.project_with_remote_repository,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_repository_no_admin,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_repository_no_member,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_organization,
has_installation=False,
is_admin=False,
target_id=int(self.remote_organization.remote_id),
),
]
assert "installation_target_groups" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "revoke"})
assert response.status_code == 200
context = response.context
assert context["has_projects_pending_migration"] is True
assert "installation_target_groups" not in context
assert "migration_targets" not in context
@requests_mock.Mocker(kw="request")
def test_migration_page_step_connect_done(self, request):
request.get("https://api.github.com/user", status_code=200)
response = self.client.get(self.url)
assert response.status_code == 200
context = response.context
assert context["step"] == "overview"
assert context["step_connect_completed"] is True
assert list(context["migrated_projects"]) == []
assert (
context["old_application_link"]
== "https://github.com/settings/connections/applications/123"
)
assert context["step_revoke_completed"] is False
assert list(context["old_github_accounts"]) == [self.social_account_github]
assert "installation_target_groups" not in context
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "install"})
assert response.status_code == 200
context = response.context
assert context["installation_target_groups"] == [
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.social_account_github.uid),
login="user",
type=GitHubAccountType.USER,
avatar_url=self.social_account_github.get_avatar_url(),
profile_url=self.social_account_github.get_profile_url(),
),
repository_ids={1111, 2222, 3333},
),
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.remote_organization.remote_id),
login="org",
type=GitHubAccountType.ORGANIZATION,
avatar_url=self.remote_organization.avatar_url,
profile_url=self.remote_organization.url,
),
repository_ids={4444},
),
]
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "migrate"})
assert response.status_code == 200
context = response.context
assert context["migration_targets"] == [
MigrationTarget(
project=self.project_with_remote_repository,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_repository_no_admin,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_repository_no_member,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_organization,
has_installation=False,
is_admin=False,
target_id=int(self.remote_organization.remote_id),
),
]
assert "installation_target_groups" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "revoke"})
assert response.status_code == 200
context = response.context
assert context["has_projects_pending_migration"] is True
assert "installation_target_groups" not in context
assert "migration_targets" not in context
@requests_mock.Mocker(kw="request")
def test_migration_page_step_install_done(self, request):
request.get("https://api.github.com/user", status_code=200)
self._create_github_app_remote_repository(self.remote_repository_a)
self._create_github_app_remote_repository(self.remote_repository_b)
self._create_github_app_remote_repository(self.remote_repository_d)
response = self.client.get(self.url)
assert response.status_code == 200
context = response.context
assert context["step"] == "overview"
assert context["step_connect_completed"] is True
assert list(context["migrated_projects"]) == []
assert (
context["old_application_link"]
== "https://github.com/settings/connections/applications/123"
)
assert context["step_revoke_completed"] is False
assert list(context["old_github_accounts"]) == [self.social_account_github]
assert "installation_target_groups" not in context
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "install"})
assert response.status_code == 200
context = response.context
assert context["installation_target_groups"] == [
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.social_account_github.uid),
login="user",
type=GitHubAccountType.USER,
avatar_url=self.social_account_github.get_avatar_url(),
profile_url=self.social_account_github.get_profile_url(),
),
repository_ids={3333},
),
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.remote_organization.remote_id),
login="org",
type=GitHubAccountType.ORGANIZATION,
avatar_url=self.remote_organization.avatar_url,
profile_url=self.remote_organization.url,
),
repository_ids=set(),
),
]
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "migrate"})
assert response.status_code == 200
context = response.context
assert context["migration_targets"] == [
MigrationTarget(
project=self.project_with_remote_repository,
has_installation=True,
is_admin=True,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_repository_no_admin,
has_installation=True,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_repository_no_member,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_organization,
has_installation=True,
is_admin=True,
target_id=int(self.remote_organization.remote_id),
),
]
assert "installation_target_groups" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "revoke"})
assert response.status_code == 200
context = response.context
assert context["has_projects_pending_migration"] is True
assert "installation_target_groups" not in context
assert "migration_targets" not in context
@requests_mock.Mocker(kw="request")
@mock.patch.object(GitHubService, "remove_webhook")
@mock.patch.object(GitHubService, "remove_ssh_key")
def test_migration_page_step_migrate_one_project(
self, remove_ssh_key, remove_webhook, request
):
request.get("https://api.github.com/user", status_code=200)
remove_ssh_key.return_value = True
remove_webhook.return_value = True
self._create_github_app_remote_repository(self.remote_repository_a)
self._create_github_app_remote_repository(self.remote_repository_b)
self._create_github_app_remote_repository(self.remote_repository_d)
response = self.client.post(
self.url, data={"project": self.project_with_remote_repository.slug}
)
assert response.status_code == 302
response = self.client.get(self.url)
assert response.status_code == 200
context = response.context
assert context["step"] == "overview"
assert context["step_connect_completed"] is True
assert list(context["migrated_projects"]) == [
self.project_with_remote_repository,
]
assert (
context["old_application_link"]
== "https://github.com/settings/connections/applications/123"
)
assert context["step_revoke_completed"] is False
assert list(context["old_github_accounts"]) == [self.social_account_github]
assert "installation_target_groups" not in context
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "install"})
assert response.status_code == 200
context = response.context
assert context["installation_target_groups"] == [
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.social_account_github.uid),
login="user",
type=GitHubAccountType.USER,
avatar_url=self.social_account_github.get_avatar_url(),
profile_url=self.social_account_github.get_profile_url(),
),
repository_ids={3333},
),
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.remote_organization.remote_id),
login="org",
type=GitHubAccountType.ORGANIZATION,
avatar_url=self.remote_organization.avatar_url,
profile_url=self.remote_organization.url,
),
repository_ids=set(),
),
]
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "migrate"})
assert response.status_code == 200
context = response.context
assert context["migration_targets"] == [
MigrationTarget(
project=self.project_with_remote_repository_no_admin,
has_installation=True,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_repository_no_member,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_organization,
has_installation=True,
is_admin=True,
target_id=int(self.remote_organization.remote_id),
),
]
assert "installation_target_groups" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "revoke"})
assert response.status_code == 200
context = response.context
assert context["has_projects_pending_migration"] is True
assert "installation_target_groups" not in context
assert "migration_targets" not in context
@requests_mock.Mocker(kw="request")
@mock.patch.object(GitHubService, "remove_webhook")
@mock.patch.object(GitHubService, "remove_ssh_key")
def test_migration_page_step_migrate_all_projects(
self, remove_ssh_key, remove_webhook, request
):
request.get("https://api.github.com/user", status_code=200)
remove_ssh_key.return_value = True
remove_webhook.return_value = True
self._create_github_app_remote_repository(self.remote_repository_a)
self._create_github_app_remote_repository(self.remote_repository_b)
self._create_github_app_remote_repository(self.remote_repository_d)
response = self.client.post(self.url)
assert response.status_code == 302
response = self.client.get(self.url)
context = response.context
assert context["step"] == "overview"
assert context["step_connect_completed"] is True
assert list(context["migrated_projects"]) == [
self.project_with_remote_repository,
self.project_with_remote_organization,
]
assert (
context["old_application_link"]
== "https://github.com/settings/connections/applications/123"
)
assert context["step_revoke_completed"] is False
assert list(context["old_github_accounts"]) == [self.social_account_github]
assert "installation_target_groups" not in context
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "install"})
context = response.context
assert context["installation_target_groups"] == [
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.social_account_github.uid),
login="user",
type=GitHubAccountType.USER,
avatar_url=self.social_account_github.get_avatar_url(),
profile_url=self.social_account_github.get_profile_url(),
),
repository_ids={3333},
),
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.remote_organization.remote_id),
login="org",
type=GitHubAccountType.ORGANIZATION,
avatar_url=self.remote_organization.avatar_url,
profile_url=self.remote_organization.url,
),
repository_ids=set(),
),
]
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "migrate"})
assert response.status_code == 200
context = response.context
assert context["migration_targets"] == [
MigrationTarget(
project=self.project_with_remote_repository_no_admin,
has_installation=True,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_repository_no_member,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
]
assert "installation_target_groups" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "revoke"})
assert response.status_code == 200
context = response.context
assert context["has_projects_pending_migration"] is True
assert "installation_target_groups" not in context
assert "migration_targets" not in context
@requests_mock.Mocker(kw="request")
@mock.patch.object(GitHubService, "remove_webhook")
@mock.patch.object(GitHubService, "remove_ssh_key")
def test_migration_page_step_migrate_one_project_with_errors(
self, remove_ssh_key, remove_webhook, request
):
request.get("https://api.github.com/user", status_code=200)
remove_ssh_key.return_value = False
remove_webhook.return_value = False
self._create_github_app_remote_repository(self.remote_repository_a)
self._create_github_app_remote_repository(self.remote_repository_b)
self._create_github_app_remote_repository(self.remote_repository_d)
response = self.client.post(
self.url, data={"project": self.project_with_remote_repository.slug}
)
assert response.status_code == 302
response = self.client.get(self.url)
context = response.context
assert context["step"] == "overview"
assert context["step_connect_completed"] is True
assert list(context["migrated_projects"]) == [
self.project_with_remote_repository,
]
assert (
context["old_application_link"]
== "https://github.com/settings/connections/applications/123"
)
assert context["step_revoke_completed"] is False
assert list(context["old_github_accounts"]) == [self.social_account_github]
notifications = Notification.objects.for_user(self.user, self.user)
assert notifications.count() == 2
assert notifications.filter(
message_id=MESSAGE_OAUTH_WEBHOOK_NOT_REMOVED
).exists()
assert notifications.filter(
message_id=MESSAGE_OAUTH_DEPLOY_KEY_NOT_REMOVED
).exists()
assert "installation_target_groups" not in context
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "install"})
assert response.status_code == 200
context = response.context
assert context["installation_target_groups"] == [
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.social_account_github.uid),
login="user",
type=GitHubAccountType.USER,
avatar_url=self.social_account_github.get_avatar_url(),
profile_url=self.social_account_github.get_profile_url(),
),
repository_ids={3333},
),
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.remote_organization.remote_id),
login="org",
type=GitHubAccountType.ORGANIZATION,
avatar_url=self.remote_organization.avatar_url,
profile_url=self.remote_organization.url,
),
repository_ids=set(),
),
]
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "migrate"})
assert response.status_code == 200
context = response.context
assert context["migration_targets"] == [
MigrationTarget(
project=self.project_with_remote_repository_no_admin,
has_installation=True,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_repository_no_member,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_organization,
has_installation=True,
is_admin=True,
target_id=int(self.remote_organization.remote_id),
),
]
assert "installation_target_groups" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "revoke"})
assert response.status_code == 200
context = response.context
assert context["has_projects_pending_migration"] is True
assert "installation_target_groups" not in context
assert "migration_targets" not in context
@requests_mock.Mocker(kw="request")
def test_migration_page_step_revoke_done(self, request):
request.get("https://api.github.com/user", status_code=401)
response = self.client.get(self.url)
assert response.status_code == 200
context = response.context
assert context["step"] == "overview"
assert context["step_connect_completed"] is True
assert list(context["migrated_projects"]) == []
assert (
context["old_application_link"]
== "https://github.com/settings/connections/applications/123"
)
assert context["step_revoke_completed"] is True
assert list(context["old_github_accounts"]) == [self.social_account_github]
assert "installation_target_groups" not in context
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "install"})
assert response.status_code == 200
context = response.context
assert context["installation_target_groups"] == [
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.social_account_github.uid),
login="user",
type=GitHubAccountType.USER,
avatar_url=self.social_account_github.get_avatar_url(),
profile_url=self.social_account_github.get_profile_url(),
),
repository_ids={1111, 2222, 3333},
),
InstallationTargetGroup(
target=GitHubAccountTarget(
id=int(self.remote_organization.remote_id),
login="org",
type=GitHubAccountType.ORGANIZATION,
avatar_url=self.remote_organization.avatar_url,
profile_url=self.remote_organization.url,
),
repository_ids={4444},
),
]
assert "migration_targets" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "migrate"})
assert response.status_code == 200
context = response.context
assert context["migration_targets"] == [
MigrationTarget(
project=self.project_with_remote_repository,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_repository_no_admin,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_repository_no_member,
has_installation=False,
is_admin=False,
target_id=int(self.social_account_github.uid),
),
MigrationTarget(
project=self.project_with_remote_organization,
has_installation=False,
is_admin=False,
target_id=int(self.remote_organization.remote_id),
),
]
assert "installation_target_groups" not in context
assert "has_projects_pending_migration" not in context
response = self.client.get(self.url, data={"step": "revoke"})
assert response.status_code == 200
context = response.context
assert context["has_projects_pending_migration"] is True
assert "installation_target_groups" not in context
assert "migration_targets" not in context
| TestMigrateToGitHubAppView |
python | jschneier__django-storages | tests/test_gcloud.py | {
"start": 549,
"end": 963
} | class ____(TestCase):
def setUp(self):
self.bucket_name = "test_bucket"
self.filename = "test_file.txt"
self.storage = gcloud.GoogleCloudStorage(bucket_name=self.bucket_name)
self.client_patcher = mock.patch("storages.backends.gcloud.Client")
self.client_patcher.start()
def tearDown(self):
super().tearDown()
self.client_patcher.stop()
| GCloudTestCase |
python | RaRe-Technologies__gensim | gensim/test/test_translation_matrix.py | {
"start": 3938,
"end": 5980
} | class ____(unittest.TestCase):
def setUp(self):
filename = datapath("alldata-id-10.txt")
train_docs = read_sentiment_docs(filename)
self.train_docs = train_docs
self.source_doc_vec = Doc2Vec(documents=train_docs[:5], vector_size=8, epochs=50, seed=1)
self.target_doc_vec = Doc2Vec(documents=train_docs, vector_size=8, epochs=50, seed=2)
def test_translation_matrix(self):
model = translation_matrix.BackMappingTranslationMatrix(
self.source_doc_vec, self.target_doc_vec, self.train_docs[:5],
)
transmat = model.train(self.train_docs[:5])
self.assertEqual(transmat.shape, (8, 8))
@unittest.skip(
"flaky test likely to be discarded when <https://github.com/RaRe-Technologies/gensim/issues/2977> "
"is addressed"
)
def test_infer_vector(self):
"""Test that translation gives similar results to traditional inference.
This may not be completely sensible/salient with such tiny data, but
replaces what seemed to me to be an ever-more-nonsensical test.
See <https://github.com/RaRe-Technologies/gensim/issues/2977> for discussion
of whether the class this supposedly tested even survives when the
TranslationMatrix functionality is better documented.
"""
model = translation_matrix.BackMappingTranslationMatrix(
self.source_doc_vec, self.target_doc_vec, self.train_docs[:5],
)
model.train(self.train_docs[:5])
backmapped_vec = model.infer_vector(self.target_doc_vec.dv[self.train_docs[5].tags[0]])
self.assertEqual(backmapped_vec.shape, (8, ))
d2v_inferred_vector = self.source_doc_vec.infer_vector(self.train_docs[5].words)
distance = cosine(backmapped_vec, d2v_inferred_vector)
self.assertLessEqual(distance, 0.1)
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
unittest.main()
| TestBackMappingTranslationMatrix |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.