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 | huggingface__transformers | src/transformers/models/big_bird/modeling_big_bird.py | {
"start": 68909,
"end": 70036
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.
prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
before SoftMax).
"""
loss: Optional[torch.FloatTensor] = None
prediction_logits: Optional[torch.FloatTensor] = None
seq_relationship_logits: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for outputs of question answering models.
"""
)
| BigBirdForPreTrainingOutput |
python | neetcode-gh__leetcode | python/0350-intersection-of-two-arrays-ii.py | {
"start": 0,
"end": 550
} | class ____:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
counter1 = Counter(nums1)
counter2 = Counter(nums2)
# Using defaultdict to handle missing keys more efficiently
counter1 = defaultdict(int, counter1)
counter2 = defaultdict(int, counter2)
intersection = []
for num, freq in counter1.items():
min_freq = min(freq, counter2[num])
if min_freq > 0:
intersection.extend([num] * min_freq)
return intersection
| Solution |
python | huggingface__transformers | src/transformers/models/mllama/modeling_mllama.py | {
"start": 58777,
"end": 64469
} | class ____(MllamaPreTrainedModel, GenerationMixin):
config: MllamaTextConfig
_can_compile_fullgraph = True # only the LLM without cross attn can do compile
base_model_prefix = "language_model"
def __init__(self, config):
super().__init__(config.get_text_config())
self.text_config = config.get_text_config()
self.vocab_size = self.text_config.vocab_size
self.model = MllamaTextModel._from_config(self.text_config)
self.lm_head = nn.Linear(self.text_config.hidden_size, self.vocab_size, bias=False)
self.post_init()
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
cross_attention_states: Optional[torch.LongTensor] = None,
cross_attention_mask: Optional[torch.LongTensor] = None,
full_text_row_masked_out_mask: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, CausalLMOutputWithPast]:
r"""
cross_attention_states (`torch.FloatTensor`, *optional*):
Output of the vision model, used for cross-attention. This tensor contains the processed image features that
the language model will attend to.
cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*):
Cross-attention mask to control the interaction between text tokens and image tiles.
This 4D tensor defines which image tiles each text token should attend to.
For each text token (in seq_length):
- 1 indicates the token **should attend** to the corresponding image tile
- 0 indicates the token **should not attend** to the corresponding image tile
full_text_row_masked_out_mask (`tuple[torch.Tensor, torch.Tensor]`, *optional*):
A tuple containing two tensors that mask out rows in the cross-attention mechanism:
- The first tensor has shape `(batch_size, 1, seq_length, 1)` and contains values of 0 or 1.
A value of 0 indicates that the corresponding text token's entire row in the cross-attention
matrix should be masked out (all image tokens ignored).
- The second tensor has the same shape and is used internally to apply the masking during
the forward pass of cross-attention layers.
This mask is derived from the cross_attention_mask and is used to handle cases where a text token
should not attend to any image token.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
Example:
```python
>>> from transformers import AutoTokenizer, MllamaForCausalLM
>>> model = MllamaForCausalLM.from_pretrained("Llama-3.2-11B-Vision")
>>> tokenizer = AutoTokenizer.from_pretrained("Llama-3.2-11B-Vision")
>>> prompt = "If I had to write a haiku, it would be:"
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=40, do_sample=True, temperature=0.6)
>>> result = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
>>> print(result)
If I had to write a haiku, it would be: "Snowflakes gently fall" - simple, yet peaceful.
I love the idea of snowflakes gently falling, each one
```
"""
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
outputs = self.model(
input_ids=input_ids,
cross_attention_states=cross_attention_states,
attention_mask=attention_mask,
position_ids=position_ids,
cross_attention_mask=cross_attention_mask,
full_text_row_masked_out_mask=full_text_row_masked_out_mask,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :]).float()
loss = None
if labels is not None:
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@auto_docstring(
custom_intro="""
The Mllama model which consists of a vision encoder and a language model without language modeling head.
"""
)
| MllamaForCausalLM |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_float.py | {
"start": 39354,
"end": 45621
} | class ____(__TestCase):
def assertFloatsAreIdentical(self, x, y):
"""assert that floats x and y are identical, in the sense that:
(1) both x and y are nans, or
(2) both x and y are infinities, with the same sign, or
(3) both x and y are zeros, with the same sign, or
(4) x and y are both finite and nonzero, and x == y
"""
msg = 'floats {!r} and {!r} are not identical'
if isnan(x) or isnan(y):
if isnan(x) and isnan(y):
return
elif x == y:
if x != 0.0:
return
# both zero; check that signs match
elif copysign(1.0, x) == copysign(1.0, y):
return
else:
msg += ': zeros have different signs'
self.fail(msg.format(x, y))
def test_inf_nan(self):
self.assertRaises(OverflowError, round, INF)
self.assertRaises(OverflowError, round, -INF)
self.assertRaises(ValueError, round, NAN)
self.assertRaises(TypeError, round, INF, 0.0)
self.assertRaises(TypeError, round, -INF, 1.0)
self.assertRaises(TypeError, round, NAN, "ceci n'est pas un integer")
self.assertRaises(TypeError, round, -0.0, 1j)
def test_inf_nan_ndigits(self):
self.assertEqual(round(INF, 0), INF)
self.assertEqual(round(-INF, 0), -INF)
self.assertTrue(math.isnan(round(NAN, 0)))
def test_large_n(self):
for n in [324, 325, 400, 2**31-1, 2**31, 2**32, 2**100]:
self.assertEqual(round(123.456, n), 123.456)
self.assertEqual(round(-123.456, n), -123.456)
self.assertEqual(round(1e300, n), 1e300)
self.assertEqual(round(1e-320, n), 1e-320)
self.assertEqual(round(1e150, 300), 1e150)
self.assertEqual(round(1e300, 307), 1e300)
self.assertEqual(round(-3.1415, 308), -3.1415)
self.assertEqual(round(1e150, 309), 1e150)
self.assertEqual(round(1.4e-315, 315), 1e-315)
def test_small_n(self):
for n in [-308, -309, -400, 1-2**31, -2**31, -2**31-1, -2**100]:
self.assertFloatsAreIdentical(round(123.456, n), 0.0)
self.assertFloatsAreIdentical(round(-123.456, n), -0.0)
self.assertFloatsAreIdentical(round(1e300, n), 0.0)
self.assertFloatsAreIdentical(round(1e-320, n), 0.0)
def test_overflow(self):
self.assertRaises(OverflowError, round, 1.6e308, -308)
self.assertRaises(OverflowError, round, -1.7e308, -308)
@unittest.skipUnless(getattr(sys, 'float_repr_style', '') == 'short',
"applies only when using short float repr style")
def test_previous_round_bugs(self):
# particular cases that have occurred in bug reports
self.assertEqual(round(562949953421312.5, 1),
562949953421312.5)
self.assertEqual(round(56294995342131.5, 3),
56294995342131.5)
# round-half-even
self.assertEqual(round(25.0, -1), 20.0)
self.assertEqual(round(35.0, -1), 40.0)
self.assertEqual(round(45.0, -1), 40.0)
self.assertEqual(round(55.0, -1), 60.0)
self.assertEqual(round(65.0, -1), 60.0)
self.assertEqual(round(75.0, -1), 80.0)
self.assertEqual(round(85.0, -1), 80.0)
self.assertEqual(round(95.0, -1), 100.0)
@unittest.skipUnless(getattr(sys, 'float_repr_style', '') == 'short',
"applies only when using short float repr style")
def test_matches_float_format(self):
# round should give the same results as float formatting
for i in range(500):
x = i/1000.
self.assertEqual(float(format(x, '.0f')), round(x, 0))
self.assertEqual(float(format(x, '.1f')), round(x, 1))
self.assertEqual(float(format(x, '.2f')), round(x, 2))
self.assertEqual(float(format(x, '.3f')), round(x, 3))
for i in range(5, 5000, 10):
x = i/1000.
self.assertEqual(float(format(x, '.0f')), round(x, 0))
self.assertEqual(float(format(x, '.1f')), round(x, 1))
self.assertEqual(float(format(x, '.2f')), round(x, 2))
self.assertEqual(float(format(x, '.3f')), round(x, 3))
for i in range(500):
x = random.random()
self.assertEqual(float(format(x, '.0f')), round(x, 0))
self.assertEqual(float(format(x, '.1f')), round(x, 1))
self.assertEqual(float(format(x, '.2f')), round(x, 2))
self.assertEqual(float(format(x, '.3f')), round(x, 3))
def test_format_specials(self):
# Test formatting of nans and infs.
def test(fmt, value, expected):
# Test with both % and format().
self.assertEqual(fmt % value, expected, fmt)
fmt = fmt[1:] # strip off the %
self.assertEqual(format(value, fmt), expected, fmt)
for fmt in ['%e', '%f', '%g', '%.0e', '%.6f', '%.20g',
'%#e', '%#f', '%#g', '%#.20e', '%#.15f', '%#.3g']:
pfmt = '%+' + fmt[1:]
sfmt = '% ' + fmt[1:]
test(fmt, INF, 'inf')
test(fmt, -INF, '-inf')
test(fmt, NAN, 'nan')
test(fmt, -NAN, 'nan')
# When asking for a sign, it's always provided. nans are
# always positive.
test(pfmt, INF, '+inf')
test(pfmt, -INF, '-inf')
test(pfmt, NAN, '+nan')
test(pfmt, -NAN, '+nan')
# When using ' ' for a sign code, only infs can be negative.
# Others have a space.
test(sfmt, INF, ' inf')
test(sfmt, -INF, '-inf')
test(sfmt, NAN, ' nan')
test(sfmt, -NAN, ' nan')
def test_None_ndigits(self):
for x in round(1.23), round(1.23, None), round(1.23, ndigits=None):
self.assertEqual(x, 1)
self.assertIsInstance(x, int)
for x in round(1.78), round(1.78, None), round(1.78, ndigits=None):
self.assertEqual(x, 2)
self.assertIsInstance(x, int)
# Beginning with Python 2.6 float has cross platform compatible
# ways to create and represent inf and nan
| RoundTestCase |
python | huggingface__transformers | src/transformers/models/owlvit/modeling_owlvit.py | {
"start": 22260,
"end": 22935
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.fc1(hidden_states)
hidden_states = self.activation_fn(hidden_states)
hidden_states = self.fc2(hidden_states)
return hidden_states
# Copied from transformers.models.altclip.modeling_altclip.AltCLIPEncoderLayer with AltCLIP->OwlViT
| OwlViTMLP |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_ps.py | {
"start": 11845,
"end": 31557
} | class ____(_backend_pdf_ps.RendererPDFPSBase):
"""
The renderer handles all the drawing primitives using a graphics
context instance that controls the colors/styles.
"""
_afm_font_dir = cbook._get_data_path("fonts/afm")
_use_afm_rc_name = "ps.useafm"
def __init__(self, width, height, pswriter, imagedpi=72):
# Although postscript itself is dpi independent, we need to inform the
# image code about a requested dpi to generate high resolution images
# and then scale them before embedding them.
super().__init__(width, height)
self._pswriter = pswriter
if mpl.rcParams['text.usetex']:
self.textcnt = 0
self.psfrag = []
self.imagedpi = imagedpi
# current renderer state (None=uninitialised)
self.color = None
self.linewidth = None
self.linejoin = None
self.linecap = None
self.linedash = None
self.fontname = None
self.fontsize = None
self._hatches = {}
self.image_magnification = imagedpi / 72
self._clip_paths = {}
self._path_collection_id = 0
self._character_tracker = _backend_pdf_ps.CharacterTracker()
self._logwarn_once = functools.cache(_log.warning)
def _is_transparent(self, rgb_or_rgba):
if rgb_or_rgba is None:
return True # Consistent with rgbFace semantics.
elif len(rgb_or_rgba) == 4:
if rgb_or_rgba[3] == 0:
return True
if rgb_or_rgba[3] != 1:
self._logwarn_once(
"The PostScript backend does not support transparency; "
"partially transparent artists will be rendered opaque.")
return False
else: # len() == 3.
return False
def set_color(self, r, g, b, store=True):
if (r, g, b) != self.color:
self._pswriter.write(f"{_nums_to_str(r)} setgray\n"
if r == g == b else
f"{_nums_to_str(r, g, b)} setrgbcolor\n")
if store:
self.color = (r, g, b)
def set_linewidth(self, linewidth, store=True):
linewidth = float(linewidth)
if linewidth != self.linewidth:
self._pswriter.write(f"{_nums_to_str(linewidth)} setlinewidth\n")
if store:
self.linewidth = linewidth
@staticmethod
def _linejoin_cmd(linejoin):
# Support for directly passing integer values is for backcompat.
linejoin = {'miter': 0, 'round': 1, 'bevel': 2, 0: 0, 1: 1, 2: 2}[
linejoin]
return f"{linejoin:d} setlinejoin\n"
def set_linejoin(self, linejoin, store=True):
if linejoin != self.linejoin:
self._pswriter.write(self._linejoin_cmd(linejoin))
if store:
self.linejoin = linejoin
@staticmethod
def _linecap_cmd(linecap):
# Support for directly passing integer values is for backcompat.
linecap = {'butt': 0, 'round': 1, 'projecting': 2, 0: 0, 1: 1, 2: 2}[
linecap]
return f"{linecap:d} setlinecap\n"
def set_linecap(self, linecap, store=True):
if linecap != self.linecap:
self._pswriter.write(self._linecap_cmd(linecap))
if store:
self.linecap = linecap
def set_linedash(self, offset, seq, store=True):
if self.linedash is not None:
oldo, oldseq = self.linedash
if np.array_equal(seq, oldseq) and oldo == offset:
return
self._pswriter.write(f"[{_nums_to_str(*seq)}] {_nums_to_str(offset)} setdash\n"
if seq is not None and len(seq) else
"[] 0 setdash\n")
if store:
self.linedash = (offset, seq)
def set_font(self, fontname, fontsize, store=True):
if (fontname, fontsize) != (self.fontname, self.fontsize):
self._pswriter.write(f"/{fontname} {fontsize:1.3f} selectfont\n")
if store:
self.fontname = fontname
self.fontsize = fontsize
def create_hatch(self, hatch, linewidth):
sidelen = 72
if hatch in self._hatches:
return self._hatches[hatch]
name = 'H%d' % len(self._hatches)
pageheight = self.height * 72
self._pswriter.write(f"""\
<< /PatternType 1
/PaintType 2
/TilingType 2
/BBox[0 0 {sidelen:d} {sidelen:d}]
/XStep {sidelen:d}
/YStep {sidelen:d}
/PaintProc {{
pop
{linewidth:g} setlinewidth
{self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}
gsave
fill
grestore
stroke
}} bind
>>
matrix
0 {pageheight:g} translate
makepattern
/{name} exch def
""")
self._hatches[hatch] = name
return name
def get_image_magnification(self):
"""
Get the factor by which to magnify images passed to draw_image.
Allows a backend to have images at a different resolution to other
artists.
"""
return self.image_magnification
def _convert_path(self, path, transform, clip=False, simplify=None):
if clip:
clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0)
else:
clip = None
return _path.convert_to_string(
path, transform, clip, simplify, None,
6, [b"m", b"l", b"", b"c", b"cl"], True).decode("ascii")
def _get_clip_cmd(self, gc):
clip = []
rect = gc.get_clip_rectangle()
if rect is not None:
clip.append(f"{_nums_to_str(*rect.p0, *rect.size)} rectclip\n")
path, trf = gc.get_clip_path()
if path is not None:
key = (path, id(trf))
custom_clip_cmd = self._clip_paths.get(key)
if custom_clip_cmd is None:
custom_clip_cmd = "c%d" % len(self._clip_paths)
self._pswriter.write(f"""\
/{custom_clip_cmd} {{
{self._convert_path(path, trf, simplify=False)}
clip
newpath
}} bind def
""")
self._clip_paths[key] = custom_clip_cmd
clip.append(f"{custom_clip_cmd}\n")
return "".join(clip)
@_log_if_debug_on
def draw_image(self, gc, x, y, im, transform=None):
# docstring inherited
h, w = im.shape[:2]
imagecmd = "false 3 colorimage"
data = im[::-1, :, :3] # Vertically flipped rgb values.
hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
if transform is None:
matrix = "1 0 0 1 0 0"
xscale = w / self.image_magnification
yscale = h / self.image_magnification
else:
matrix = " ".join(map(str, transform.frozen().to_values()))
xscale = 1.0
yscale = 1.0
self._pswriter.write(f"""\
gsave
{self._get_clip_cmd(gc)}
{x:g} {y:g} translate
[{matrix}] concat
{xscale:g} {yscale:g} scale
/DataString {w:d} string def
{w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ]
{{
currentfile DataString readhexstring pop
}} bind {imagecmd}
{hexdata}
grestore
""")
@_log_if_debug_on
def draw_path(self, gc, path, transform, rgbFace=None):
# docstring inherited
clip = rgbFace is None and gc.get_hatch_path() is None
simplify = path.should_simplify and clip
ps = self._convert_path(path, transform, clip=clip, simplify=simplify)
self._draw_ps(ps, gc, rgbFace)
@_log_if_debug_on
def draw_markers(
self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
# docstring inherited
ps_color = (
None
if self._is_transparent(rgbFace)
else f'{_nums_to_str(rgbFace[0])} setgray'
if rgbFace[0] == rgbFace[1] == rgbFace[2]
else f'{_nums_to_str(*rgbFace[:3])} setrgbcolor')
# construct the generic marker command:
# don't want the translate to be global
ps_cmd = ['/o {', 'gsave', 'newpath', 'translate']
lw = gc.get_linewidth()
alpha = (gc.get_alpha()
if gc.get_forced_alpha() or len(gc.get_rgb()) == 3
else gc.get_rgb()[3])
stroke = lw > 0 and alpha > 0
if stroke:
ps_cmd.append('%.1f setlinewidth' % lw)
ps_cmd.append(self._linejoin_cmd(gc.get_joinstyle()))
ps_cmd.append(self._linecap_cmd(gc.get_capstyle()))
ps_cmd.append(self._convert_path(marker_path, marker_trans,
simplify=False))
if rgbFace:
if stroke:
ps_cmd.append('gsave')
if ps_color:
ps_cmd.extend([ps_color, 'fill'])
if stroke:
ps_cmd.append('grestore')
if stroke:
ps_cmd.append('stroke')
ps_cmd.extend(['grestore', '} bind def'])
for vertices, code in path.iter_segments(
trans,
clip=(0, 0, self.width*72, self.height*72),
simplify=False):
if len(vertices):
x, y = vertices[-2:]
ps_cmd.append(f"{x:g} {y:g} o")
ps = '\n'.join(ps_cmd)
self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)
@_log_if_debug_on
def draw_path_collection(self, gc, master_transform, paths, all_transforms,
offsets, offset_trans, facecolors, edgecolors,
linewidths, linestyles, antialiaseds, urls,
offset_position, *, hatchcolors=None):
if hatchcolors is None:
hatchcolors = []
# Is the optimization worth it? Rough calculation:
# cost of emitting a path in-line is
# (len_path + 2) * uses_per_path
# cost of definition+use is
# (len_path + 3) + 3 * uses_per_path
len_path = len(paths[0].vertices) if len(paths) > 0 else 0
uses_per_path = self._iter_collection_uses_per_path(
paths, all_transforms, offsets, facecolors, edgecolors)
should_do_optimization = \
len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path
if not should_do_optimization:
return RendererBase.draw_path_collection(
self, gc, master_transform, paths, all_transforms,
offsets, offset_trans, facecolors, edgecolors,
linewidths, linestyles, antialiaseds, urls,
offset_position, hatchcolors=hatchcolors)
path_codes = []
for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
master_transform, paths, all_transforms)):
name = 'p%d_%d' % (self._path_collection_id, i)
path_bytes = self._convert_path(path, transform, simplify=False)
self._pswriter.write(f"""\
/{name} {{
newpath
translate
{path_bytes}
}} bind def
""")
path_codes.append(name)
for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
gc, path_codes, offsets, offset_trans,
facecolors, edgecolors, linewidths, linestyles,
antialiaseds, urls, offset_position, hatchcolors=hatchcolors):
ps = f"{xo:g} {yo:g} {path_id}"
self._draw_ps(ps, gc0, rgbFace)
self._path_collection_id += 1
@_log_if_debug_on
def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
# docstring inherited
if self._is_transparent(gc.get_rgb()):
return # Special handling for fully transparent.
if not hasattr(self, "psfrag"):
self._logwarn_once(
"The PS backend determines usetex status solely based on "
"rcParams['text.usetex'] and does not support having "
"usetex=True only for some elements; this element will thus "
"be rendered as if usetex=False.")
self.draw_text(gc, x, y, s, prop, angle, False, mtext)
return
w, h, bl = self.get_text_width_height_descent(s, prop, ismath="TeX")
fontsize = prop.get_size_in_points()
thetext = 'psmarker%d' % self.textcnt
color = _nums_to_str(*gc.get_rgb()[:3], sep=',')
fontcmd = {'sans-serif': r'{\sffamily %s}',
'monospace': r'{\ttfamily %s}'}.get(
mpl.rcParams['font.family'][0], r'{\rmfamily %s}')
s = fontcmd % s
tex = r'\color[rgb]{%s} %s' % (color, s)
# Stick to bottom-left alignment, so subtract descent from the text-normal
# direction since text is normally positioned by its baseline.
rangle = np.radians(angle + 90)
pos = _nums_to_str(x - bl * np.cos(rangle), y - bl * np.sin(rangle))
self.psfrag.append(
r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % (
thetext, angle, fontsize, fontsize*1.25, tex))
self._pswriter.write(f"""\
gsave
{pos} moveto
({thetext})
show
grestore
""")
self.textcnt += 1
@_log_if_debug_on
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
# docstring inherited
if self._is_transparent(gc.get_rgb()):
return # Special handling for fully transparent.
if ismath == 'TeX':
return self.draw_tex(gc, x, y, s, prop, angle)
if ismath:
return self.draw_mathtext(gc, x, y, s, prop, angle)
stream = [] # list of (ps_name, x, char_name)
if mpl.rcParams['ps.useafm']:
font = self._get_font_afm(prop)
ps_name = (font.postscript_name.encode("ascii", "replace")
.decode("ascii"))
scale = 0.001 * prop.get_size_in_points()
thisx = 0
last_name = None # kerns returns 0 for None.
for c in s:
name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
try:
width = font.get_width_from_char_name(name)
except KeyError:
name = 'question'
width = font.get_width_char(ord('?'))
kern = font.get_kern_dist_from_name(last_name, name)
last_name = name
thisx += kern * scale
stream.append((ps_name, thisx, name))
thisx += width * scale
else:
font = self._get_font_ttf(prop)
self._character_tracker.track(font, s)
for item in _text_helpers.layout(s, font):
ps_name = (item.ft_object.postscript_name
.encode("ascii", "replace").decode("ascii"))
glyph_name = item.ft_object.get_glyph_name(item.glyph_idx)
stream.append((ps_name, item.x, glyph_name))
self.set_color(*gc.get_rgb())
for ps_name, group in itertools. \
groupby(stream, lambda entry: entry[0]):
self.set_font(ps_name, prop.get_size_in_points(), False)
thetext = "\n".join(f"{x:g} 0 m /{name:s} glyphshow"
for _, x, name in group)
self._pswriter.write(f"""\
gsave
{self._get_clip_cmd(gc)}
{x:g} {y:g} translate
{angle:g} rotate
{thetext}
grestore
""")
@_log_if_debug_on
def draw_mathtext(self, gc, x, y, s, prop, angle):
"""Draw the math text using matplotlib.mathtext."""
width, height, descent, glyphs, rects = \
self._text2path.mathtext_parser.parse(s, 72, prop)
self.set_color(*gc.get_rgb())
self._pswriter.write(
f"gsave\n"
f"{x:g} {y:g} translate\n"
f"{angle:g} rotate\n")
lastfont = None
for font, fontsize, num, ox, oy in glyphs:
self._character_tracker.track_glyph(font, num)
if (font.postscript_name, fontsize) != lastfont:
lastfont = font.postscript_name, fontsize
self._pswriter.write(
f"/{font.postscript_name} {fontsize} selectfont\n")
glyph_name = font.get_glyph_name(font.get_char_index(num))
self._pswriter.write(
f"{ox:g} {oy:g} moveto\n"
f"/{glyph_name} glyphshow\n")
for ox, oy, w, h in rects:
self._pswriter.write(f"{ox} {oy} {w} {h} rectfill\n")
self._pswriter.write("grestore\n")
@_log_if_debug_on
def draw_gouraud_triangles(self, gc, points, colors, trans):
assert len(points) == len(colors)
if len(points) == 0:
return
assert points.ndim == 3
assert points.shape[1] == 3
assert points.shape[2] == 2
assert colors.ndim == 3
assert colors.shape[1] == 3
assert colors.shape[2] == 4
shape = points.shape
flat_points = points.reshape((shape[0] * shape[1], 2))
flat_points = trans.transform(flat_points)
flat_colors = colors.reshape((shape[0] * shape[1], 4))
points_min = np.min(flat_points, axis=0) - (1 << 12)
points_max = np.max(flat_points, axis=0) + (1 << 12)
factor = np.ceil((2 ** 32 - 1) / (points_max - points_min))
xmin, ymin = points_min
xmax, ymax = points_max
data = np.empty(
shape[0] * shape[1],
dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')])
data['flags'] = 0
data['points'] = (flat_points - points_min) * factor
data['colors'] = flat_colors[:, :3] * 255.0
hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
self._pswriter.write(f"""\
gsave
<< /ShadingType 4
/ColorSpace [/DeviceRGB]
/BitsPerCoordinate 32
/BitsPerComponent 8
/BitsPerFlag 8
/AntiAlias true
/Decode [ {xmin:g} {xmax:g} {ymin:g} {ymax:g} 0 1 0 1 0 1 ]
/DataSource <
{hexdata}
>
>>
shfill
grestore
""")
def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True):
"""
Emit the PostScript snippet *ps* with all the attributes from *gc*
applied. *ps* must consist of PostScript commands to construct a path.
The *fill* and/or *stroke* kwargs can be set to False if the *ps*
string already includes filling and/or stroking, in which case
`_draw_ps` is just supplying properties and clipping.
"""
write = self._pswriter.write
mightstroke = (gc.get_linewidth() > 0
and not self._is_transparent(gc.get_rgb()))
if not mightstroke:
stroke = False
if self._is_transparent(rgbFace):
fill = False
hatch = gc.get_hatch()
if mightstroke:
self.set_linewidth(gc.get_linewidth())
self.set_linejoin(gc.get_joinstyle())
self.set_linecap(gc.get_capstyle())
self.set_linedash(*gc.get_dashes())
if mightstroke or hatch:
self.set_color(*gc.get_rgb()[:3])
write('gsave\n')
write(self._get_clip_cmd(gc))
write(ps.strip())
write("\n")
if fill:
if stroke or hatch:
write("gsave\n")
self.set_color(*rgbFace[:3], store=False)
write("fill\n")
if stroke or hatch:
write("grestore\n")
if hatch:
hatch_name = self.create_hatch(hatch, gc.get_hatch_linewidth())
write("gsave\n")
write(_nums_to_str(*gc.get_hatch_color()[:3]))
write(f" {hatch_name} setpattern fill grestore\n")
if stroke:
write("stroke\n")
write("grestore\n")
| RendererPS |
python | coleifer__peewee | examples/diary.py | {
"start": 315,
"end": 2450
} | class ____(Model):
content = TextField()
timestamp = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
def initialize(passphrase):
db.init('diary.db', passphrase=passphrase)
db.create_tables([Entry])
def menu_loop():
choice = None
while choice != 'q':
for key, value in menu.items():
print('%s) %s' % (key, value.__doc__))
choice = input('Action: ').lower().strip()
if choice in menu:
menu[choice]()
def add_entry():
"""Add entry"""
print('Enter your entry. Press ctrl+d when finished.')
data = sys.stdin.read().strip()
if data and input('Save entry? [Yn] ') != 'n':
Entry.create(content=data)
print('Saved successfully.')
def view_entries(search_query=None):
"""View previous entries"""
query = Entry.select().order_by(Entry.timestamp.desc())
if search_query:
query = query.where(Entry.content.contains(search_query))
for entry in query:
timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:%M%p')
print(timestamp)
print('=' * len(timestamp))
print(entry.content)
print('n) next entry')
print('d) delete entry')
print('q) return to main menu')
action = input('Choice? (Ndq) ').lower().strip()
if action == 'q':
break
elif action == 'd':
entry.delete_instance()
break
def search_entries():
"""Search entries"""
view_entries(input('Search query: '))
menu = OrderedDict([
('a', add_entry),
('v', view_entries),
('s', search_entries),
])
if __name__ == '__main__':
# Collect the passphrase using a secure method.
passphrase = getpass('Enter password: ')
if not passphrase:
sys.stderr.write('Passphrase required to access diary.\n')
sys.stderr.flush()
sys.exit(1)
elif len(passphrase) < 8:
sys.stderr.write('Passphrase must be at least 8 characters.\n')
sys.stderr.flush()
sys.exit(1)
# Initialize the database.
initialize(passphrase)
menu_loop()
| Entry |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 50055,
"end": 53388
} | class ____(PrefectFilterBaseModel):
"""Filter by text search across log content."""
query: str = Field(
description="Text search query string",
examples=[
"error",
"error -debug",
'"connection timeout"',
"+required -excluded",
],
max_length=200,
)
def includes(self, log: "Log") -> bool:
"""Check if this text filter includes the given log."""
from prefect.server.schemas.core import Log
if not isinstance(log, Log):
raise TypeError(f"Expected Log object, got {type(log)}")
# Parse query into components
parsed = parse_text_search_query(self.query)
# Build searchable text from message and logger name
searchable_text = f"{log.message} {log.name}".lower()
# Check include terms (OR logic)
if parsed.include:
include_match = any(
term.lower() in searchable_text for term in parsed.include
)
if not include_match:
return False
# Check exclude terms (NOT logic)
if parsed.exclude:
exclude_match = any(
term.lower() in searchable_text for term in parsed.exclude
)
if exclude_match:
return False
# Check required terms (AND logic - future feature)
if parsed.required:
required_match = all(
term.lower() in searchable_text for term in parsed.required
)
if not required_match:
return False
return True
def _get_filter_list(
self, db: "PrefectDBInterface"
) -> Iterable[sa.ColumnExpressionArgument[bool]]:
"""Build SQLAlchemy WHERE clauses for text search"""
filters: list[sa.ColumnExpressionArgument[bool]] = []
if not self.query.strip():
return filters
parsed = parse_text_search_query(self.query)
# Build combined searchable text field (message + name)
searchable_field = sa.func.concat(db.Log.message, " ", db.Log.name)
# Handle include terms (OR logic)
if parsed.include:
include_conditions = []
for term in parsed.include:
include_conditions.append(
sa.func.lower(searchable_field).contains(term.lower())
)
if include_conditions:
filters.append(sa.or_(*include_conditions))
# Handle exclude terms (NOT logic)
if parsed.exclude:
exclude_conditions = []
for term in parsed.exclude:
exclude_conditions.append(
~sa.func.lower(searchable_field).contains(term.lower())
)
if exclude_conditions:
filters.append(sa.and_(*exclude_conditions))
# Handle required terms (AND logic - future feature)
if parsed.required:
required_conditions = []
for term in parsed.required:
required_conditions.append(
sa.func.lower(searchable_field).contains(term.lower())
)
if required_conditions:
filters.append(sa.and_(*required_conditions))
return filters
| LogFilterTextSearch |
python | getsentry__sentry | tests/sentry/api/test_invite_helper.py | {
"start": 384,
"end": 5210
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.org = self.create_organization(name="Rowdy Tiger", owner=None)
self.team = self.create_team(organization=self.org, name="Mariachi Band")
self.user = self.create_user("foo@example.com")
self.member = self.create_member(
user=None,
email="bar@example.com",
organization=self.org,
teams=[self.team],
)
self.request = HttpRequest()
# Needed for audit logs
self.request.META["REMOTE_ADDR"] = "127.0.0.1"
self.request.user = self.user
def _get_om_from_accepting_invite(self) -> OrganizationMember:
"""
Returns a refreshed organization member (id=self.member.id) after having accepted
the invite from the ApiInviteHelper. Assert on the resulting OM depending on the context for
the organization (e.g. SSO, duplicate invite)
"""
om = OrganizationMember.objects.get(id=self.member.id)
assert om.email == self.member.email
invite_context = organization_service.get_invite_by_id(
organization_member_id=om.id, organization_id=om.organization_id
)
assert invite_context is not None
helper = ApiInviteHelper(self.request, invite_context, None)
with assume_test_silo_mode(SiloMode.CONTROL):
helper.accept_invite(self.user)
om.refresh_from_db()
return om
def test_accept_invite_without_SSO(self) -> None:
om = self._get_om_from_accepting_invite()
assert om.email is None
assert om.user_id == self.user.id
def test_invite_already_accepted_without_SSO(self) -> None:
om = self._get_om_from_accepting_invite()
invite_context = organization_service.get_invite_by_id(
organization_member_id=om.id, organization_id=om.organization_id
)
assert invite_context is not None
member_id = invite_context.invite_organization_member_id
assert member_id is not None
# Without this member_id, don't delete the organization member
invite_context.invite_organization_member_id = None
helper = ApiInviteHelper(self.request, invite_context, None)
with assume_test_silo_mode(SiloMode.CONTROL):
helper.accept_invite(self.user)
om.refresh_from_db()
assert om.email is None
assert om.user_id == self.user.id
# With the member_id, ensure it's deleted
invite_context.invite_organization_member_id = member_id
helper = ApiInviteHelper(self.request, invite_context, None)
with assume_test_silo_mode(SiloMode.CONTROL):
helper.accept_invite(self.user)
with pytest.raises(OrganizationMember.DoesNotExist):
OrganizationMember.objects.get(id=self.member.id)
def test_accept_invite_with_optional_SSO(self) -> None:
ap = self.create_auth_provider(organization_id=self.org.id, provider="Friendly IdP")
with assume_test_silo_mode(SiloMode.CONTROL):
ap.flags.allow_unlinked = True
ap.save()
om = self._get_om_from_accepting_invite()
assert om.email is None
assert om.user_id == self.user.id
def test_invite_already_accepted_with_optional_SSO(self) -> None:
ap = self.create_auth_provider(organization_id=self.org.id, provider="Friendly IdP")
with assume_test_silo_mode(SiloMode.CONTROL):
ap.flags.allow_unlinked = True
ap.save()
self.test_invite_already_accepted_without_SSO()
def test_accept_invite_with_required_SSO(self) -> None:
ap = self.create_auth_provider(organization_id=self.org.id, provider="Friendly IdP")
assert not ap.flags.allow_unlinked # SSO is required
om = self._get_om_from_accepting_invite()
# Invite cannot be accepted without AuthIdentity if SSO is required
assert om.email is not None
assert om.user_id is None
def test_accept_invite_with_required_SSO_with_identity(self) -> None:
ap = self.create_auth_provider(organization_id=self.org.id, provider="Friendly IdP")
assert not ap.flags.allow_unlinked # SSO is required
self.create_auth_identity(auth_provider=ap, user=self.user)
om = self._get_om_from_accepting_invite()
assert om.email is None
assert om.user_id == self.user.id
def test_invite_already_accepted_with_required_SSO(self) -> None:
ap = self.create_auth_provider(organization_id=self.org.id, provider="Friendly IdP")
assert not ap.flags.allow_unlinked # SSO is required
self.create_auth_identity(auth_provider=ap, user=self.user)
self.test_invite_already_accepted_without_SSO()
| ApiInviteHelperTest |
python | django-import-export__django-import-export | tests/core/tests/test_mixins.py | {
"start": 420,
"end": 4145
} | class ____(AdminTestMixin, TestCase):
class TestExportForm(forms.ExportForm):
cleaned_data = {}
def setUp(self):
self.url = reverse("export-category")
self.cat1 = Category.objects.create(name="Cat 1")
self.cat2 = Category.objects.create(name="Cat 2")
self.resource = modelresource_factory(Category)
self.form = ExportViewMixinTest.TestExportForm(
formats=formats.base_formats.DEFAULT_FORMATS,
resources=[self.resource],
)
self.form.cleaned_data["format"] = "0"
def test_get(self):
response = self.client.get(self.url)
self.assertContains(response, self.cat1.name, status_code=200)
self.assertEqual(response["Content-Type"], "text/html; charset=utf-8")
def test_post(self):
data = {"format": "0", "categoryresource_id": True}
self._prepend_form_prefix(data)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
response = self.client.post(self.url, data)
self.assertContains(response, self.cat1.name, status_code=200)
self.assertTrue(response.has_header("Content-Disposition"))
self.assertEqual(response["Content-Type"], "text/csv")
def test_get_response_raises_TypeError_when_content_type_kwarg_used(self):
"""
Test that HttpResponse is instantiated using the correct kwarg.
"""
content_type = "text/csv"
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=DeprecationWarning)
class TestMixin(mixins.ExportViewFormMixin):
def __init__(self):
self.model = MagicMock()
self.request = MagicMock(spec=HttpRequest)
self.model.__name__ = "mockModel"
def get_queryset(self):
return MagicMock()
m = TestMixin()
with mock.patch("import_export.mixins.HttpResponse") as mock_http_response:
# on first instantiation, raise TypeError, on second, return mock
mock_http_response.side_effect = [TypeError(), mock_http_response]
m.form_valid(self.form)
self.assertEqual(
content_type, mock_http_response.call_args_list[0][1]["content_type"]
)
self.assertEqual(
content_type, mock_http_response.call_args_list[1][1]["mimetype"]
)
def test_implements_get_filterset(self):
"""
test that if the class-under-test defines a get_filterset()
method, then this is called as required.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=DeprecationWarning)
class TestMixin(mixins.ExportViewFormMixin):
mock_get_filterset_call_count = 0
mock_get_filterset_class_call_count = 0
def __init__(self):
self.model = MagicMock()
self.request = MagicMock(spec=HttpRequest)
self.model.__name__ = "mockModel"
def get_filterset(self, filterset_class):
self.mock_get_filterset_call_count += 1
return MagicMock()
def get_filterset_class(self):
self.mock_get_filterset_class_call_count += 1
return MagicMock()
m = TestMixin()
res = m.form_valid(self.form)
self.assertEqual(200, res.status_code)
self.assertEqual(1, m.mock_get_filterset_call_count)
self.assertEqual(1, m.mock_get_filterset_class_call_count)
| ExportViewMixinTest |
python | wandb__wandb | wandb/sdk/artifacts/storage_policies/wandb_storage_policy.py | {
"start": 1887,
"end": 13405
} | class ____(StoragePolicy):
@classmethod
def name(cls) -> str:
return WANDB_STORAGE_POLICY
@classmethod
def from_config(cls, config: StoragePolicyConfig) -> WandbStoragePolicy:
return cls(config=config)
def __init__(
self,
config: StoragePolicyConfig | None = None,
cache: ArtifactFileCache | None = None,
api: InternalApi | None = None,
) -> None:
self._config = StoragePolicyConfig.model_validate(config or {})
# Don't instantiate these right away if missing, instead defer to the
# first time they're needed. Otherwise, at the time of writing, this
# significantly slows down `Artifact.__init__()`.
self._maybe_cache = cache
self._maybe_api = api
self._maybe_session: requests.Session | None = None
self._maybe_handler: MultiHandler | None = None
@property
def _cache(self) -> ArtifactFileCache:
if self._maybe_cache is None:
self._maybe_cache = get_artifact_file_cache()
return self._maybe_cache
@property
def _api(self) -> InternalApi:
if self._maybe_api is None:
self._maybe_api = InternalApi()
return self._maybe_api
@_api.setter
def _api(self, api: InternalApi) -> None:
self._maybe_api = api
@property
def _session(self) -> requests.Session:
if self._maybe_session is None:
self._maybe_session = make_http_session()
return self._maybe_session
@property
def _handler(self) -> MultiHandler:
if self._maybe_handler is None:
self._maybe_handler = MultiHandler(
handlers=make_storage_handlers(self._session),
default_handler=TrackingHandler(),
)
return self._maybe_handler
def config(self) -> dict[str, Any]:
return self._config.model_dump(exclude_none=True)
def load_file(
self,
artifact: Artifact,
manifest_entry: ArtifactManifestEntry,
dest_path: str | None = None,
# FIXME: We should avoid passing the executor into multiple inner functions,
# it leads to confusing code and opaque tracebacks/call stacks.
executor: concurrent.futures.Executor | None = None,
) -> FilePathStr:
"""Use cache or download the file using signed url.
Args:
executor: A thread pool provided by the caller for multi-file
downloads. Reuse the thread pool for multipart downloads; it is
closed when the artifact download completes. If this is `None`,
download the file serially.
"""
if dest_path is not None:
self._cache._override_cache_path = dest_path
path, hit, cache_open = self._cache.check_md5_obj_path(
manifest_entry.digest,
size=manifest_entry.size or 0,
)
if hit:
return path
if url := manifest_entry._download_url:
# Use multipart parallel download for large file
if executor and (size := manifest_entry.size):
multipart_download(executor, self._session, url, size, cache_open)
return path
# Serial download
try:
response = self._session.get(url, stream=True)
except requests.HTTPError:
# Signed URL might have expired, fall back to fetching it one by one.
manifest_entry._download_url = None
if manifest_entry._download_url is None:
auth = None
headers = _thread_local_api_settings.headers
cookies = _thread_local_api_settings.cookies
# For auth, prefer using (in order): auth header, cookies, HTTP Basic Auth
if token := self._api.access_token:
headers = {**(headers or {}), "Authorization": f"Bearer {token}"}
elif cookies is not None:
pass
else:
auth = ("api", self._api.api_key or "")
file_url = self._file_url(artifact, manifest_entry)
response = self._session.get(
file_url, auth=auth, cookies=cookies, headers=headers, stream=True
)
with cache_open(mode="wb") as file:
for data in response.iter_content(chunk_size=16 * KiB):
file.write(data)
return path
def store_reference(
self,
artifact: Artifact,
path: URIStr | FilePathStr,
name: str | None = None,
checksum: bool = True,
max_objects: int | None = None,
) -> list[ArtifactManifestEntry]:
return self._handler.store_path(
artifact, path, name=name, checksum=checksum, max_objects=max_objects
)
def load_reference(
self,
manifest_entry: ArtifactManifestEntry,
local: bool = False,
dest_path: str | None = None,
) -> FilePathStr | URIStr:
assert manifest_entry.ref is not None
used_handler = self._handler._get_handler(manifest_entry.ref)
if hasattr(used_handler, "_cache") and (dest_path is not None):
used_handler._cache._override_cache_path = dest_path
return self._handler.load_path(manifest_entry, local)
def _file_url(self, artifact: Artifact, entry: ArtifactManifestEntry) -> str:
api = self._api
base_url: str = api.settings("base_url")
layout = self._config.storage_layout or StorageLayout.V1
region = self._config.storage_region or "default"
entity = artifact.entity
project = artifact.project
collection = artifact.name.split(":")[0]
hexhash = b64_to_hex_id(entry.digest)
if layout is StorageLayout.V1:
return f"{base_url}/artifacts/{entity}/{hexhash}"
if layout is StorageLayout.V2:
birth_artifact_id = entry.birth_artifact_id or ""
if server_supports(
api.client, pb.ARTIFACT_COLLECTION_MEMBERSHIP_FILE_DOWNLOAD_HANDLER
):
return f"{base_url}/artifactsV2/{region}/{quote(entity)}/{quote(project)}/{quote(collection)}/{quote(birth_artifact_id)}/{hexhash}/{entry.path.name}"
return f"{base_url}/artifactsV2/{region}/{quote(entity)}/{quote(birth_artifact_id)}/{hexhash}"
assert_never(layout)
def s3_multipart_file_upload(
self,
file_path: str,
chunk_size: int,
hex_digests: dict[int, str],
multipart_urls: dict[int, str],
extra_headers: dict[str, str],
) -> list[dict[str, Any]]:
etags: deque[dict[str, Any]] = deque()
file_chunks = scan_chunks(file_path, chunk_size)
for num, data in enumerate(file_chunks, start=1):
rsp = self._api.upload_multipart_file_chunk_retry(
multipart_urls[num],
data,
extra_headers={
"content-md5": hex_to_b64_id(hex_digests[num]),
"content-length": str(len(data)),
"content-type": extra_headers.get("Content-Type") or "",
},
)
assert rsp is not None
etags.append({"partNumber": num, "hexMD5": rsp.headers["ETag"]})
return list(etags)
def default_file_upload(
self,
upload_url: str,
file_path: str,
extra_headers: dict[str, Any],
progress_callback: progress.ProgressFn | None = None,
) -> None:
"""Upload a file to the artifact store and write to cache."""
with open(file_path, "rb") as file:
# This fails if we don't send the first byte before the signed URL expires.
self._api.upload_file_retry(
upload_url, file, progress_callback, extra_headers=extra_headers
)
def store_file(
self,
artifact_id: str,
artifact_manifest_id: str,
entry: ArtifactManifestEntry,
preparer: StepPrepare,
progress_callback: progress.ProgressFn | None = None,
) -> bool:
"""Upload a file to the artifact store.
Returns:
True if the file was a duplicate (did not need to be uploaded),
False if it needed to be uploaded or was a reference (nothing to dedupe).
"""
file_size = entry.size or 0
chunk_size = calc_part_size(file_size)
file_path = entry.local_path or ""
# Logic for AWS s3 multipart upload.
# Only chunk files if larger than 2 GiB. Currently can only support up to 5TiB.
if MIN_MULTI_UPLOAD_SIZE <= file_size <= MAX_MULTI_UPLOAD_SIZE:
file_chunks = scan_chunks(file_path, chunk_size)
upload_parts = [
{"partNumber": num, "hexMD5": hashlib.md5(data).hexdigest()}
for num, data in enumerate(file_chunks, start=1)
]
hex_digests = dict(map(itemgetter("partNumber", "hexMD5"), upload_parts))
else:
upload_parts = []
hex_digests = {}
resp = preparer.prepare(
{
"artifactID": artifact_id,
"artifactManifestID": artifact_manifest_id,
"name": entry.path,
"md5": entry.digest,
"uploadPartsInput": upload_parts,
}
).get()
entry.birth_artifact_id = resp.birth_artifact_id
if resp.upload_url is None:
return True
if entry.local_path is None:
return False
extra_headers = dict(hdr.split(":", 1) for hdr in (resp.upload_headers or []))
# This multipart upload isn't available, do a regular single url upload
if (multipart_urls := resp.multipart_upload_urls) is None and resp.upload_url:
self.default_file_upload(
resp.upload_url, file_path, extra_headers, progress_callback
)
elif multipart_urls is None:
raise ValueError(f"No multipart urls to upload for file: {file_path}")
else:
# Upload files using s3 multipart upload urls
etags = self.s3_multipart_file_upload(
file_path,
chunk_size,
hex_digests,
multipart_urls,
extra_headers,
)
assert resp.storage_path is not None
self._api.complete_multipart_upload_artifact(
artifact_id, resp.storage_path, etags, resp.upload_id
)
self._write_cache(entry)
return False
def _write_cache(self, entry: ArtifactManifestEntry) -> None:
if entry.local_path is None:
return
# Cache upon successful upload.
_, hit, cache_open = self._cache.check_md5_obj_path(
entry.digest,
size=entry.size or 0,
)
staging_dir = get_staging_dir()
try:
if not (entry.skip_cache or hit):
with cache_open("wb") as f, open(entry.local_path, "rb") as src:
shutil.copyfileobj(src, f)
if entry.local_path.startswith(staging_dir):
# Delete staged files here instead of waiting till
# all the files are uploaded
os.chmod(entry.local_path, 0o600)
os.remove(entry.local_path)
except OSError as e:
termwarn(f"Failed to cache {entry.local_path}, ignoring {e}")
| WandbStoragePolicy |
python | walkccc__LeetCode | solutions/2850. Minimum Moves to Spread Stones Over Grid/2850.py | {
"start": 0,
"end": 576
} | class ____:
def minimumMoves(self, grid: list[list[int]]) -> int:
if sum(row.count(0) for row in grid) == 0:
return 0
ans = math.inf
for i in range(3):
for j in range(3):
if grid[i][j] == 0:
for x in range(3):
for y in range(3):
if grid[x][y] > 1:
grid[x][y] -= 1
grid[i][j] += 1
ans = min(ans, abs(x - i) + abs(y - j) +
self.minimumMoves(grid))
grid[x][y] += 1
grid[i][j] -= 1
return ans
| Solution |
python | sympy__sympy | sympy/core/numbers.py | {
"start": 58510,
"end": 74180
} | class ____(Rational):
"""Represents integer numbers of any size.
Examples
========
>>> from sympy import Integer
>>> Integer(3)
3
If a float or a rational is passed to Integer, the fractional part
will be discarded; the effect is of rounding toward zero.
>>> Integer(3.8)
3
>>> Integer(-3.8)
-3
A string is acceptable input if it can be parsed as an integer:
>>> Integer("9" * 20)
99999999999999999999
It is rarely needed to explicitly instantiate an Integer, because
Python integers are automatically converted to Integer when they
are used in SymPy expressions.
"""
q = 1
is_integer = True
is_number = True
is_Integer = True
__slots__ = ()
def _as_mpf_val(self, prec):
return mlib.from_int(self.p, prec, rnd)
def _mpmath_(self, prec, rnd):
return mpmath.make_mpf(self._as_mpf_val(prec))
@cacheit
def __new__(cls, i):
if isinstance(i, str):
i = i.replace(' ', '')
# whereas we cannot, in general, make a Rational from an
# arbitrary expression, we can make an Integer unambiguously
# (except when a non-integer expression happens to round to
# an integer). So we proceed by taking int() of the input and
# let the int routines determine whether the expression can
# be made into an int or whether an error should be raised.
try:
ival = int(i)
except TypeError:
raise TypeError(
"Argument of Integer should be of numeric type, got %s." % i)
# We only work with well-behaved integer types. This converts, for
# example, numpy.int32 instances.
if ival == 1:
return S.One
if ival == -1:
return S.NegativeOne
if ival == 0:
return S.Zero
obj = Expr.__new__(cls)
obj.p = ival
return obj
def __getnewargs__(self):
return (self.p,)
# Arithmetic operations are here for efficiency
def __int__(self):
return self.p
def floor(self):
return Integer(self.p)
def ceiling(self):
return Integer(self.p)
def __floor__(self):
return self.floor()
def __ceil__(self):
return self.ceiling()
def __neg__(self):
return Integer(-self.p)
def __abs__(self):
if self.p >= 0:
return self
else:
return Integer(-self.p)
def __divmod__(self, other):
if isinstance(other, Integer) and global_parameters.evaluate:
return Tuple(*(divmod(self.p, other.p)))
else:
return Number.__divmod__(self, other)
def __rdivmod__(self, other):
if isinstance(other, int) and global_parameters.evaluate:
return Tuple(*(divmod(other, self.p)))
else:
try:
other = Number(other)
except TypeError:
msg = "unsupported operand type(s) for divmod(): '%s' and '%s'"
oname = type(other).__name__
sname = type(self).__name__
raise TypeError(msg % (oname, sname))
return Number.__divmod__(other, self)
# TODO make it decorator + bytecodehacks?
def __add__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p + other)
elif isinstance(other, Integer):
return Integer(self.p + other.p)
elif isinstance(other, Rational):
return Rational._new(self.p*other.q + other.p, other.q, 1)
return Rational.__add__(self, other)
else:
return Add(self, other)
def __radd__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other + self.p)
elif isinstance(other, Rational):
return Rational._new(other.p + self.p*other.q, other.q, 1)
return Rational.__radd__(self, other)
return Rational.__radd__(self, other)
def __sub__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p - other)
elif isinstance(other, Integer):
return Integer(self.p - other.p)
elif isinstance(other, Rational):
return Rational._new(self.p*other.q - other.p, other.q, 1)
return Rational.__sub__(self, other)
return Rational.__sub__(self, other)
def __rsub__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other - self.p)
elif isinstance(other, Rational):
return Rational._new(other.p - self.p*other.q, other.q, 1)
return Rational.__rsub__(self, other)
return Rational.__rsub__(self, other)
def __mul__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p*other)
elif isinstance(other, Integer):
return Integer(self.p*other.p)
elif isinstance(other, Rational):
return Rational._new(self.p*other.p, other.q, igcd(self.p, other.q))
return Rational.__mul__(self, other)
return Rational.__mul__(self, other)
def __rmul__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other*self.p)
elif isinstance(other, Rational):
return Rational._new(other.p*self.p, other.q, igcd(self.p, other.q))
return Rational.__rmul__(self, other)
return Rational.__rmul__(self, other)
def __mod__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(self.p % other)
elif isinstance(other, Integer):
return Integer(self.p % other.p)
return Rational.__mod__(self, other)
return Rational.__mod__(self, other)
def __rmod__(self, other):
if global_parameters.evaluate:
if isinstance(other, int):
return Integer(other % self.p)
elif isinstance(other, Integer):
return Integer(other.p % self.p)
return Rational.__rmod__(self, other)
return Rational.__rmod__(self, other)
def __pow__(self, other, mod=None):
if mod is not None:
try:
other_int = as_int(other)
mod_int = as_int(mod)
except ValueError:
pass
else:
return Integer(pow(self.p, other_int, mod_int))
return super().__pow__(other, mod)
def __eq__(self, other):
if isinstance(other, int):
return (self.p == other)
elif isinstance(other, Integer):
return (self.p == other.p)
return Rational.__eq__(self, other)
def __ne__(self, other):
return not self == other
def __gt__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p > other.p)
return Rational.__gt__(self, other)
def __lt__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p < other.p)
return Rational.__lt__(self, other)
def __ge__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p >= other.p)
return Rational.__ge__(self, other)
def __le__(self, other):
try:
other = _sympify(other)
except SympifyError:
return NotImplemented
if other.is_Integer:
return _sympify(self.p <= other.p)
return Rational.__le__(self, other)
def __hash__(self):
return hash(self.p)
def __index__(self):
return self.p
########################################
def _eval_is_odd(self):
return bool(self.p % 2)
def _eval_power(self, expt):
"""
Tries to do some simplifications on self**expt
Returns None if no further simplifications can be done.
Explanation
===========
When exponent is a fraction (so we have for example a square root),
we try to find a simpler representation by factoring the argument
up to factors of 2**15, e.g.
- sqrt(4) becomes 2
- sqrt(-4) becomes 2*I
- (2**(3+7)*3**(6+7))**Rational(1,7) becomes 6*18**(3/7)
Further simplification would require a special call to factorint on
the argument which is not done here for sake of speed.
"""
from sympy.ntheory.factor_ import perfect_power
if expt is S.Infinity:
if self.p > S.One:
return S.Infinity
# cases -1, 0, 1 are done in their respective classes
return S.Infinity + S.ImaginaryUnit*S.Infinity
if expt is S.NegativeInfinity:
return Rational._new(1, self, 1)**S.Infinity
if not isinstance(expt, Number):
# simplify when expt is even
# (-2)**k --> 2**k
if self.is_negative and expt.is_even:
return (-self)**expt
if isinstance(expt, Float):
# Rational knows how to exponentiate by a Float
return super()._eval_power(expt)
if not isinstance(expt, Rational):
return
if expt is S.Half and self.is_negative:
# we extract I for this special case since everyone is doing so
return S.ImaginaryUnit*Pow(-self, expt)
if expt.is_negative:
# invert base and change sign on exponent
ne = -expt
if self.is_negative:
return S.NegativeOne**expt*Rational._new(1, -self.p, 1)**ne
else:
return Rational._new(1, self.p, 1)**ne
# see if base is a perfect root, sqrt(4) --> 2
x, xexact = integer_nthroot(abs(self.p), expt.q)
if xexact:
# if it's a perfect root we've finished
result = Integer(x**abs(expt.p))
if self.is_negative:
result *= S.NegativeOne**expt
return result
# The following is an algorithm where we collect perfect roots
# from the factors of base.
# if it's not an nth root, it still might be a perfect power
b_pos = int(abs(self.p))
p = perfect_power(b_pos)
if p is not False:
dict = {p[0]: p[1]}
else:
dict = Integer(b_pos).factors(limit=2**15)
# now process the dict of factors
out_int = 1 # integer part
out_rad = 1 # extracted radicals
sqr_int = 1
sqr_gcd = 0
sqr_dict = {}
for prime, exponent in dict.items():
exponent *= expt.p
# remove multiples of expt.q: (2**12)**(1/10) -> 2*(2**2)**(1/10)
div_e, div_m = divmod(exponent, expt.q)
if div_e > 0:
out_int *= prime**div_e
if div_m > 0:
# see if the reduced exponent shares a gcd with e.q
# (2**2)**(1/10) -> 2**(1/5)
g = igcd(div_m, expt.q)
if g != 1:
out_rad *= Pow(prime, Rational._new(div_m//g, expt.q//g, 1))
else:
sqr_dict[prime] = div_m
# identify gcd of remaining powers
for p, ex in sqr_dict.items():
if sqr_gcd == 0:
sqr_gcd = ex
else:
sqr_gcd = igcd(sqr_gcd, ex)
if sqr_gcd == 1:
break
for k, v in sqr_dict.items():
sqr_int *= k**(v//sqr_gcd)
if sqr_int == b_pos and out_int == 1 and out_rad == 1:
result = None
else:
result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q))
if self.is_negative:
result *= Pow(S.NegativeOne, expt)
return result
def _eval_is_prime(self):
from sympy.ntheory.primetest import isprime
return isprime(self)
def _eval_is_composite(self):
if self > 1:
return fuzzy_not(self.is_prime)
else:
return False
def as_numer_denom(self):
return self, S.One
@_sympifyit('other', NotImplemented)
def __floordiv__(self, other):
if not isinstance(other, Expr):
return NotImplemented
if isinstance(other, Integer):
return Integer(self.p // other)
return divmod(self, other)[0]
def __rfloordiv__(self, other):
return Integer(Integer(other).p // self.p)
# These bitwise operations (__lshift__, __rlshift__, ..., __invert__) are defined
# for Integer only and not for general SymPy expressions. This is to achieve
# compatibility with the numbers.Integral ABC which only defines these operations
# among instances of numbers.Integral. Therefore, these methods check explicitly for
# integer types rather than using sympify because they should not accept arbitrary
# symbolic expressions and there is no symbolic analogue of numbers.Integral's
# bitwise operations.
def __lshift__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p << int(other))
else:
return NotImplemented
def __rlshift__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) << self.p)
else:
return NotImplemented
def __rshift__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p >> int(other))
else:
return NotImplemented
def __rrshift__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) >> self.p)
else:
return NotImplemented
def __and__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p & int(other))
else:
return NotImplemented
def __rand__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) & self.p)
else:
return NotImplemented
def __xor__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p ^ int(other))
else:
return NotImplemented
def __rxor__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) ^ self.p)
else:
return NotImplemented
def __or__(self, other):
if isinstance(other, (int, Integer, numbers.Integral)):
return Integer(self.p | int(other))
else:
return NotImplemented
def __ror__(self, other):
if isinstance(other, (int, numbers.Integral)):
return Integer(int(other) | self.p)
else:
return NotImplemented
def __invert__(self):
return Integer(~self.p)
# Add sympify converters
_sympy_converter[int] = Integer
| Integer |
python | langchain-ai__langchain | libs/core/langchain_core/retrievers.py | {
"start": 1176,
"end": 1536
} | class ____(TypedDict, total=False):
"""LangSmith parameters for tracing."""
ls_retriever_name: str
"""Retriever name."""
ls_vector_store_provider: str | None
"""Vector store provider."""
ls_embedding_provider: str | None
"""Embedding provider."""
ls_embedding_model: str | None
"""Embedding model."""
| LangSmithRetrieverParams |
python | jupyterlab__jupyterlab | examples/cell/main.py | {
"start": 773,
"end": 1667
} | class ____(ExtensionHandlerJinjaMixin, ExtensionHandlerMixin, JupyterHandler):
"""Handle requests between the main app page and notebook server."""
def get(self):
"""Get the main page for the application's interface."""
config_data = {
# Use camelCase here, since that's what the lab components expect
"appVersion": version,
"baseUrl": self.base_url,
"token": self.settings["token"],
"fullStaticUrl": ujoin(self.base_url, "static", self.name),
"frontendUrl": ujoin(self.base_url, "example/"),
}
return self.write(
self.render_template(
"index.html",
static=self.static_url,
base_url=self.base_url,
token=self.settings["token"],
page_config=config_data,
)
)
| ExampleHandler |
python | encode__django-rest-framework | tests/test_description.py | {
"start": 1319,
"end": 4726
} | class ____(TestCase):
def test_view_name_uses_class_name(self):
"""
Ensure view names are based on the class name.
"""
class MockView(APIView):
pass
assert MockView().get_view_name() == 'Mock'
def test_view_name_uses_name_attribute(self):
class MockView(APIView):
name = 'Foo'
assert MockView().get_view_name() == 'Foo'
def test_view_name_uses_suffix_attribute(self):
class MockView(APIView):
suffix = 'List'
assert MockView().get_view_name() == 'Mock List'
def test_view_name_preferences_name_over_suffix(self):
class MockView(APIView):
name = 'Foo'
suffix = 'List'
assert MockView().get_view_name() == 'Foo'
def test_view_description_uses_docstring(self):
"""Ensure view descriptions are based on the docstring."""
class MockView(APIView):
"""an example docstring
====================
* list
* list
another header
--------------
code block
indented
# hash style header #
```json
[{
"alpha": 1,
"beta": "this is a string"
}]
```"""
assert MockView().get_view_description() == DESCRIPTION
def test_view_description_uses_description_attribute(self):
class MockView(APIView):
description = 'Foo'
assert MockView().get_view_description() == 'Foo'
def test_view_description_allows_empty_description(self):
class MockView(APIView):
"""Description."""
description = ''
assert MockView().get_view_description() == ''
def test_view_description_can_be_empty(self):
"""
Ensure that if a view has no docstring,
then it's description is the empty string.
"""
class MockView(APIView):
pass
assert MockView().get_view_description() == ''
def test_view_description_can_be_promise(self):
"""
Ensure a view may have a docstring that is actually a lazily evaluated
class that can be converted to a string.
See: https://github.com/encode/django-rest-framework/issues/1708
"""
# use a mock object instead of gettext_lazy to ensure that we can't end
# up with a test case string in our l10n catalog
class MockLazyStr:
def __init__(self, string):
self.s = string
def __str__(self):
return self.s
class MockView(APIView):
__doc__ = MockLazyStr("a gettext string")
assert MockView().get_view_description() == 'a gettext string'
@pytest.mark.skipif(not apply_markdown, reason="Markdown is not installed")
def test_markdown(self):
"""
Ensure markdown to HTML works as expected.
"""
assert apply_markdown(DESCRIPTION) == MARKDOWN_DOCSTRING
def test_dedent_tabs():
result = 'first string\n\nsecond string'
assert dedent(" first string\n\n second string") == result
assert dedent("first string\n\n second string") == result
assert dedent("\tfirst string\n\n\tsecond string") == result
assert dedent("first string\n\n\tsecond string") == result
| TestViewNamesAndDescriptions |
python | pallets__werkzeug | src/werkzeug/sansio/multipart.py | {
"start": 643,
"end": 684
} | class ____(Event):
data: bytes
| Epilogue |
python | doocs__leetcode | solution/2900-2999/2956.Find Common Elements Between Two Arrays/Solution.py | {
"start": 0,
"end": 217
} | class ____:
def findIntersectionValues(self, nums1: List[int], nums2: List[int]) -> List[int]:
s1, s2 = set(nums1), set(nums2)
return [sum(x in s2 for x in nums1), sum(x in s1 for x in nums2)]
| Solution |
python | kamyu104__LeetCode-Solutions | Python/count-triplets-with-even-xor-set-bits-i.py | {
"start": 1392,
"end": 1718
} | class ____(object):
def tripletCount(self, a, b, c):
"""
:type a: List[int]
:type b: List[int]
:type c: List[int]
:rtype: int
"""
def popcount(x):
return bin(x).count('1')
return sum(popcount(x^y^z)%2 == 0 for x in a for y in b for z in c)
| Solution3 |
python | walkccc__LeetCode | solutions/3523. Make Array Non-decreasing/3523.py | {
"start": 0,
"end": 194
} | class ____:
def maximumPossibleSize(self, nums: list[int]) -> int:
ans = 0
prev = 0
for num in nums:
if num >= prev:
prev = num
ans += 1
return ans
| Solution |
python | keras-team__keras | keras/src/ops/image_test.py | {
"start": 34107,
"end": 69343
} | class ____(testing.TestCase):
def setUp(self):
# Defaults to channels_last
self.data_format = backend.image_data_format()
backend.set_image_data_format("channels_last")
return super().setUp()
def tearDown(self):
backend.set_image_data_format(self.data_format)
return super().tearDown()
def test_rgb_to_grayscale(self):
# Test channels_last
x = np.random.random((50, 50, 3)).astype("float32") * 255
out = kimage.rgb_to_grayscale(x)
ref_out = tf.image.rgb_to_grayscale(x)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
x = np.random.random((2, 50, 50, 3)).astype("float32") * 255
out = kimage.rgb_to_grayscale(x)
ref_out = tf.image.rgb_to_grayscale(x)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
# Test channels_first
backend.set_image_data_format("channels_first")
x = np.random.random((3, 50, 50)).astype("float32") * 255
out = kimage.rgb_to_grayscale(x)
ref_out = tf.image.rgb_to_grayscale(np.transpose(x, [1, 2, 0]))
ref_out = tf.transpose(ref_out, [2, 0, 1])
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
x = np.random.random((2, 3, 50, 50)).astype("float32") * 255
out = kimage.rgb_to_grayscale(x)
ref_out = tf.image.rgb_to_grayscale(np.transpose(x, [0, 2, 3, 1]))
ref_out = tf.transpose(ref_out, [0, 3, 1, 2])
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
# Test class
out = kimage.RGBToGrayscale()(x)
self.assertAllClose(ref_out, out)
def test_rgb_to_hsv(self):
# Test channels_last
x = np.random.random((50, 50, 3)).astype("float32")
out = kimage.rgb_to_hsv(x)
ref_out = tf.image.rgb_to_hsv(x)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
x = np.random.random((2, 50, 50, 3)).astype("float32")
out = kimage.rgb_to_hsv(x)
ref_out = tf.image.rgb_to_hsv(x)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
# Test channels_first
backend.set_image_data_format("channels_first")
x = np.random.random((3, 50, 50)).astype("float32")
out = kimage.rgb_to_hsv(x)
ref_out = tf.image.rgb_to_hsv(np.transpose(x, [1, 2, 0]))
ref_out = tf.transpose(ref_out, [2, 0, 1])
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
x = np.random.random((2, 3, 50, 50)).astype("float32")
out = kimage.rgb_to_hsv(x)
ref_out = tf.image.rgb_to_hsv(np.transpose(x, [0, 2, 3, 1]))
ref_out = tf.transpose(ref_out, [0, 3, 1, 2])
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
# Test class
out = kimage.RGBToHSV()(x)
self.assertAllClose(ref_out, out)
def test_hsv_to_rgb(self):
# Test channels_last
x = np.random.random((50, 50, 3)).astype("float32")
out = kimage.hsv_to_rgb(x)
ref_out = tf.image.hsv_to_rgb(x)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
x = np.random.random((2, 50, 50, 3)).astype("float32")
out = kimage.hsv_to_rgb(x)
ref_out = tf.image.hsv_to_rgb(x)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
# Test channels_first
backend.set_image_data_format("channels_first")
x = np.random.random((3, 50, 50)).astype("float32")
out = kimage.hsv_to_rgb(x)
ref_out = tf.image.hsv_to_rgb(np.transpose(x, [1, 2, 0]))
ref_out = tf.transpose(ref_out, [2, 0, 1])
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
x = np.random.random((2, 3, 50, 50)).astype("float32")
out = kimage.hsv_to_rgb(x)
ref_out = tf.image.hsv_to_rgb(np.transpose(x, [0, 2, 3, 1]))
ref_out = tf.transpose(ref_out, [0, 3, 1, 2])
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out)
# Test class
out = kimage.HSVToRGB()(x)
self.assertAllClose(ref_out, out)
@parameterized.named_parameters(
named_product(
interpolation=[
"bilinear",
"nearest",
"lanczos3",
"lanczos5",
"bicubic",
],
antialias=[True, False],
)
)
def test_resize(self, interpolation, antialias):
if backend.backend() == "torch":
if "lanczos" in interpolation:
self.skipTest(
"Resizing with Lanczos interpolation is "
"not supported by the PyTorch backend. "
f"Received: interpolation={interpolation}."
)
if interpolation == "bicubic" and antialias is False:
self.skipTest(
"Resizing with Bicubic interpolation in "
"PyTorch backend produces noise. Please "
"turn on anti-aliasing. "
f"Received: interpolation={interpolation}, "
f"antialias={antialias}."
)
# Test channels_last
x = np.random.random((30, 30, 3)).astype("float32") * 255
out = kimage.resize(
x,
size=(15, 15),
interpolation=interpolation,
antialias=antialias,
)
ref_out = tf.image.resize(
x,
size=(15, 15),
method=interpolation,
antialias=antialias,
)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-4)
x = np.random.random((2, 30, 30, 3)).astype("float32") * 255
out = kimage.resize(
x,
size=(15, 15),
interpolation=interpolation,
antialias=antialias,
)
ref_out = tf.image.resize(
x,
size=(15, 15),
method=interpolation,
antialias=antialias,
)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-4)
# Test channels_first
backend.set_image_data_format("channels_first")
x = np.random.random((3, 30, 30)).astype("float32") * 255
out = kimage.resize(
x,
size=(15, 15),
interpolation=interpolation,
antialias=antialias,
)
ref_out = tf.image.resize(
np.transpose(x, [1, 2, 0]),
size=(15, 15),
method=interpolation,
antialias=antialias,
)
ref_out = tf.transpose(ref_out, [2, 0, 1])
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-4)
x = np.random.random((2, 3, 30, 30)).astype("float32") * 255
out = kimage.resize(
x,
size=(15, 15),
interpolation=interpolation,
antialias=antialias,
)
ref_out = tf.image.resize(
np.transpose(x, [0, 2, 3, 1]),
size=(15, 15),
method=interpolation,
antialias=antialias,
)
ref_out = tf.transpose(ref_out, [0, 3, 1, 2])
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-4)
# Test class
out = kimage.Resize(
size=(15, 15),
interpolation=interpolation,
antialias=antialias,
)(x)
self.assertAllClose(ref_out, out, atol=1e-4)
def test_resize_uint8_round(self):
x = np.array([0, 1, 254, 255], dtype="uint8").reshape(1, 2, 2, 1)
expected = np.array(
# OpenCV as gold standard.
# [
# [0, 0, 1, 1],
# [64, 64, 64, 65],
# [191, 191, 191, 192],
# [254, 254, 255, 255],
# ]
#
# Resize without `round` - differences in 8 points
# [
# [0, 0, 0, 1],
# [63, 63, 64, 64],
# [190, 190, 191, 191],
# [254, 254, 254, 255],
# ]
#
# Resize with `round` - differences in 2 points
[
[0, 0, 1, 1],
[64, 64, 64, 64],
[190, 191, 191, 192],
[254, 254, 255, 255],
],
dtype="uint8",
).reshape(1, 4, 4, 1)
out = kimage.resize(
x,
size=(4, 4),
interpolation="bilinear",
antialias=False,
)
self.assertEqual(tuple(out.shape), tuple(expected.shape))
self.assertEqual(backend.standardize_dtype(out.dtype), "uint8")
self.assertAllClose(out, expected, atol=1e-4)
def test_resize_uint8_round_saturate(self):
x = np.array([0, 1, 254, 255], dtype="uint8").reshape(1, 2, 2, 1)
expected = np.array(
# OpenCV as gold standard. Same for `torch` backend.
(
[
[0, 0, 0, 0],
[57, 58, 58, 59],
[196, 197, 197, 198],
[255, 255, 255, 255],
]
if "torch" == backend.backend()
# Resize without `round` and `saturate_cast` - differences in
# 16 points
# [
# [234, 234, 235, 235],
# [-5, -6, -5, -6],
# [5, 4, 5, 4],
# [-235, -235, -234, -234],
# ]
#
# Resize with `round` and `saturate_cast` - differences in
# 8 points
else [
[0, 0, 0, 0],
[53, 53, 53, 54],
[201, 202, 202, 202],
[255, 255, 255, 255],
]
),
dtype="uint8",
).reshape(1, 4, 4, 1)
out = kimage.resize(
x,
size=(4, 4),
interpolation="bicubic",
antialias=False,
)
self.assertEqual(tuple(out.shape), tuple(expected.shape))
self.assertEqual(backend.standardize_dtype(out.dtype), "uint8")
self.assertAllClose(out, expected, atol=1e-4)
def test_resize_with_crop(self):
# Test channels_last
x = np.random.random((60, 50, 3)).astype("float32") * 255
out = kimage.resize(x, size=(25, 25), crop_to_aspect_ratio=True)
self.assertEqual(out.shape, (25, 25, 3))
x = np.random.random((2, 50, 60, 3)).astype("float32") * 255
out = kimage.resize(x, size=(25, 25), crop_to_aspect_ratio=True)
self.assertEqual(out.shape, (2, 25, 25, 3))
# Test channels_first
backend.set_image_data_format("channels_first")
x = np.random.random((3, 60, 50)).astype("float32") * 255
out = kimage.resize(x, size=(25, 25), crop_to_aspect_ratio=True)
self.assertEqual(out.shape, (3, 25, 25))
x = np.random.random((2, 3, 50, 60)).astype("float32") * 255
out = kimage.resize(x, size=(25, 25), crop_to_aspect_ratio=True)
self.assertEqual(out.shape, (2, 3, 25, 25))
@parameterized.named_parameters(named_product(fill_value=[1.0, 2.0]))
def test_resize_with_pad(self, fill_value):
# Test channels_last
x = np.random.random((60, 50, 3)).astype("float32") * 255
out = kimage.resize(
x,
size=(25, 25),
pad_to_aspect_ratio=True,
fill_value=fill_value,
)
self.assertEqual(out.shape, (25, 25, 3))
x = np.random.random((2, 50, 60, 3)).astype("float32") * 255
out = kimage.resize(
x, size=(25, 25), pad_to_aspect_ratio=True, fill_value=fill_value
)
self.assertEqual(out.shape, (2, 25, 25, 3))
# Test channels_first
backend.set_image_data_format("channels_first")
x = np.random.random((3, 60, 50)).astype("float32") * 255
out = kimage.resize(
x, size=(25, 25), pad_to_aspect_ratio=True, fill_value=fill_value
)
self.assertEqual(out.shape, (3, 25, 25))
x = np.random.random((2, 3, 50, 60)).astype("float32") * 255
out = kimage.resize(
x, size=(25, 25), pad_to_aspect_ratio=True, fill_value=fill_value
)
self.assertEqual(out.shape, (2, 3, 25, 25))
x = np.ones((2, 3, 10, 10)) * 128
out = kimage.resize(
x, size=(4, 4), pad_to_aspect_ratio=True, fill_value=fill_value
)
self.assertEqual(out.shape, (2, 3, 4, 4))
self.assertAllClose(out[:, 0, :, :], np.ones((2, 4, 4)) * 128)
x = np.ones((2, 3, 10, 8)) * 128
out = kimage.resize(
x, size=(4, 4), pad_to_aspect_ratio=True, fill_value=fill_value
)
self.assertEqual(out.shape, (2, 3, 4, 4))
self.assertAllClose(
out,
np.concatenate(
[
np.ones((2, 3, 4, 1)) * 96.25,
np.ones((2, 3, 4, 2)) * 128.0,
np.ones((2, 3, 4, 1)) * 96.25,
],
axis=3,
),
atol=1.0,
)
@parameterized.named_parameters(
named_product(
interpolation=["bilinear", "nearest"],
fill_mode=["constant", "nearest", "wrap", "mirror", "reflect"],
)
)
def test_affine_transform(self, interpolation, fill_mode):
if backend.backend() == "tensorflow" and fill_mode == "mirror":
self.skipTest(
"In tensorflow backend, applying affine_transform with "
"fill_mode=mirror is not supported"
)
if backend.backend() == "tensorflow" and fill_mode == "wrap":
self.skipTest(
"In tensorflow backend, the numerical results of applying "
"affine_transform with fill_mode=wrap is inconsistent with"
"scipy"
)
# TODO: `nearest` interpolation in jax and torch causes random index
# shifting, resulting in significant differences in output which leads
# to failure
if backend.backend() in ("jax", "torch") and interpolation == "nearest":
self.skipTest(
f"In {backend.backend()} backend, "
f"interpolation={interpolation} causes index shifting and "
"leads test failure"
)
# Test channels_last
np.random.seed(42)
x = np.random.uniform(size=(50, 50, 3)).astype("float32") * 255
transform = np.random.uniform(size=(6)).astype("float32")
transform = np.pad(transform, (0, 2)) # makes c0, c1 always 0
out = kimage.affine_transform(
x, transform, interpolation=interpolation, fill_mode=fill_mode
)
coordinates = _compute_affine_transform_coordinates(x, transform)
ref_out = _fixed_map_coordinates(
x,
coordinates,
order=AFFINE_TRANSFORM_INTERPOLATIONS[interpolation],
fill_mode=fill_mode,
)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-2)
x = np.random.uniform(size=(2, 50, 50, 3)).astype("float32") * 255
transform = np.random.uniform(size=(2, 6)).astype("float32")
transform = np.pad(transform, [(0, 0), (0, 2)]) # makes c0, c1 always 0
out = kimage.affine_transform(
x,
transform,
interpolation=interpolation,
fill_mode=fill_mode,
)
coordinates = _compute_affine_transform_coordinates(x, transform)
ref_out = np.stack(
[
_fixed_map_coordinates(
x[i],
coordinates[i],
order=AFFINE_TRANSFORM_INTERPOLATIONS[interpolation],
fill_mode=fill_mode,
)
for i in range(x.shape[0])
],
axis=0,
)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-2)
# Test channels_first
backend.set_image_data_format("channels_first")
x = np.random.uniform(size=(3, 50, 50)).astype("float32") * 255
transform = np.random.uniform(size=(6)).astype("float32")
transform = np.pad(transform, (0, 2)) # makes c0, c1 always 0
out = kimage.affine_transform(
x, transform, interpolation=interpolation, fill_mode=fill_mode
)
coordinates = _compute_affine_transform_coordinates(
np.transpose(x, [1, 2, 0]), transform
)
ref_out = _fixed_map_coordinates(
np.transpose(x, [1, 2, 0]),
coordinates,
order=AFFINE_TRANSFORM_INTERPOLATIONS[interpolation],
fill_mode=fill_mode,
)
ref_out = np.transpose(ref_out, [2, 0, 1])
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-2)
x = np.random.uniform(size=(2, 3, 50, 50)).astype("float32") * 255
transform = np.random.uniform(size=(2, 6)).astype("float32")
transform = np.pad(transform, [(0, 0), (0, 2)]) # makes c0, c1 always 0
out = kimage.affine_transform(
x,
transform,
interpolation=interpolation,
fill_mode=fill_mode,
)
coordinates = _compute_affine_transform_coordinates(
np.transpose(x, [0, 2, 3, 1]), transform
)
ref_out = np.stack(
[
_fixed_map_coordinates(
np.transpose(x[i], [1, 2, 0]),
coordinates[i],
order=AFFINE_TRANSFORM_INTERPOLATIONS[interpolation],
fill_mode=fill_mode,
)
for i in range(x.shape[0])
],
axis=0,
)
ref_out = np.transpose(ref_out, [0, 3, 1, 2])
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-2)
# Test class
out = kimage.AffineTransform(
interpolation=interpolation, fill_mode=fill_mode
)(x, transform)
self.assertAllClose(ref_out, out, atol=1e-2)
@parameterized.named_parameters(
named_product(
size=[(3, 3), (5, 5)],
strides=[None, (1, 1), (2, 2)],
dilation_rate=[1, 3],
padding=["valid", "same"],
)
)
def test_extract_patches(self, size, strides, dilation_rate, padding):
patch_h, patch_w = size[0], size[1]
if strides is None:
strides_h, strides_w = patch_h, patch_w
else:
strides_h, strides_w = strides[0], strides[1]
if (
backend.backend() == "tensorflow"
and strides_h > 1
or strides_w > 1
and dilation_rate > 1
):
pytest.skip("dilation_rate>1 with strides>1 not supported with TF")
# Test channels_last
image = np.random.uniform(size=(1, 20, 20, 3)).astype("float32")
patches_out = kimage.extract_patches(
image,
size=size,
strides=strides,
dilation_rate=dilation_rate,
padding=padding,
)
patches_ref = tf.image.extract_patches(
image,
sizes=(1, patch_h, patch_w, 1),
strides=(1, strides_h, strides_w, 1),
rates=(1, dilation_rate, dilation_rate, 1),
padding=padding.upper(),
)
self.assertEqual(tuple(patches_out.shape), tuple(patches_ref.shape))
self.assertAllClose(patches_ref, patches_out, atol=1e-2)
# Test channels_first
if backend.backend() == "tensorflow":
# tensorflow doesn't support channels_first in
# `kimage.extract_patches`
return
backend.set_image_data_format("channels_first")
image = np.random.uniform(size=(1, 3, 20, 20)).astype("float32")
patches_out = kimage.extract_patches(
image,
size=size,
strides=strides,
dilation_rate=dilation_rate,
padding=padding,
)
patches_ref = tf.image.extract_patches(
np.transpose(image, [0, 2, 3, 1]),
sizes=(1, patch_h, patch_w, 1),
strides=(1, strides_h, strides_w, 1),
rates=(1, dilation_rate, dilation_rate, 1),
padding=padding.upper(),
)
patches_ref = tf.transpose(patches_ref, [0, 3, 1, 2])
self.assertEqual(tuple(patches_out.shape), tuple(patches_ref.shape))
self.assertAllClose(patches_ref, patches_out, atol=1e-2)
# Test class
patches_out = kimage.ExtractPatches(
size=size,
strides=strides,
dilation_rate=dilation_rate,
padding=padding,
)(image)
self.assertAllClose(patches_ref, patches_out, atol=1e-2)
@parameterized.named_parameters(
named_product(
# (input_shape, coordinates_shape)
shape=[((5,), (7,)), ((3, 4, 5), (2, 3, 4))],
# TODO: scipy.ndimage.map_coordinates does not support float16
# TODO: torch cpu does not support round & floor for float16
dtype=["uint8", "int32", "float32"],
order=[0, 1],
fill_mode=["constant", "nearest", "wrap", "mirror", "reflect"],
)
)
def test_map_coordinates(self, shape, dtype, order, fill_mode):
input_shape, coordinates_shape = shape
input = np.arange(math.prod(input_shape), dtype=dtype).reshape(
input_shape
)
coordinates_dtype = "float32" if "int" in dtype else dtype
coordinates = [
(size - 1)
* np.random.uniform(size=coordinates_shape).astype(
coordinates_dtype
)
for size in input_shape
]
output = kimage.map_coordinates(input, coordinates, order, fill_mode)
expected = _fixed_map_coordinates(input, coordinates, order, fill_mode)
self.assertAllClose(output, expected)
# Test class
output = kimage.MapCoordinates(order, fill_mode)(input, coordinates)
self.assertAllClose(output, expected)
@parameterized.parameters(
[
(0, 0, 3, 3, None, None),
(1, 0, 4, 3, None, None),
(0, 1, 3, 4, None, None),
(0, 0, 4, 3, None, None),
(0, 0, 3, 4, None, None),
(0, 0, None, None, 0, 1),
(0, 0, None, None, 1, 0),
(1, 2, None, None, 3, 4),
]
)
def test_pad_images(
self,
top_padding,
left_padding,
target_height,
target_width,
bottom_padding,
right_padding,
):
# Test channels_last
image = np.random.uniform(size=(3, 3, 1)).astype("float32")
_target_height = target_height # For `tf.image.pad_to_bounding_box`
_target_width = target_width # For `tf.image.pad_to_bounding_box`
if _target_height is None:
_target_height = image.shape[0] + top_padding + bottom_padding
if _target_width is None:
_target_width = image.shape[1] + left_padding + right_padding
padded_image = kimage.pad_images(
image,
top_padding,
left_padding,
bottom_padding,
right_padding,
target_height,
target_width,
)
ref_padded_image = tf.image.pad_to_bounding_box(
image, top_padding, left_padding, _target_height, _target_width
)
self.assertEqual(
tuple(padded_image.shape), tuple(ref_padded_image.shape)
)
self.assertAllClose(ref_padded_image, padded_image)
# Test channels_first
backend.set_image_data_format("channels_first")
image = np.random.uniform(size=(1, 3, 3)).astype("float32")
padded_image = kimage.pad_images(
image,
top_padding,
left_padding,
bottom_padding,
right_padding,
target_height,
target_width,
)
ref_padded_image = tf.image.pad_to_bounding_box(
np.transpose(image, [1, 2, 0]),
top_padding,
left_padding,
_target_height,
_target_width,
)
ref_padded_image = tf.transpose(ref_padded_image, [2, 0, 1])
self.assertEqual(
tuple(padded_image.shape), tuple(ref_padded_image.shape)
)
self.assertAllClose(ref_padded_image, padded_image)
# Test class
padded_image = kimage.PadImages(
top_padding,
left_padding,
bottom_padding,
right_padding,
target_height,
target_width,
)(image)
self.assertAllClose(ref_padded_image, padded_image)
@parameterized.parameters(
[
(0, 0, 3, 3, None, None),
(1, 0, 4, 3, None, None),
(0, 1, 3, 4, None, None),
(0, 0, 4, 3, None, None),
(0, 0, 3, 4, None, None),
(0, 0, None, None, 0, 1),
(0, 0, None, None, 1, 0),
(1, 2, None, None, 3, 4),
]
)
def test_crop_images(
self,
top_cropping,
left_cropping,
target_height,
target_width,
bottom_cropping,
right_cropping,
):
# Test channels_last
image = np.random.uniform(size=(10, 10, 1)).astype("float32")
_target_height = target_height # For `tf.image.pad_to_bounding_box`
_target_width = target_width # For `tf.image.pad_to_bounding_box`
if _target_height is None:
_target_height = image.shape[0] - top_cropping - bottom_cropping
if _target_width is None:
_target_width = image.shape[1] - left_cropping - right_cropping
cropped_image = kimage.crop_images(
image,
top_cropping,
left_cropping,
bottom_cropping,
right_cropping,
target_height,
target_width,
)
ref_cropped_image = tf.image.crop_to_bounding_box(
image, top_cropping, left_cropping, _target_height, _target_width
)
self.assertEqual(
tuple(cropped_image.shape), tuple(ref_cropped_image.shape)
)
self.assertAllClose(ref_cropped_image, cropped_image)
# Test channels_first
backend.set_image_data_format("channels_first")
image = np.random.uniform(size=(1, 10, 10)).astype("float32")
cropped_image = kimage.crop_images(
image,
top_cropping,
left_cropping,
bottom_cropping,
right_cropping,
target_height,
target_width,
)
ref_cropped_image = tf.image.crop_to_bounding_box(
np.transpose(image, [1, 2, 0]),
top_cropping,
left_cropping,
_target_height,
_target_width,
)
ref_cropped_image = tf.transpose(ref_cropped_image, [2, 0, 1])
self.assertEqual(
tuple(cropped_image.shape), tuple(ref_cropped_image.shape)
)
self.assertAllClose(ref_cropped_image, cropped_image)
# Test class
cropped_image = kimage.CropImages(
top_cropping,
left_cropping,
bottom_cropping,
right_cropping,
target_height,
target_width,
)(image)
self.assertAllClose(ref_cropped_image, cropped_image)
@parameterized.named_parameters(
named_product(
interpolation=["bilinear", "nearest"],
)
)
def test_perspective_transform(self, interpolation):
# Test channels_last
np.random.seed(42)
x = np.random.uniform(size=(50, 50, 3)).astype("float32")
start_points = np.random.uniform(size=(1, 4, 2)).astype("float32")
end_points = np.random.uniform(size=(1, 4, 2)).astype("float32")
out = kimage.perspective_transform(
x, start_points, end_points, interpolation=interpolation
)
ref_out = _perspective_transform_numpy(
x, start_points, end_points, interpolation=interpolation
)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-2, rtol=1e-2)
# Test channels_first
backend.set_image_data_format("channels_first")
x = np.random.uniform(size=(3, 50, 50)).astype("float32")
start_points = np.random.uniform(size=(1, 4, 2)).astype("float32")
end_points = np.random.uniform(size=(1, 4, 2)).astype("float32")
out = kimage.perspective_transform(
x, start_points, end_points, interpolation=interpolation
)
ref_out = _perspective_transform_numpy(
x,
start_points,
end_points,
interpolation=interpolation,
data_format="channels_first",
)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-2, rtol=1e-2)
def test_gaussian_blur(self):
# Test channels_last
backend.set_image_data_format("channels_last")
np.random.seed(42)
x = np.random.uniform(size=(50, 50, 3)).astype("float32")
kernel_size = np.array([3, 3])
sigma = np.random.uniform(size=(2,)).astype("float32")
out = kimage.gaussian_blur(
x,
kernel_size,
sigma,
data_format="channels_last",
)
ref_out = gaussian_blur_np(
x,
kernel_size,
sigma,
data_format="channels_last",
)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-2, rtol=1e-2)
# Test channels_first
backend.set_image_data_format("channels_first")
x = np.random.uniform(size=(3, 50, 50)).astype("float32")
kernel_size = np.array([3, 3])
sigma = np.random.uniform(size=(2,)).astype("float32")
out = kimage.gaussian_blur(
x,
kernel_size,
sigma,
data_format="channels_first",
)
ref_out = gaussian_blur_np(
x,
kernel_size,
sigma,
data_format="channels_first",
)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-2, rtol=1e-2)
def test_elastic_transform(self):
# Test channels_last
backend.set_image_data_format("channels_last")
np.random.seed(42)
x = np.random.uniform(size=(50, 50, 3)).astype("float32")
alpha, sigma, seed = 20.0, 5.0, 42
out = kimage.elastic_transform(
x,
alpha=alpha,
sigma=sigma,
seed=seed,
data_format="channels_last",
)
ref_out = elastic_transform_np(
x,
alpha=alpha,
sigma=sigma,
seed=seed,
data_format="channels_last",
)
out = backend.convert_to_numpy(out)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(
np.mean(ref_out), np.mean(out), atol=1e-2, rtol=1e-2
)
self.assertAllClose(np.var(ref_out), np.var(out), atol=1e-2, rtol=1e-2)
# Test channels_first
backend.set_image_data_format("channels_first")
x = np.random.uniform(size=(3, 50, 50)).astype("float32")
alpha, sigma, seed = 20.0, 5.0, 42
ref_out = elastic_transform_np(
x,
alpha=alpha,
sigma=sigma,
seed=seed,
data_format="channels_first",
)
out = kimage.elastic_transform(
x,
alpha=alpha,
sigma=sigma,
seed=seed,
data_format="channels_first",
)
out = backend.convert_to_numpy(out)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(
np.mean(ref_out), np.mean(out), atol=1e-2, rtol=1e-2
)
self.assertAllClose(np.var(ref_out), np.var(out), atol=1e-2, rtol=1e-2)
def test_map_coordinates_constant_padding(self):
input_img = tf.ones((2, 2), dtype=tf.uint8)
# one pixel outside of the input space around the edges
grid = tf.stack(
tf.meshgrid(
tf.range(-1, 3, dtype=tf.float32),
tf.range(-1, 3, dtype=tf.float32),
indexing="ij",
),
axis=0,
)
out = backend.convert_to_numpy(
kimage.map_coordinates(
input_img, grid, order=0, fill_mode="constant", fill_value=0
)
)
# check for ones in the middle and zeros around the edges
self.assertTrue(np.all(out[:1] == 0))
self.assertTrue(np.all(out[-1:] == 0))
self.assertTrue(np.all(out[:, :1] == 0))
self.assertTrue(np.all(out[:, -1:] == 0))
self.assertTrue(np.all(out[1:3, 1:3] == 1))
@parameterized.named_parameters(
named_product(
method=["linear", "cubic", "lanczos3", "lanczos5"],
antialias=[True, False],
)
)
def test_scale_and_translate(self, method, antialias):
images = np.random.random((30, 30, 3)).astype("float32") * 255
scale = np.array([2.0, 2.0]).astype("float32")
translation = -(scale / 2.0 - 0.5)
out = kimage.scale_and_translate(
images,
output_shape=(15, 15, 3),
scale=scale,
translation=translation,
spatial_dims=(0, 1),
method=method,
antialias=antialias,
)
ref_out = jax.image.scale_and_translate(
images,
shape=(15, 15, 3),
spatial_dims=(0, 1),
scale=scale,
translation=translation,
method=method,
antialias=antialias,
)
self.assertEqual(tuple(out.shape), tuple(ref_out.shape))
self.assertAllClose(ref_out, out, atol=1e-4)
| ImageOpsCorrectnessTest |
python | apache__airflow | airflow-core/src/airflow/models/dag.py | {
"start": 6704,
"end": 10409
} | class ____(AirflowException):
"""
Exception raised when a model populates data interval fields incorrectly.
The data interval fields should either both be None (for runs scheduled
prior to AIP-39), or both be datetime (for runs scheduled after AIP-39 is
implemented). This is raised if exactly one of the fields is None.
"""
_template = (
"Inconsistent {cls}: {start[0]}={start[1]!r}, {end[0]}={end[1]!r}, "
"they must be either both None or both datetime"
)
def __init__(self, instance: Any, start_field_name: str, end_field_name: str) -> None:
self._class_name = type(instance).__name__
self._start_field = (start_field_name, getattr(instance, start_field_name))
self._end_field = (end_field_name, getattr(instance, end_field_name))
def __str__(self) -> str:
return self._template.format(cls=self._class_name, start=self._start_field, end=self._end_field)
def _get_model_data_interval(
instance: Any,
start_field_name: str,
end_field_name: str,
) -> DataInterval | None:
start = timezone.coerce_datetime(getattr(instance, start_field_name))
end = timezone.coerce_datetime(getattr(instance, end_field_name))
if start is None:
if end is not None:
raise InconsistentDataInterval(instance, start_field_name, end_field_name)
return None
if end is None:
raise InconsistentDataInterval(instance, start_field_name, end_field_name)
return DataInterval(start, end)
def get_last_dagrun(dag_id: str, session: Session, include_manually_triggered: bool = False) -> DagRun | None:
"""
Return the last dag run for a dag, None if there was none.
Last dag run can be any type of run e.g. scheduled or backfilled.
Overridden DagRuns are ignored.
"""
DR = DagRun
query = select(DR).where(DR.dag_id == dag_id, DR.logical_date.is_not(None))
if not include_manually_triggered:
query = query.where(DR.run_type != DagRunType.MANUAL)
query = query.order_by(DR.logical_date.desc())
return session.scalar(query.limit(1))
def get_asset_triggered_next_run_info(
dag_ids: list[str], *, session: Session
) -> dict[str, dict[str, int | str]]:
"""
Get next run info for a list of dag_ids.
Given a list of dag_ids, get string representing how close any that are asset triggered are
their next run, e.g. "1 of 2 assets updated".
"""
from airflow.models.asset import AssetDagRunQueue as ADRQ, DagScheduleAssetReference
return {
x.dag_id: {
"uri": x.uri,
"ready": x.ready,
"total": x.total,
}
for x in session.execute(
select(
DagScheduleAssetReference.dag_id,
# This is a dirty hack to workaround group by requiring an aggregate,
# since grouping by asset is not what we want to do here...but it works
case((func.count() == 1, func.max(AssetModel.uri)), else_="").label("uri"),
func.count().label("total"),
func.sum(case((ADRQ.target_dag_id.is_not(None), 1), else_=0)).label("ready"),
)
.join(
ADRQ,
and_(
ADRQ.asset_id == DagScheduleAssetReference.asset_id,
ADRQ.target_dag_id == DagScheduleAssetReference.dag_id,
),
isouter=True,
)
.join(AssetModel, AssetModel.id == DagScheduleAssetReference.asset_id)
.group_by(DagScheduleAssetReference.dag_id)
.where(DagScheduleAssetReference.dag_id.in_(dag_ids))
).all()
}
| InconsistentDataInterval |
python | getsentry__sentry | src/sentry/notifications/notification_action/issue_alert_registry/handlers/azure_devops_issue_alert_handler.py | {
"start": 293,
"end": 366
} | class ____(TicketingIssueAlertHandler):
pass
| AzureDevopsIssueAlertHandler |
python | ansible__ansible | lib/ansible/_internal/_json/_profiles/_legacy.py | {
"start": 6909,
"end": 7555
} | class ____(_profiles.AnsibleProfileJSONDecoder):
_profile = _Profile
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
# NB: these can only be sampled properly when loading strings, eg, `json.loads`; the global `json.load` function does not expose the file-like to us
self._origin: _tags.Origin | None = None
self._trusted_as_template: bool = False
def raw_decode(self, s: str, idx: int = 0) -> tuple[_t.Any, int]:
self._origin = _tags.Origin.get_tag(s)
self._trusted_as_template = _tags.TrustedAsTemplate.is_tagged_on(s)
return super().raw_decode(s, idx)
| Decoder |
python | django__django | tests/model_enums/tests.py | {
"start": 9652,
"end": 9896
} | class ____(ipaddress.IPv6Network, models.Choices):
LOOPBACK = "::1/128", "Loopback"
UNSPECIFIED = "::/128", "Unspecified"
UNIQUE_LOCAL = "fc00::/7", "Unique-Local"
LINK_LOCAL_UNICAST = "fe80::/10", "Link-Local Unicast"
| IPv6Network |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 66096,
"end": 71152
} | class ____(system_info):
notfounderror = LapackNotFoundError
# List of all known LAPACK libraries, in the default order
lapack_order = ['armpl', 'mkl', 'ssl2', 'openblas', 'flame',
'accelerate', 'atlas', 'lapack']
order_env_var_name = 'NPY_LAPACK_ORDER'
def _calc_info_armpl(self):
info = get_info('lapack_armpl')
if info:
self.set_info(**info)
return True
return False
def _calc_info_mkl(self):
info = get_info('lapack_mkl')
if info:
self.set_info(**info)
return True
return False
def _calc_info_ssl2(self):
info = get_info('lapack_ssl2')
if info:
self.set_info(**info)
return True
return False
def _calc_info_openblas(self):
info = get_info('openblas_lapack')
if info:
self.set_info(**info)
return True
info = get_info('openblas_clapack')
if info:
self.set_info(**info)
return True
return False
def _calc_info_flame(self):
info = get_info('flame')
if info:
self.set_info(**info)
return True
return False
def _calc_info_atlas(self):
info = get_info('atlas_3_10_threads')
if not info:
info = get_info('atlas_3_10')
if not info:
info = get_info('atlas_threads')
if not info:
info = get_info('atlas')
if info:
# Figure out if ATLAS has lapack...
# If not we need the lapack library, but not BLAS!
l = info.get('define_macros', [])
if ('ATLAS_WITH_LAPACK_ATLAS', None) in l \
or ('ATLAS_WITHOUT_LAPACK', None) in l:
# Get LAPACK (with possible warnings)
# If not found we don't accept anything
# since we can't use ATLAS with LAPACK!
lapack_info = self._get_info_lapack()
if not lapack_info:
return False
dict_append(info, **lapack_info)
self.set_info(**info)
return True
return False
def _calc_info_accelerate(self):
info = get_info('accelerate')
if info:
self.set_info(**info)
return True
return False
def _get_info_blas(self):
# Default to get the optimized BLAS implementation
info = get_info('blas_opt')
if not info:
warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=3)
info_src = get_info('blas_src')
if not info_src:
warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=3)
return {}
dict_append(info, libraries=[('fblas_src', info_src)])
return info
def _get_info_lapack(self):
info = get_info('lapack')
if not info:
warnings.warn(LapackNotFoundError.__doc__ or '', stacklevel=3)
info_src = get_info('lapack_src')
if not info_src:
warnings.warn(LapackSrcNotFoundError.__doc__ or '', stacklevel=3)
return {}
dict_append(info, libraries=[('flapack_src', info_src)])
return info
def _calc_info_lapack(self):
info = self._get_info_lapack()
if info:
info_blas = self._get_info_blas()
dict_append(info, **info_blas)
dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)])
self.set_info(**info)
return True
return False
def _calc_info_from_envvar(self):
info = {}
info['language'] = 'f77'
info['libraries'] = []
info['include_dirs'] = []
info['define_macros'] = []
info['extra_link_args'] = os.environ['NPY_LAPACK_LIBS'].split()
self.set_info(**info)
return True
def _calc_info(self, name):
return getattr(self, '_calc_info_{}'.format(name))()
def calc_info(self):
lapack_order, unknown_order = _parse_env_order(self.lapack_order, self.order_env_var_name)
if len(unknown_order) > 0:
raise ValueError("lapack_opt_info user defined "
"LAPACK order has unacceptable "
"values: {}".format(unknown_order))
if 'NPY_LAPACK_LIBS' in os.environ:
# Bypass autodetection, set language to F77 and use env var linker
# flags directly
self._calc_info_from_envvar()
return
for lapack in lapack_order:
if self._calc_info(lapack):
return
if 'lapack' not in lapack_order:
# Since the user may request *not* to use any library, we still need
# to raise warnings to signal missing packages!
warnings.warn(LapackNotFoundError.__doc__ or '', stacklevel=2)
warnings.warn(LapackSrcNotFoundError.__doc__ or '', stacklevel=2)
| lapack_opt_info |
python | django__django | tests/str/models.py | {
"start": 393,
"end": 574
} | class ____(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateTimeField()
def __str__(self):
return self.headline
| InternationalArticle |
python | sympy__sympy | sympy/functions/special/spherical_harmonics.py | {
"start": 577,
"end": 9059
} | class ____(DefinedFunction):
r"""
Spherical harmonics defined as
.. math::
Y_n^m(\theta, \varphi) := \sqrt{\frac{(2n+1)(n-m)!}{4\pi(n+m)!}}
\exp(i m \varphi)
\mathrm{P}_n^m\left(\cos(\theta)\right)
Explanation
===========
``Ynm()`` gives the spherical harmonic function of order $n$ and $m$
in $\theta$ and $\varphi$, $Y_n^m(\theta, \varphi)$. The four
parameters are as follows: $n \geq 0$ an integer and $m$ an integer
such that $-n \leq m \leq n$ holds. The two angles are real-valued
with $\theta \in [0, \pi]$ and $\varphi \in [0, 2\pi]$.
Examples
========
>>> from sympy import Ynm, Symbol, simplify
>>> from sympy.abc import n,m
>>> theta = Symbol("theta")
>>> phi = Symbol("phi")
>>> Ynm(n, m, theta, phi)
Ynm(n, m, theta, phi)
Several symmetries are known, for the order:
>>> Ynm(n, -m, theta, phi)
(-1)**m*exp(-2*I*m*phi)*Ynm(n, m, theta, phi)
As well as for the angles:
>>> Ynm(n, m, -theta, phi)
Ynm(n, m, theta, phi)
>>> Ynm(n, m, theta, -phi)
exp(-2*I*m*phi)*Ynm(n, m, theta, phi)
For specific integers $n$ and $m$ we can evaluate the harmonics
to more useful expressions:
>>> simplify(Ynm(0, 0, theta, phi).expand(func=True))
1/(2*sqrt(pi))
>>> simplify(Ynm(1, -1, theta, phi).expand(func=True))
sqrt(6)*exp(-I*phi)*sin(theta)/(4*sqrt(pi))
>>> simplify(Ynm(1, 0, theta, phi).expand(func=True))
sqrt(3)*cos(theta)/(2*sqrt(pi))
>>> simplify(Ynm(1, 1, theta, phi).expand(func=True))
-sqrt(6)*exp(I*phi)*sin(theta)/(4*sqrt(pi))
>>> simplify(Ynm(2, -2, theta, phi).expand(func=True))
sqrt(30)*exp(-2*I*phi)*sin(theta)**2/(8*sqrt(pi))
>>> simplify(Ynm(2, -1, theta, phi).expand(func=True))
sqrt(30)*exp(-I*phi)*sin(2*theta)/(8*sqrt(pi))
>>> simplify(Ynm(2, 0, theta, phi).expand(func=True))
sqrt(5)*(3*cos(theta)**2 - 1)/(4*sqrt(pi))
>>> simplify(Ynm(2, 1, theta, phi).expand(func=True))
-sqrt(30)*exp(I*phi)*sin(2*theta)/(8*sqrt(pi))
>>> simplify(Ynm(2, 2, theta, phi).expand(func=True))
sqrt(30)*exp(2*I*phi)*sin(theta)**2/(8*sqrt(pi))
We can differentiate the functions with respect
to both angles:
>>> from sympy import Ynm, Symbol, diff
>>> from sympy.abc import n,m
>>> theta = Symbol("theta")
>>> phi = Symbol("phi")
>>> diff(Ynm(n, m, theta, phi), theta)
m*cot(theta)*Ynm(n, m, theta, phi) + sqrt((-m + n)*(m + n + 1))*exp(-I*phi)*Ynm(n, m + 1, theta, phi)
>>> diff(Ynm(n, m, theta, phi), phi)
I*m*Ynm(n, m, theta, phi)
Further we can compute the complex conjugation:
>>> from sympy import Ynm, Symbol, conjugate
>>> from sympy.abc import n,m
>>> theta = Symbol("theta")
>>> phi = Symbol("phi")
>>> conjugate(Ynm(n, m, theta, phi))
(-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi)
To get back the well known expressions in spherical
coordinates, we use full expansion:
>>> from sympy import Ynm, Symbol, expand_func
>>> from sympy.abc import n,m
>>> theta = Symbol("theta")
>>> phi = Symbol("phi")
>>> expand_func(Ynm(n, m, theta, phi))
sqrt((2*n + 1)*factorial(-m + n)/factorial(m + n))*exp(I*m*phi)*assoc_legendre(n, m, cos(theta))/(2*sqrt(pi))
See Also
========
Ynm_c, Znm, sympy.physics.hydrogen.Y_lm, sympy.physics.hydrogen.Z_lm
References
==========
.. [1] https://en.wikipedia.org/wiki/Spherical_harmonics
.. [2] https://mathworld.wolfram.com/SphericalHarmonic.html
.. [3] https://functions.wolfram.com/Polynomials/SphericalHarmonicY/
.. [4] https://dlmf.nist.gov/14.30
"""
@classmethod
def eval(cls, n, m, theta, phi):
# Handle negative index m and arguments theta, phi
if m.could_extract_minus_sign():
m = -m
return S.NegativeOne**m * exp(-2*I*m*phi) * Ynm(n, m, theta, phi)
if theta.could_extract_minus_sign():
theta = -theta
return Ynm(n, m, theta, phi)
if phi.could_extract_minus_sign():
phi = -phi
return exp(-2*I*m*phi) * Ynm(n, m, theta, phi)
# TODO Add more simplififcation here
def _eval_expand_func(self, **hints):
n, m, theta, phi = self.args
rv = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) *
exp(I*m*phi) * assoc_legendre(n, m, cos(theta)))
# We can do this because of the range of theta
return rv.subs(sqrt(-cos(theta)**2 + 1), sin(theta))
def fdiff(self, argindex=4):
if argindex == 1:
# Diff wrt n
raise ArgumentIndexError(self, argindex)
elif argindex == 2:
# Diff wrt m
raise ArgumentIndexError(self, argindex)
elif argindex == 3:
# Diff wrt theta
n, m, theta, phi = self.args
return (m * cot(theta) * Ynm(n, m, theta, phi) +
sqrt((n - m)*(n + m + 1)) * exp(-I*phi) * Ynm(n, m + 1, theta, phi))
elif argindex == 4:
# Diff wrt phi
n, m, theta, phi = self.args
return I * m * Ynm(n, m, theta, phi)
else:
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_polynomial(self, n, m, theta, phi, **kwargs):
# TODO: Make sure n \in N
# TODO: Assert |m| <= n ortherwise we should return 0
return self.expand(func=True)
def _eval_rewrite_as_sin(self, n, m, theta, phi, **kwargs):
return self.rewrite(cos)
def _eval_rewrite_as_cos(self, n, m, theta, phi, **kwargs):
# This method can be expensive due to extensive use of simplification!
from sympy.simplify import simplify, trigsimp
# TODO: Make sure n \in N
# TODO: Assert |m| <= n ortherwise we should return 0
term = simplify(self.expand(func=True))
# We can do this because of the range of theta
term = term.xreplace({Abs(sin(theta)):sin(theta)})
return simplify(trigsimp(term))
def _eval_conjugate(self):
# TODO: Make sure theta \in R and phi \in R
n, m, theta, phi = self.args
return S.NegativeOne**m * self.func(n, -m, theta, phi)
def as_real_imag(self, deep=True, **hints):
# TODO: Handle deep and hints
n, m, theta, phi = self.args
re = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) *
cos(m*phi) * assoc_legendre(n, m, cos(theta)))
im = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) *
sin(m*phi) * assoc_legendre(n, m, cos(theta)))
return (re, im)
def _eval_evalf(self, prec):
# Note: works without this function by just calling
# mpmath for Legendre polynomials. But using
# the dedicated function directly is cleaner.
from mpmath import mp, workprec
n = self.args[0]._to_mpmath(prec)
m = self.args[1]._to_mpmath(prec)
theta = self.args[2]._to_mpmath(prec)
phi = self.args[3]._to_mpmath(prec)
with workprec(prec):
res = mp.spherharm(n, m, theta, phi)
return Expr._from_mpmath(res, prec)
def Ynm_c(n, m, theta, phi):
r"""
Conjugate spherical harmonics defined as
.. math::
\overline{Y_n^m(\theta, \varphi)} := (-1)^m Y_n^{-m}(\theta, \varphi).
Examples
========
>>> from sympy import Ynm_c, Symbol, simplify
>>> from sympy.abc import n,m
>>> theta = Symbol("theta")
>>> phi = Symbol("phi")
>>> Ynm_c(n, m, theta, phi)
(-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi)
>>> Ynm_c(n, m, -theta, phi)
(-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi)
For specific integers $n$ and $m$ we can evaluate the harmonics
to more useful expressions:
>>> simplify(Ynm_c(0, 0, theta, phi).expand(func=True))
1/(2*sqrt(pi))
>>> simplify(Ynm_c(1, -1, theta, phi).expand(func=True))
sqrt(6)*exp(I*(-phi + 2*conjugate(phi)))*sin(theta)/(4*sqrt(pi))
See Also
========
Ynm, Znm, sympy.physics.hydrogen.Y_lm, sympy.physics.hydrogen.Z_lm
References
==========
.. [1] https://en.wikipedia.org/wiki/Spherical_harmonics
.. [2] https://mathworld.wolfram.com/SphericalHarmonic.html
.. [3] https://functions.wolfram.com/Polynomials/SphericalHarmonicY/
"""
return conjugate(Ynm(n, m, theta, phi))
| Ynm |
python | wandb__wandb | wandb/vendor/pygments/lexers/actionscript.py | {
"start": 6405,
"end": 9941
} | class ____(RegexLexer):
"""
For ActionScript 3 source code.
.. versionadded:: 0.11
"""
name = 'ActionScript 3'
aliases = ['as3', 'actionscript3']
filenames = ['*.as']
mimetypes = ['application/x-actionscript3', 'text/x-actionscript3',
'text/actionscript3']
identifier = r'[$a-zA-Z_]\w*'
typeidentifier = identifier + '(?:\.<\w+>)?'
flags = re.DOTALL | re.MULTILINE
tokens = {
'root': [
(r'\s+', Text),
(r'(function\s+)(' + identifier + r')(\s*)(\()',
bygroups(Keyword.Declaration, Name.Function, Text, Operator),
'funcparams'),
(r'(var|const)(\s+)(' + identifier + r')(\s*)(:)(\s*)(' +
typeidentifier + r')',
bygroups(Keyword.Declaration, Text, Name, Text, Punctuation, Text,
Keyword.Type)),
(r'(import|package)(\s+)((?:' + identifier + r'|\.)+)(\s*)',
bygroups(Keyword, Text, Name.Namespace, Text)),
(r'(new)(\s+)(' + typeidentifier + r')(\s*)(\()',
bygroups(Keyword, Text, Keyword.Type, Text, Operator)),
(r'//.*?\n', Comment.Single),
(r'/\*.*?\*/', Comment.Multiline),
(r'/(\\\\|\\/|[^\n])*/[gisx]*', String.Regex),
(r'(\.)(' + identifier + r')', bygroups(Operator, Name.Attribute)),
(r'(case|default|for|each|in|while|do|break|return|continue|if|else|'
r'throw|try|catch|with|new|typeof|arguments|instanceof|this|'
r'switch|import|include|as|is)\b',
Keyword),
(r'(class|public|final|internal|native|override|private|protected|'
r'static|import|extends|implements|interface|intrinsic|return|super|'
r'dynamic|function|const|get|namespace|package|set)\b',
Keyword.Declaration),
(r'(true|false|null|NaN|Infinity|-Infinity|undefined|void)\b',
Keyword.Constant),
(r'(decodeURI|decodeURIComponent|encodeURI|escape|eval|isFinite|isNaN|'
r'isXMLName|clearInterval|fscommand|getTimer|getURL|getVersion|'
r'isFinite|parseFloat|parseInt|setInterval|trace|updateAfterEvent|'
r'unescape)\b', Name.Function),
(identifier, Name),
(r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float),
(r'0x[0-9a-f]+', Number.Hex),
(r'[0-9]+', Number.Integer),
(r'"(\\\\|\\"|[^"])*"', String.Double),
(r"'(\\\\|\\'|[^'])*'", String.Single),
(r'[~^*!%&<>|+=:;,/?\\{}\[\]().-]+', Operator),
],
'funcparams': [
(r'\s+', Text),
(r'(\s*)(\.\.\.)?(' + identifier + r')(\s*)(:)(\s*)(' +
typeidentifier + r'|\*)(\s*)',
bygroups(Text, Punctuation, Name, Text, Operator, Text,
Keyword.Type, Text), 'defval'),
(r'\)', Operator, 'type')
],
'type': [
(r'(\s*)(:)(\s*)(' + typeidentifier + r'|\*)',
bygroups(Text, Operator, Text, Keyword.Type), '#pop:2'),
(r'\s+', Text, '#pop:2'),
default('#pop:2')
],
'defval': [
(r'(=)(\s*)([^(),]+)(\s*)(,?)',
bygroups(Operator, Text, using(this), Text, Operator), '#pop'),
(r',', Operator, '#pop'),
default('#pop')
]
}
def analyse_text(text):
if re.match(r'\w+\s*:\s*\w', text):
return 0.3
return 0
| ActionScript3Lexer |
python | anthropics__anthropic-sdk-python | src/anthropic/resources/beta/skills/skills.py | {
"start": 22414,
"end": 23063
} | class ____:
def __init__(self, skills: Skills) -> None:
self._skills = skills
self.create = _legacy_response.to_raw_response_wrapper(
skills.create,
)
self.retrieve = _legacy_response.to_raw_response_wrapper(
skills.retrieve,
)
self.list = _legacy_response.to_raw_response_wrapper(
skills.list,
)
self.delete = _legacy_response.to_raw_response_wrapper(
skills.delete,
)
@cached_property
def versions(self) -> VersionsWithRawResponse:
return VersionsWithRawResponse(self._skills.versions)
| SkillsWithRawResponse |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/bilstm_classifier.py | {
"start": 6133,
"end": 7045
} | class ____(nn.Module):
"""A simple bi-directional LSTM."""
hidden_size: int
def setup(self):
self.forward_lstm = SimpleLSTM()
self.backward_lstm = SimpleLSTM()
def __call__(self, embedded_inputs, lengths):
batch_size = embedded_inputs.shape[0]
# Forward LSTM.
initial_state = SimpleLSTM.initialize_carry((batch_size,), self.hidden_size)
_, forward_outputs = self.forward_lstm(initial_state, embedded_inputs)
# Backward LSTM.
reversed_inputs = flip_sequences(embedded_inputs, lengths)
initial_state = SimpleLSTM.initialize_carry((batch_size,), self.hidden_size)
_, backward_outputs = self.backward_lstm(initial_state, reversed_inputs)
backward_outputs = flip_sequences(backward_outputs, lengths)
# Concatenate the forward and backward representations.
outputs = jnp.concatenate([forward_outputs, backward_outputs], -1)
return outputs
| SimpleBiLSTM |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/optimization/shuffle_and_repeat_fusion_test.py | {
"start": 1165,
"end": 2195
} | class ____(test_base.DatasetTestBase,
parameterized.TestCase):
@combinations.generate(test_base.default_test_combinations())
def testShuffleAndRepeatFusion(self):
expected = "ShuffleAndRepeat"
dataset = dataset_ops.Dataset.range(10).apply(
testing.assert_next([expected])).shuffle(10).repeat(2)
options = options_lib.Options()
options.experimental_optimization.apply_default_optimizations = False
options.experimental_optimization.shuffle_and_repeat_fusion = True
dataset = dataset.with_options(options)
get_next = self.getNext(dataset)
for _ in range(2):
results = []
for _ in range(10):
results.append(self.evaluate(get_next()))
self.assertAllEqual([x for x in range(10)], sorted(results))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
if __name__ == "__main__":
test.main()
| ShuffleAndRepeatFusionTest |
python | PrefectHQ__prefect | src/prefect/settings/sources.py | {
"start": 8423,
"end": 10617
} | class ____(PydanticBaseSettingsSource, ConfigFileSourceMixin):
def __init__(self, settings_cls: Type[BaseSettings]):
super().__init__(settings_cls)
self.settings_cls = settings_cls
self.toml_data: dict[str, Any] = {}
def _read_file(self, path: Path) -> dict[str, Any]:
return _read_toml_file(path)
def get_field_value(
self, field: FieldInfo, field_name: str
) -> tuple[Any, str, bool]:
"""Concrete implementation to get the field value from toml data"""
value = self.toml_data.get(field_name)
if isinstance(value, dict):
# if the value is a dict, it is likely a nested settings object and a nested
# source will handle it
value = None
name = field_name
# Use validation alias as the key to ensure profile value does not
# higher priority sources. Lower priority sources that use the
# field name can override higher priority sources that use the
# validation alias as seen in https://github.com/PrefectHQ/prefect/issues/15981
if value is not None:
if field.validation_alias and isinstance(field.validation_alias, str):
name = field.validation_alias
elif field.validation_alias and isinstance(
field.validation_alias, AliasChoices
):
for alias in reversed(field.validation_alias.choices):
if isinstance(alias, str):
name = alias
break
return value, name, self.field_is_complex(field)
def __call__(self) -> dict[str, Any]:
"""Called by pydantic to get the settings from our custom source"""
toml_setings: dict[str, Any] = {}
for field_name, field in self.settings_cls.model_fields.items():
value, key, is_complex = self.get_field_value(field, field_name)
if value is not None:
prepared_value = self.prepare_field_value(
field_name, field, value, is_complex
)
toml_setings[key] = prepared_value
return toml_setings
| TomlConfigSettingsSourceBase |
python | sympy__sympy | sympy/vector/dyadic.py | {
"start": 7698,
"end": 8102
} | class ____(BasisDependentAdd, Dyadic):
""" Class to hold dyadic sums """
def __new__(cls, *args, **options):
obj = BasisDependentAdd.__new__(cls, *args, **options)
return obj
def _sympystr(self, printer):
items = list(self.components.items())
items.sort(key=lambda x: x[0].__str__())
return " + ".join(printer._print(k * v) for k, v in items)
| DyadicAdd |
python | ansible__ansible | test/units/plugins/lookup/test_password.py | {
"start": 8241,
"end": 9616
} | class ____(unittest.TestCase):
def setUp(self):
self.fake_loader = DictDataLoader({'/path/to/somewhere': 'sdfsdf'})
self.password_lookup = lookup_loader.get('password')
self.password_lookup._loader = self.fake_loader
def test(self):
for testcase in old_style_params_data:
filename, params = self.password_lookup._parse_parameters(testcase['term'])
params['chars'].sort()
self.assertEqual(filename, testcase['filename'])
self.assertEqual(params, testcase['params'])
def test_unrecognized_value(self):
testcase = dict(term=u'/path/to/file chars=くらとみi sdfsdf',
filename=u'/path/to/file',
params=dict(length=DEFAULT_LENGTH, encrypt=None, chars=[u'くらとみ']),
candidate_chars=u'くらとみ')
self.assertRaises(AnsibleError, self.password_lookup._parse_parameters, testcase['term'])
def test_invalid_params(self):
testcase = dict(term=u'/path/to/file chars=くらとみi somethign_invalid=123',
filename=u'/path/to/file',
params=dict(length=DEFAULT_LENGTH, encrypt=None, chars=[u'くらとみ']),
candidate_chars=u'くらとみ')
self.assertRaises(AnsibleError, self.password_lookup._parse_parameters, testcase['term'])
| TestParseParameters |
python | pytorch__pytorch | torch/distributed/pipelining/stage.py | {
"start": 2700,
"end": 2856
} | class ____:
"""
Placeholder for model-level inputs.
"""
def __init__(self, tensor):
self.meta = tensor.to("meta")
| _RootArgPlaceholder |
python | google__pytype | pytype/pytd/visitors.py | {
"start": 752,
"end": 1457
} | class ____(KeyError):
def __init__(self, module):
self.module = module
super().__init__(f"Unknown module {module}")
# All public elements of pytd_visitors are aliased here so that we can maintain
# the conceptually simpler illusion of having a single visitors module.
ALL_NODE_NAMES = base_visitor.ALL_NODE_NAMES
Visitor = base_visitor.Visitor
CanonicalOrderingVisitor = pytd_visitors.CanonicalOrderingVisitor
ClassTypeToNamedType = pytd_visitors.ClassTypeToNamedType
CollectTypeParameters = pytd_visitors.CollectTypeParameters
ExtractSuperClasses = pytd_visitors.ExtractSuperClasses
PrintVisitor = printer.PrintVisitor
RenameModuleVisitor = pytd_visitors.RenameModuleVisitor
| MissingModuleError |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_list_tuple.py | {
"start": 8086,
"end": 8194
} | class ____(ImplicitContains):
def __contains__(self, item):
return item in {2, 5}
| ExplicitContains |
python | PrefectHQ__prefect | tests/test_task_engine.py | {
"start": 1608,
"end": 4585
} | class ____:
async def test_basic_init(self):
engine = SyncTaskRunEngine(task=foo)
assert isinstance(engine.task, Task)
assert engine.task.name == "foo"
assert engine.parameters == {}
async def test_client_attribute_raises_informative_error(self):
engine = SyncTaskRunEngine(task=foo)
with pytest.raises(RuntimeError, match="not started"):
engine.client
async def test_client_attr_returns_client_after_starting(self):
engine = SyncTaskRunEngine(task=foo)
with engine.initialize_run():
client = engine.client
assert isinstance(client, SyncPrefectClient)
with pytest.raises(RuntimeError, match="not started"):
engine.client
async def test_set_task_run_state(self):
engine = SyncTaskRunEngine(task=foo)
with engine.initialize_run():
running_state = Running()
new_state = engine.set_state(running_state)
assert new_state == running_state
completed_state = Completed()
new_state = engine.set_state(completed_state)
assert new_state == completed_state
async def test_set_task_run_state_duplicated_timestamp(self):
engine = SyncTaskRunEngine(task=foo)
with engine.initialize_run():
running_state = Running()
completed_state = Completed()
completed_state.timestamp = running_state.timestamp
new_state = engine.set_state(running_state)
assert new_state == running_state
new_state = engine.set_state(completed_state)
assert new_state == completed_state
assert new_state.timestamp > running_state.timestamp
def test_logs_message_when_submitted_tasks_end_in_pending(self, caplog):
"""
If submitted tasks aren't waited on before a flow exits, they may fail to run
because they're transition from PENDING to RUNNING is denied. This test ensures
that a message is logged when this happens.
"""
engine = SyncTaskRunEngine(task=foo)
with engine.initialize_run():
assert engine.state.is_pending()
assert (
"Please wait for all submitted tasks to complete before exiting your flow"
in caplog.text
)
def test_doesnt_log_message_when_submitted_tasks_end_in_not_ready(self, caplog):
"""
Regression test for tasks that didn't run because of upstream issues, not because of
a lack of wait call. See https://github.com/PrefectHQ/prefect/issues/16848
"""
engine = SyncTaskRunEngine(task=foo)
with engine.initialize_run():
assert engine.state.is_pending()
engine.set_state(Pending(name="NotReady"))
assert (
"Please wait for all submitted tasks to complete before exiting your flow"
not in caplog.text
)
| TestSyncTaskRunEngine |
python | great-expectations__great_expectations | great_expectations/data_context/types/base.py | {
"start": 67594,
"end": 71104
} | class ____(BaseStoreBackendDefaults):
"""
Default store configs for database backends, with some accessible parameters
Args:
default_credentials: Use these credentials for all stores that do not have credentials provided
expectations_store_credentials: Overrides default_credentials if supplied
validation_results_store_credentials: Overrides default_credentials if supplied
checkpoint_store_credentials: Overrides default_credentials if supplied
expectations_store_name: Overrides default if supplied
validation_results_store_name: Overrides default if supplied
checkpoint_store_name: Overrides default if supplied
""" # noqa: E501 # FIXME CoP
def __init__( # noqa: PLR0913 # FIXME CoP
self,
default_credentials: Optional[Dict] = None,
expectations_store_credentials: Optional[Dict] = None,
validation_results_store_credentials: Optional[Dict] = None,
validation_definition_store_credentials: Optional[Dict] = None,
checkpoint_store_credentials: Optional[Dict] = None,
expectations_store_name: str = "expectations_database_store",
validation_results_store_name: str = "validation_results_database_store",
checkpoint_store_name: str = "checkpoint_database_store",
) -> None:
# Initialize base defaults
super().__init__()
# Use default credentials if separate credentials not supplied for expectations_store and validation_results_store # noqa: E501 # FIXME CoP
if expectations_store_credentials is None:
expectations_store_credentials = default_credentials
if validation_results_store_credentials is None:
validation_results_store_credentials = default_credentials
if validation_definition_store_credentials is None:
validation_definition_store_credentials = default_credentials
if checkpoint_store_credentials is None:
checkpoint_store_credentials = default_credentials
# Overwrite defaults
self.expectations_store_name = expectations_store_name
self.validation_results_store_name = validation_results_store_name
self.checkpoint_store_name = checkpoint_store_name
self.stores = {
expectations_store_name: {
"class_name": "ExpectationsStore",
"store_backend": {
"class_name": "DatabaseStoreBackend",
"credentials": expectations_store_credentials,
},
},
validation_results_store_name: {
"class_name": "ValidationResultsStore",
"store_backend": {
"class_name": "DatabaseStoreBackend",
"credentials": validation_results_store_credentials,
},
},
self.validation_definition_store_name: {
"class_name": "ValidationDefinitionStore",
"store_backend": {
"class_name": "DatabaseStoreBackend",
"credentials": validation_definition_store_credentials,
},
},
checkpoint_store_name: {
"class_name": "CheckpointStore",
"store_backend": {
"class_name": "DatabaseStoreBackend",
"credentials": checkpoint_store_credentials,
},
},
}
@public_api
| DatabaseStoreBackendDefaults |
python | openai__openai-python | src/openai/types/beta/realtime/conversation_item_content_param.py | {
"start": 218,
"end": 972
} | class ____(TypedDict, total=False):
id: str
"""
ID of a previous conversation item to reference (for `item_reference` content
types in `response.create` events). These can reference both client and server
created items.
"""
audio: str
"""Base64-encoded audio bytes, used for `input_audio` content type."""
text: str
"""The text content, used for `input_text` and `text` content types."""
transcript: str
"""The transcript of the audio, used for `input_audio` and `audio` content types."""
type: Literal["input_text", "input_audio", "item_reference", "text", "audio"]
"""
The content type (`input_text`, `input_audio`, `item_reference`, `text`,
`audio`).
"""
| ConversationItemContentParam |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/data_adapter.py | {
"start": 31644,
"end": 38088
} | class ____(GeneratorDataAdapter):
"""Adapter that handles `keras.utils.Sequence`."""
@staticmethod
def can_handle(x, y=None):
return isinstance(x, data_utils.Sequence)
def __init__(self,
x,
y=None,
sample_weights=None,
shuffle=False,
workers=1,
use_multiprocessing=False,
max_queue_size=10,
model=None,
**kwargs):
if not is_none_or_empty(y):
raise ValueError("`y` argument is not supported when using "
"`keras.utils.Sequence` as input.")
if not is_none_or_empty(sample_weights):
raise ValueError("`sample_weight` argument is not supported when using "
"`keras.utils.Sequence` as input.")
self._size = len(x)
self._shuffle_sequence = shuffle
self._keras_sequence = x
self._enqueuer = None
super(KerasSequenceAdapter, self).__init__(
x,
shuffle=False, # Shuffle is handed in the _make_callable override.
workers=workers,
use_multiprocessing=use_multiprocessing,
max_queue_size=max_queue_size,
model=model,
**kwargs)
@staticmethod
def _peek_and_restore(x):
return x[0], x
def _handle_multiprocessing(self, x, workers, use_multiprocessing,
max_queue_size):
if workers > 1 or (workers > 0 and use_multiprocessing):
def generator_fn():
self._enqueuer = data_utils.OrderedEnqueuer(
x, use_multiprocessing=use_multiprocessing,
shuffle=self._shuffle_sequence)
self._enqueuer.start(workers=workers, max_queue_size=max_queue_size)
return self._enqueuer.get()
else:
def generator_fn():
order = range(len(x))
if self._shuffle_sequence:
# Match the shuffle convention in OrderedEnqueuer.
order = list(order)
random.shuffle(order)
for i in order:
yield x[i]
return generator_fn
def get_size(self):
return self._size
def should_recreate_iterator(self):
return True
def on_epoch_end(self):
if self._enqueuer:
self._enqueuer.stop()
self._keras_sequence.on_epoch_end()
ALL_ADAPTER_CLS = [
ListsOfScalarsDataAdapter, TensorLikeDataAdapter,
GenericArrayLikeDataAdapter, DatasetAdapter, GeneratorDataAdapter,
KerasSequenceAdapter, CompositeTensorDataAdapter, DatasetCreatorAdapter
]
def select_data_adapter(x, y):
"""Selects a data adapter than can handle a given x and y."""
adapter_cls = [cls for cls in ALL_ADAPTER_CLS if cls.can_handle(x, y)]
if not adapter_cls:
# TODO(scottzhu): This should be a less implementation-specific error.
raise ValueError(
"Failed to find data adapter that can handle "
"input: {}, {}".format(
_type_name(x), _type_name(y)))
elif len(adapter_cls) > 1:
raise RuntimeError(
"Data adapters should be mutually exclusive for "
"handling inputs. Found multiple adapters {} to handle "
"input: {}, {}".format(
adapter_cls, _type_name(x), _type_name(y)))
return adapter_cls[0]
def _type_name(x):
"""Generates a description of the type of an object."""
if isinstance(x, dict):
key_types = set(_type_name(key) for key in x.keys())
val_types = set(_type_name(key) for key in x.values())
return "({} containing {} keys and {} values)".format(
type(x), key_types, val_types)
if isinstance(x, (list, tuple)):
types = set(_type_name(val) for val in x)
return "({} containing values of types {})".format(
type(x), types)
return str(type(x))
def _process_tensorlike(inputs):
"""Process tensor-like inputs.
This function:
(1) Converts `Numpy` arrays to `Tensor`s.
(2) Converts `Scipy` sparse matrices to `SparseTensor`s.
(2) Converts `list`s to `tuple`s (for `tf.data` support).
Args:
inputs: Structure of `Tensor`s, `NumPy` arrays, or tensor-like.
Returns:
Structure of `Tensor`s or tensor-like.
"""
def _convert_numpy_and_scipy(x):
if isinstance(x, np.ndarray):
dtype = None
if issubclass(x.dtype.type, np.floating):
dtype = backend.floatx()
return tensor_conversion.convert_to_tensor_v2_with_dispatch(
x, dtype=dtype
)
elif _is_scipy_sparse(x):
return _scipy_sparse_to_sparse_tensor(x)
return x
inputs = nest.map_structure(_convert_numpy_and_scipy, inputs)
return nest.list_to_tuple(inputs)
def is_none_or_empty(inputs):
# util method to check if the input is a None or a empty list.
# the python "not" check will raise an error like below if the input is a
# numpy array
# "The truth value of an array with more than one element is ambiguous.
# Use a.any() or a.all()"
return inputs is None or not nest.flatten(inputs)
def broadcast_sample_weight_modes(target_structure, sample_weight_modes):
"""Match sample_weight_modes structure with output structure."""
if target_structure is None or not nest.flatten(target_structure):
return sample_weight_modes
if isinstance(sample_weight_modes, str):
if isinstance(target_structure, dict):
return {key: sample_weight_modes for key in target_structure.keys()}
return [sample_weight_modes for _ in target_structure]
if sample_weight_modes:
try:
nest.assert_same_structure(
training_utils.list_to_tuple(target_structure),
training_utils.list_to_tuple(sample_weight_modes))
except (ValueError, TypeError):
target_str = str(nest.map_structure(lambda _: "...", target_structure))
mode_str = str(nest.map_structure(lambda _: "...", sample_weight_modes))
# Attempt to coerce sample_weight_modes to the target structure. This
# implicitly depends on the fact that Model flattens outputs for its
# internal representation.
try:
sample_weight_modes = nest.pack_sequence_as(
target_structure, nest.flatten(sample_weight_modes))
logging.warning(
"sample_weight modes were coerced from\n {}\n to \n {}"
.format(target_str, mode_str))
except (ValueError, TypeError):
raise ValueError(
"Unable to match target structure and sample_weight_modes "
"structure:\n {}\n to \n {}".format(target_str, mode_str))
return sample_weight_modes
| KerasSequenceAdapter |
python | django__django | tests/model_options/test_default_pk.py | {
"start": 188,
"end": 273
} | class ____(models.BigAutoField):
pass
@isolate_apps("model_options")
| MyBigAutoField |
python | PyCQA__pylint | tests/functional/n/not_callable.py | {
"start": 3422,
"end": 3503
} | class ____:
def __get__(self, instance, owner):
return func
| ADescriptor |
python | OmkarPathak__pygorithm | pygorithm/data_structures/stack.py | {
"start": 1682,
"end": 4058
} | class ____(object):
"""InfixToPostfix
get the postfix of the given infix expression
"""
def __init__(self, expression=None, stack=None):
"""
:param expression: the infix expression to be converted to postfix
:param stack: stack to perform infix to postfix operation
"""
self.expression = list(expression)
self.my_stack = stack
@staticmethod
def _is_operand(char):
"""
utility function to find whether the given character is an operator
"""
# OLD VERSION
# return ord(char) >= ord('a') and ord(char) <= ord('z') \
# or ord(char) >= ord('A') and ord(char) <= ord('Z')
return True if ord(char) in [ord(c) for c in ascii_letters] else False
@staticmethod
def _precedence(char):
"""
utility function to find precedence of the specified character
"""
if char == '+' or char == '-':
return 1
elif char == '*' or char == '/':
return 2
elif char == '^':
return 3
else:
return -1
def infix_to_postfix(self):
"""
function to generate postfix expression from infix expression
"""
postfix = []
for i in range(len(self.expression)):
if self._is_operand(self.expression[i]):
postfix.append(self.expression[i])
elif self.expression[i] == '(':
self.my_stack.push(self.expression[i])
elif self.expression[i] == ')':
top_operator = self.my_stack.pop()
while not self.my_stack.is_empty() and top_operator != '(':
postfix.append(top_operator)
top_operator = self.my_stack.pop()
else:
while not self.my_stack.is_empty() and self._precedence(self.expression[i]) <= self._precedence(
self.my_stack.peek()):
postfix.append(self.my_stack.pop())
self.my_stack.push(self.expression[i])
while not self.my_stack.is_empty():
postfix.append(self.my_stack.pop())
return ' '.join(postfix)
@staticmethod
def get_code():
"""
returns the code of the current class
"""
return inspect.getsource(InfixToPostfix)
| InfixToPostfix |
python | kamyu104__LeetCode-Solutions | Python/decompress-run-length-encoded-list.py | {
"start": 29,
"end": 257
} | class ____(object):
def decompressRLElist(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return [nums[i+1] for i in xrange(0, len(nums), 2) for _ in xrange(nums[i])]
| Solution |
python | Textualize__textual | src/textual/widgets/_markdown.py | {
"start": 23567,
"end": 23627
} | class ____(MarkdownListItem):
pass
| MarkdownOrderedListItem |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/axes_size.py | {
"start": 6708,
"end": 7714
} | class ____(_Base):
"""
Fixed size, corresponding to the size of decorations on a given Axes side.
"""
_get_size_map = {
"left": lambda tight_bb, axes_bb: axes_bb.xmin - tight_bb.xmin,
"right": lambda tight_bb, axes_bb: tight_bb.xmax - axes_bb.xmax,
"bottom": lambda tight_bb, axes_bb: axes_bb.ymin - tight_bb.ymin,
"top": lambda tight_bb, axes_bb: tight_bb.ymax - axes_bb.ymax,
}
def __init__(self, ax, direction):
_api.check_in_list(self._get_size_map, direction=direction)
self._direction = direction
self._ax_list = [ax] if isinstance(ax, Axes) else ax
def get_size(self, renderer):
sz = max([
self._get_size_map[self._direction](
ax.get_tightbbox(renderer, call_axes_locator=False), ax.bbox)
for ax in self._ax_list])
dpi = renderer.points_to_pixels(72)
abs_size = sz / dpi
rel_size = 0
return rel_size, abs_size
| _AxesDecorationsSize |
python | doocs__leetcode | solution/2600-2699/2653.Sliding Subarray Beauty/Solution2.py | {
"start": 1685,
"end": 2180
} | class ____:
def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]:
finder = MedianFinder(x)
for i in range(k):
if nums[i] < 0:
finder.add_num(nums[i])
ans = [finder.find()]
for i in range(k, len(nums)):
if nums[i] < 0:
finder.add_num(nums[i])
if nums[i - k] < 0:
finder.remove_num(nums[i - k])
ans.append(finder.find())
return ans
| Solution |
python | tiangolo__fastapi | docs_src/body_updates/tutorial001_py310.py | {
"start": 124,
"end": 856
} | class ____(BaseModel):
name: str | None = None
description: str | None = None
price: float | None = None
tax: float = 10.5
tags: list[str] = []
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: str):
return items[item_id]
@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: str, item: Item):
update_item_encoded = jsonable_encoder(item)
items[item_id] = update_item_encoded
return update_item_encoded
| Item |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 105555,
"end": 107906
} | class ____(Response):
"""
Response of events.get_task_latest_scalar_values endpoint.
:param metrics:
:type metrics: Sequence[dict]
"""
_service = "events"
_action = "get_task_latest_scalar_values"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"metrics": {
"items": {
"properties": {
"name": {"description": "Metric name", "type": "string"},
"variants": {
"items": {
"properties": {
"last_100_value": {
"description": "Average of 100 last reported values",
"type": "number",
},
"last_value": {
"description": "Last reported value",
"type": "number",
},
"name": {
"description": "Variant name",
"type": "string",
},
},
"type": "object",
},
"type": "array",
},
},
"type": "object",
},
"type": ["array", "null"],
}
},
"type": "object",
}
def __init__(self, metrics: Optional[List[dict]] = None, **kwargs: Any) -> None:
super(GetTaskLatestScalarValuesResponse, self).__init__(**kwargs)
self.metrics = metrics
@schema_property("metrics")
def metrics(self) -> Optional[List[dict]]:
return self._property_metrics
@metrics.setter
def metrics(self, value: Optional[List[dict]]) -> None:
if value is None:
self._property_metrics = None
return
self.assert_isinstance(value, "metrics", (list, tuple))
self.assert_isinstance(value, "metrics", (dict,), is_array=True)
self._property_metrics = value
| GetTaskLatestScalarValuesResponse |
python | numba__numba | numba/tests/test_typeinfer.py | {
"start": 26927,
"end": 28710
} | class ____(unittest.TestCase):
def check_fold_arguments_list_inputs(self, func, args, kws):
def make_tuple(*args):
return args
unused_handler = None
pysig = utils.pysignature(func)
names = list(pysig.parameters)
with self.subTest(kind='dict'):
folded_dict = typing.fold_arguments(
pysig, args, kws, make_tuple, unused_handler, unused_handler,
)
# correct ordering
for i, (j, k) in enumerate(zip(folded_dict, names)):
(got_index, got_param, got_name) = j
self.assertEqual(got_index, i)
self.assertEqual(got_name, f'arg.{k}')
kws = list(kws.items())
with self.subTest(kind='list'):
folded_list = typing.fold_arguments(
pysig, args, kws, make_tuple, unused_handler, unused_handler,
)
self.assertEqual(folded_list, folded_dict)
def test_fold_arguments_list_inputs(self):
cases = [
dict(
func=lambda a, b, c, d: None,
args=['arg.a', 'arg.b'],
kws=dict(c='arg.c', d='arg.d')
),
dict(
func=lambda: None,
args=[],
kws=dict(),
),
dict(
func=lambda a: None,
args=['arg.a'],
kws={},
),
dict(
func=lambda a: None,
args=[],
kws=dict(a='arg.a'),
),
]
for case in cases:
with self.subTest(**case):
self.check_fold_arguments_list_inputs(**case)
@register_pass(mutates_CFG=False, analysis_only=True)
| TestFoldArguments |
python | apache__airflow | providers/google/src/airflow/providers/google/marketing_platform/operators/campaign_manager.py | {
"start": 12530,
"end": 15330
} | class ____(BaseOperator):
"""
Runs a report.
.. seealso::
Check official API docs:
`https://developers.google.com/doubleclick-advertisers/rest/v4/reports/run`
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:GoogleCampaignManagerRunReportOperator`
:param profile_id: The DFA profile ID.
:param report_id: The ID of the report.
:param synchronous: If set and true, tries to run the report synchronously.
:param api_version: The version of the api that will be requested, for example 'v4'.
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = (
"profile_id",
"report_id",
"synchronous",
"api_version",
"gcp_conn_id",
"impersonation_chain",
)
def __init__(
self,
*,
profile_id: str,
report_id: str,
synchronous: bool = False,
api_version: str = "v4",
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.profile_id = profile_id
self.report_id = report_id
self.synchronous = synchronous
self.api_version = api_version
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context):
hook = GoogleCampaignManagerHook(
gcp_conn_id=self.gcp_conn_id,
api_version=self.api_version,
impersonation_chain=self.impersonation_chain,
)
self.log.info("Running report %s", self.report_id)
response = hook.run_report(
profile_id=self.profile_id,
report_id=self.report_id,
synchronous=self.synchronous,
)
file_id = response.get("id")
context["task_instance"].xcom_push(key="file_id", value=file_id)
self.log.info("Report file id: %s", file_id)
return response
| GoogleCampaignManagerRunReportOperator |
python | getsentry__sentry | src/sentry/api/serializers/models/eventattachment.py | {
"start": 203,
"end": 1126
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
content_type = obj.content_type
size = obj.size or 0
sha1 = obj.sha1
headers = {"Content-Type": content_type}
return {
"id": str(obj.id),
"event_id": obj.event_id,
"type": obj.type,
"name": obj.name,
"mimetype": content_type,
"dateCreated": obj.date_added,
"size": size,
# TODO: It would be nice to deprecate these two fields.
# If not, we can at least define `headers` as `Content-Type: $mimetype`.
"headers": headers,
"sha1": sha1,
}
def get_mimetype(file: File) -> str:
rv = file.headers.get("Content-Type")
if rv:
return rv.split(";")[0].strip()
return mimetypes.guess_type(file.name)[0] or "application/octet-stream"
| EventAttachmentSerializer |
python | kamyu104__LeetCode-Solutions | Python/valid-palindrome-iv.py | {
"start": 52,
"end": 294
} | class ____(object):
def makePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
return sum(s[i] != s[~i] for i in xrange(len(s)//2)) <= 2
# Time: O(n)
# Space: O(1)
# string, two pointers
| Solution |
python | jazzband__django-model-utils | tests/test_fields/test_field_tracker.py | {
"start": 23829,
"end": 24797
} | class ____(FieldTrackerMixin, TestCase):
"""Test that using `prefetch_related` on a tracked field does not raise a ValueError."""
fk_class = Tracked
tracked_class = TrackedFK
instance: TrackedFK
def setUp(self) -> None:
model_tracked = self.fk_class.objects.create(name="", number=0)
self.instance = self.tracked_class.objects.create(fk=model_tracked)
def test_default(self) -> None:
self.tracker = self.instance.tracker
self.assertIsNotNone(list(self.tracked_class.objects.prefetch_related("fk")))
def test_custom(self) -> None:
self.tracker = self.instance.custom_tracker
self.assertIsNotNone(list(self.tracked_class.objects.prefetch_related("fk")))
def test_custom_without_id(self) -> None:
self.tracker = self.instance.custom_tracker_without_id
self.assertIsNotNone(list(self.tracked_class.objects.prefetch_related("fk")))
| FieldTrackerForeignKeyPrefetchRelatedTests |
python | pennersr__django-allauth | allauth/account/forms.py | {
"start": 9853,
"end": 17009
} | class ____(base_signup_form_class()): # type: ignore[misc]
username = forms.CharField(
label=_("Username"),
min_length=app_settings.USERNAME_MIN_LENGTH,
widget=forms.TextInput(
attrs={"placeholder": _("Username"), "autocomplete": "username"}
),
)
email = EmailField()
def __init__(self, *args, **kwargs):
self._signup_fields = self._get_signup_fields(kwargs)
self.account_already_exists = False
super().__init__(*args, **kwargs)
username_field = self.fields["username"]
username_field.max_length = get_username_max_length()
username_field.validators.append(
validators.MaxLengthValidator(username_field.max_length)
)
username_field.widget.attrs["maxlength"] = str(username_field.max_length)
email2 = self._signup_fields.get("email2")
if email2:
self.fields["email2"] = EmailField(
label=_("Email (again)"),
required=email2["required"],
widget=forms.TextInput(
attrs={
"type": "email",
"placeholder": _("Email address confirmation"),
}
),
)
email = self._signup_fields.get("email")
if email:
if email["required"]:
self.fields["email"].label = gettext("Email")
self.fields["email"].required = True
else:
self.fields["email"].label = gettext("Email (optional)")
self.fields["email"].required = False
self.fields["email"].widget.is_required = False
else:
del self.fields["email"]
username = self._signup_fields.get("username")
if username:
if username["required"]:
self.fields["username"].label = gettext("Username")
self.fields["username"].required = True
else:
self.fields["username"].label = gettext("Username (optional)")
self.fields["username"].required = False
self.fields["username"].widget.is_required = False
else:
del self.fields["username"]
phone = self._signup_fields.get("phone")
self._has_phone_field = bool(phone)
if phone:
adapter = get_adapter()
self.fields["phone"] = adapter.phone_form_field(
label=_("Phone"), required=phone["required"]
)
default_field_order = list(self._signup_fields.keys())
set_form_field_order(
self, getattr(self, "field_order", None) or default_field_order
)
def _get_signup_fields(self, kwargs):
signup_fields = app_settings.SIGNUP_FIELDS
if "email_required" in kwargs:
email = signup_fields.get("email")
if not email:
raise exceptions.ImproperlyConfigured(
"email required but not listed as a field"
)
email["required"] = kwargs.pop("email_required")
email2 = signup_fields.get("email2")
if email2:
email2["required"] = email["required"]
if "username_required" in kwargs:
username = signup_fields.get("username")
if not username:
raise exceptions.ImproperlyConfigured(
"username required but not listed as a field"
)
username["required"] = kwargs.pop("username_required")
return signup_fields
def clean_username(self):
value = self.cleaned_data["username"]
if not value and not self._signup_fields["username"]["required"]:
return value
value = get_adapter().clean_username(value)
# Note regarding preventing enumeration: if the username is already
# taken, but the email address is not, we would still leak information
# if we were to send an email to that email address stating that the
# username is already in use.
return value
def clean_email(self):
value = self.cleaned_data["email"].lower()
value = get_adapter().clean_email(value)
if value:
value = self.validate_unique_email(value)
return value
def clean_email2(self):
value = self.cleaned_data["email2"].lower()
return value
def validate_unique_email(self, value) -> str:
email, self.account_already_exists = flows.manage_email.email_already_exists(
value
)
return email
def clean(self):
cleaned_data = super().clean()
if "email2" in self._signup_fields:
email = cleaned_data.get("email")
email2 = cleaned_data.get("email2")
if (email and email2) and email != email2:
self.add_error("email2", _("You must type the same email each time."))
if "phone" in self._signup_fields:
self._clean_phone()
return cleaned_data
def _clean_phone(self):
"""Intentionally NOT `clean_phone()`:
- phone field is optional (depending on ACCOUNT_SIGNUP_FIELDS)
- we don't want to have clean_phone() mistakenly called when a project
is using a custom signup form with their own `phone` field.
"""
adapter = get_adapter()
if phone := self.cleaned_data.get("phone"):
user = adapter.get_user_by_phone(phone)
if user:
if not app_settings.PREVENT_ENUMERATION:
self.add_error("phone", adapter.error_messages["phone_taken"])
else:
self.account_already_exists = True
def custom_signup(self, request, user):
self.signup(request, user)
def try_save(self, request):
"""Try and save the user. This can fail in case of a conflict on the
email address, in that case we will send an "account already exists"
email and return a standard "email verification sent" response.
"""
if self.account_already_exists:
# Don't create a new account, only send an email informing the user
# that (s)he already has one...
email = self.cleaned_data.get("email")
phone = None
if "phone" in self._signup_fields:
phone = self.cleaned_data.get("phone")
resp = flows.signup.prevent_enumeration(request, email=email, phone=phone)
user = None
else:
user = self.save(request)
resp = None
return user, resp
def save(self, request):
email = self.cleaned_data.get("email")
if self.account_already_exists:
raise ValueError(email)
adapter = get_adapter()
user = adapter.new_user(request)
adapter.save_user(request, user, self)
self.custom_signup(request, user)
# TODO: Move into adapter `save_user` ?
setup_user_email(request, user, [EmailAddress(email=email)] if email else [])
return user
| BaseSignupForm |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-raptor/llama_index/packs/raptor/base.py | {
"start": 12243,
"end": 13317
} | class ____(BaseLlamaPack):
"""Raptor pack."""
def __init__(
self,
documents: List[BaseNode],
llm: Optional[LLM] = None,
embed_model: Optional[BaseEmbedding] = None,
vector_store: Optional[BasePydanticVectorStore] = None,
similarity_top_k: int = 2,
mode: QueryModes = "collapsed",
verbose: bool = True,
**kwargs: Any,
) -> None:
"""Init params."""
self.retriever = RaptorRetriever(
documents,
embed_model=embed_model,
llm=llm,
similarity_top_k=similarity_top_k,
vector_store=vector_store,
mode=mode,
verbose=verbose,
**kwargs,
)
def get_modules(self) -> Dict[str, Any]:
"""Get modules."""
return {
"retriever": self.retriever,
}
def run(
self,
query: str,
mode: Optional[QueryModes] = None,
) -> Any:
"""Run the pipeline."""
return self.retriever.retrieve(query, mode=mode)
| RaptorPack |
python | Textualize__textual | docs/examples/guide/layout/dock_layout3_sidebar_header.py | {
"start": 352,
"end": 670
} | class ____(App):
CSS_PATH = "dock_layout3_sidebar_header.tcss"
def compose(self) -> ComposeResult:
yield Header(id="header")
yield Static("Sidebar1", id="sidebar")
yield Static(TEXT * 10, id="body")
if __name__ == "__main__":
app = DockLayoutExample()
app.run()
| DockLayoutExample |
python | boto__boto3 | tests/unit/dynamodb/test_transform.py | {
"start": 13619,
"end": 15331
} | class ____(BaseTransformAttributeValueTest):
def test_handler(self):
parsed = {
'Structure': {
'TransformMe': self.dynamodb_value,
'LeaveAlone': 'unchanged',
}
}
input_shape = {
'Structure': {
'type': 'structure',
'members': {
'TransformMe': {'shape': self.target_shape},
'LeaveAlone': {'shape': 'String'},
},
}
}
self.add_input_shape(input_shape)
self.injector.inject_attribute_value_output(
parsed=parsed, model=self.operation_model
)
assert parsed == {
'Structure': {
'TransformMe': self.python_value,
'LeaveAlone': 'unchanged',
}
}
def test_no_output(self):
service_model = ServiceModel(
{
'operations': {
'SampleOperation': {
'name': 'SampleOperation',
'input': {'shape': 'SampleOperationInputOutput'},
}
},
'shapes': {
'SampleOperationInput': {
'type': 'structure',
'members': {},
},
'String': {'type': 'string'},
},
}
)
operation_model = service_model.operation_model('SampleOperation')
parsed = {}
self.injector.inject_attribute_value_output(
parsed=parsed, model=operation_model
)
assert parsed == {}
| TestTransformAttributeValueOutput |
python | tornadoweb__tornado | tornado/locks.py | {
"start": 7753,
"end": 8295
} | class ____:
"""Releases a Lock or Semaphore at the end of a "with" statement.
with (yield semaphore.acquire()):
pass
# Now semaphore.release() has been called.
"""
def __init__(self, obj: Any) -> None:
self._obj = obj
def __enter__(self) -> None:
pass
def __exit__(
self,
exc_type: "Optional[Type[BaseException]]",
exc_val: Optional[BaseException],
exc_tb: Optional[types.TracebackType],
) -> None:
self._obj.release()
| _ReleasingContextManager |
python | tensorflow__tensorflow | tensorflow/python/grappler/arithmetic_optimizer_test.py | {
"start": 963,
"end": 1647
} | class ____(test.TestCase):
# See b/146524878.
def testFunctionArgShapeInference(self):
@def_function.function
def f(x, y):
return math_ops.matmul(
x, array_ops.reshape(array_ops.transpose(y), [384, 1536]))
with context.eager_mode():
x = array_ops.ones((1, 384))
y = array_ops.ones((1536, 384))
with context.collect_graphs(optimized=True) as graphs:
f(x, y).numpy()
self.assertLen(graphs, 1)
self.assertLen(graphs[0].node, 4)
self.assertEqual(graphs[0].node[2].name,
'ArithmeticOptimizer/FoldTransposeIntoMatMul_MatMul')
if __name__ == '__main__':
test.main()
| ArithmeticOptimizerTest |
python | catalyst-team__catalyst | catalyst/contrib/datasets/imagewoof.py | {
"start": 75,
"end": 466
} | class ____(ImageClassificationDataset):
"""
`Imagewoof <https://github.com/fastai/imagenette#imagewoof>`_ Dataset.
.. note::
catalyst[cv] required for this dataset.
"""
name = "imagewoof2"
resources = [
(
"https://s3.amazonaws.com/fast-ai-imageclas/imagewoof2.tgz",
"9aafe18bcdb1632c4249a76c458465ba",
)
]
| Imagewoof |
python | sqlalchemy__sqlalchemy | test/sql/test_insert.py | {
"start": 50872,
"end": 69064
} | class ____(_InsertTestBase, fixtures.TablesTest, AssertsCompiledSQL):
__dialect__ = "default"
def test_not_supported(self):
table1 = self.tables.mytable
dialect = default.DefaultDialect()
stmt = table1.insert().values([{"myid": 1}, {"myid": 2}])
assert_raises_message(
exc.CompileError,
"The 'default' dialect with current database version settings "
"does not support in-place multirow inserts.",
stmt.compile,
dialect=dialect,
)
def test_named(self):
table1 = self.tables.mytable
values = [
{"myid": 1, "name": "a", "description": "b"},
{"myid": 2, "name": "c", "description": "d"},
{"myid": 3, "name": "e", "description": "f"},
]
checkparams = {
"myid_m0": 1,
"myid_m1": 2,
"myid_m2": 3,
"name_m0": "a",
"name_m1": "c",
"name_m2": "e",
"description_m0": "b",
"description_m1": "d",
"description_m2": "f",
}
dialect = default.DefaultDialect()
dialect.supports_multivalues_insert = True
self.assert_compile(
table1.insert().values(values),
"INSERT INTO mytable (myid, name, description) VALUES "
"(:myid_m0, :name_m0, :description_m0), "
"(:myid_m1, :name_m1, :description_m1), "
"(:myid_m2, :name_m2, :description_m2)",
checkparams=checkparams,
dialect=dialect,
)
@testing.combinations(("strings",), ("columns",), ("inspectables",))
def test_named_with_column_objects(self, column_style):
table1 = self.tables.mytable
if column_style == "strings":
myid, name, description = "myid", "name", "description"
elif column_style == "columns":
myid, name, description = (
table1.c.myid,
table1.c.name,
table1.c.description,
)
elif column_style == "inspectables":
myid, name, description = (
ORMExpr(table1.c.myid),
ORMExpr(table1.c.name),
ORMExpr(table1.c.description),
)
else:
assert False
values = [
{myid: 1, name: "a", description: "b"},
{myid: 2, name: "c", description: "d"},
{myid: 3, name: "e", description: "f"},
]
checkparams = {
"myid_m0": 1,
"myid_m1": 2,
"myid_m2": 3,
"name_m0": "a",
"name_m1": "c",
"name_m2": "e",
"description_m0": "b",
"description_m1": "d",
"description_m2": "f",
}
dialect = default.DefaultDialect()
dialect.supports_multivalues_insert = True
self.assert_compile(
table1.insert().values(values),
"INSERT INTO mytable (myid, name, description) VALUES "
"(:myid_m0, :name_m0, :description_m0), "
"(:myid_m1, :name_m1, :description_m1), "
"(:myid_m2, :name_m2, :description_m2)",
checkparams=checkparams,
dialect=dialect,
)
def test_positional(self):
table1 = self.tables.mytable
values = [
{"myid": 1, "name": "a", "description": "b"},
{"myid": 2, "name": "c", "description": "d"},
{"myid": 3, "name": "e", "description": "f"},
]
checkpositional = (1, "a", "b", 2, "c", "d", 3, "e", "f")
dialect = default.DefaultDialect()
dialect.supports_multivalues_insert = True
dialect.paramstyle = "format"
dialect.positional = True
self.assert_compile(
table1.insert().values(values),
"INSERT INTO mytable (myid, name, description) VALUES "
"(%s, %s, %s), (%s, %s, %s), (%s, %s, %s)",
checkpositional=checkpositional,
dialect=dialect,
)
def test_positional_w_defaults(self):
table1 = self.tables.table_w_defaults
values = [{"id": 1}, {"id": 2}, {"id": 3}]
checkpositional = (1, None, None, 2, None, None, 3, None, None)
dialect = default.DefaultDialect()
dialect.supports_multivalues_insert = True
dialect.paramstyle = "format"
dialect.positional = True
self.assert_compile(
table1.insert().values(values),
"INSERT INTO table_w_defaults (id, x, z) VALUES "
"(%s, %s, %s), (%s, %s, %s), (%s, %s, %s)",
checkpositional=checkpositional,
check_prefetch=[
table1.c.x,
table1.c.z,
crud._multiparam_column(table1.c.x, 0),
crud._multiparam_column(table1.c.z, 0),
crud._multiparam_column(table1.c.x, 1),
crud._multiparam_column(table1.c.z, 1),
],
dialect=dialect,
)
def test_mix_single_and_multi_single_first(self):
table1 = self.tables.mytable
stmt = table1.insert().values(myid=1, name="d1")
stmt = stmt.values(
[{"myid": 2, "name": "d2"}, {"myid": 3, "name": "d3"}]
)
assert_raises_message(
exc.InvalidRequestError,
"Can't mix single and multiple VALUES formats in one "
"INSERT statement",
stmt.compile,
)
def test_mix_single_and_multi_multi_first(self):
table1 = self.tables.mytable
stmt = table1.insert().values(
[{"myid": 2, "name": "d2"}, {"myid": 3, "name": "d3"}]
)
stmt = stmt.values(myid=1, name="d1")
assert_raises_message(
exc.InvalidRequestError,
"Can't mix single and multiple VALUES formats in one "
"INSERT statement",
stmt.compile,
)
def test_multi_multi(self):
table1 = self.tables.mytable
stmt = table1.insert().values([{"myid": 1, "name": "d1"}])
stmt = stmt.values(
[{"myid": 2, "name": "d2"}, {"myid": 3, "name": "d3"}]
)
self.assert_compile(
stmt,
"INSERT INTO mytable (myid, name) VALUES (%(myid_m0)s, "
"%(name_m0)s), (%(myid_m1)s, %(name_m1)s), (%(myid_m2)s, "
"%(name_m2)s)",
checkparams={
"myid_m0": 1,
"name_m0": "d1",
"myid_m1": 2,
"name_m1": "d2",
"myid_m2": 3,
"name_m2": "d3",
},
dialect=postgresql.dialect(),
)
def test_inline_default(self):
metadata = MetaData()
table = Table(
"sometable",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String),
Column("foo", Integer, default=func.foobar()),
)
values = [
{"id": 1, "data": "data1"},
{"id": 2, "data": "data2", "foo": "plainfoo"},
{"id": 3, "data": "data3"},
]
checkparams = {
"id_m0": 1,
"id_m1": 2,
"id_m2": 3,
"data_m0": "data1",
"data_m1": "data2",
"data_m2": "data3",
"foo_m1": "plainfoo",
}
self.assert_compile(
table.insert().values(values),
"INSERT INTO sometable (id, data, foo) VALUES "
"(%(id_m0)s, %(data_m0)s, foobar()), "
"(%(id_m1)s, %(data_m1)s, %(foo_m1)s), "
"(%(id_m2)s, %(data_m2)s, foobar())",
checkparams=checkparams,
dialect=postgresql.dialect(),
)
@testing.combinations(("strings",), ("columns",), ("inspectables",))
def test_python_scalar_default(self, key_type):
metadata = MetaData()
table = Table(
"sometable",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String),
Column("foo", Integer, default=10),
)
if key_type == "strings":
id_, data, foo = "id", "data", "foo"
elif key_type == "columns":
id_, data, foo = table.c.id, table.c.data, table.c.foo
elif key_type == "inspectables":
id_, data, foo = (
ORMExpr(table.c.id),
ORMExpr(table.c.data),
ORMExpr(table.c.foo),
)
else:
assert False
values = [
{id_: 1, data: "data1"},
{id_: 2, data: "data2", foo: 15},
{id_: 3, data: "data3"},
]
checkparams = {
"id_m0": 1,
"id_m1": 2,
"id_m2": 3,
"data_m0": "data1",
"data_m1": "data2",
"data_m2": "data3",
"foo": None, # evaluated later
"foo_m1": 15,
"foo_m2": None, # evaluated later
}
stmt = table.insert().values(values)
eq_(
{
k: v.type._type_affinity
for (k, v) in stmt.compile(
dialect=postgresql.dialect()
).binds.items()
},
{
"foo": Integer,
"data_m2": String,
"id_m0": Integer,
"id_m2": Integer,
"foo_m1": Integer,
"data_m1": String,
"id_m1": Integer,
"foo_m2": Integer,
"data_m0": String,
},
)
self.assert_compile(
stmt,
"INSERT INTO sometable (id, data, foo) VALUES "
"(%(id_m0)s, %(data_m0)s, %(foo)s), "
"(%(id_m1)s, %(data_m1)s, %(foo_m1)s), "
"(%(id_m2)s, %(data_m2)s, %(foo_m2)s)",
checkparams=checkparams,
dialect=postgresql.dialect(),
)
def test_sql_expression_pk_autoinc_lastinserted(self):
# test that postfetch isn't invoked for a SQL expression
# in a primary key column. the DB either needs to support a lastrowid
# that can return it, or RETURNING. [ticket:3133]
metadata = MetaData()
table = Table(
"sometable",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String),
)
stmt = table.insert().return_defaults().values(id=func.foobar())
dialect = sqlite.dialect()
dialect.insert_returning = False
compiled = stmt.compile(dialect=dialect, column_keys=["data"])
eq_(compiled.postfetch, [])
eq_(compiled.implicit_returning, [])
self.assert_compile(
stmt,
"INSERT INTO sometable (id, data) VALUES (foobar(), ?)",
checkparams={"data": "foo"},
params={"data": "foo"},
dialect=dialect,
)
def test_sql_expression_pk_autoinc_returning(self):
# test that return_defaults() works with a primary key where we are
# sending a SQL expression, and we need to get the server-calculated
# value back. [ticket:3133]
metadata = MetaData()
table = Table(
"sometable",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String),
)
stmt = table.insert().return_defaults().values(id=func.foobar())
returning_dialect = postgresql.dialect()
returning_dialect.implicit_returning = True
compiled = stmt.compile(
dialect=returning_dialect, column_keys=["data"]
)
eq_(compiled.postfetch, [])
eq_(compiled.implicit_returning, [table.c.id])
self.assert_compile(
stmt,
"INSERT INTO sometable (id, data) VALUES "
"(foobar(), %(data)s) RETURNING sometable.id",
checkparams={"data": "foo"},
params={"data": "foo"},
dialect=returning_dialect,
)
def test_sql_expression_pk_noautoinc_returning(self):
# test that return_defaults() works with a primary key where we are
# sending a SQL expression, and we need to get the server-calculated
# value back. [ticket:3133]
metadata = MetaData()
table = Table(
"sometable",
metadata,
Column("id", Integer, autoincrement=False, primary_key=True),
Column("data", String),
)
stmt = table.insert().return_defaults().values(id=func.foobar())
returning_dialect = postgresql.dialect()
returning_dialect.implicit_returning = True
compiled = stmt.compile(
dialect=returning_dialect, column_keys=["data"]
)
eq_(compiled.postfetch, [])
eq_(compiled.implicit_returning, [table.c.id])
self.assert_compile(
stmt,
"INSERT INTO sometable (id, data) VALUES "
"(foobar(), %(data)s) RETURNING sometable.id",
checkparams={"data": "foo"},
params={"data": "foo"},
dialect=returning_dialect,
)
def test_python_fn_default(self):
metadata = MetaData()
table = Table(
"sometable",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String),
Column("foo", Integer, default=lambda: 10),
)
values = [
{"id": 1, "data": "data1"},
{"id": 2, "data": "data2", "foo": 15},
{"id": 3, "data": "data3"},
]
checkparams = {
"id_m0": 1,
"id_m1": 2,
"id_m2": 3,
"data_m0": "data1",
"data_m1": "data2",
"data_m2": "data3",
"foo": None, # evaluated later
"foo_m1": 15,
"foo_m2": None, # evaluated later
}
stmt = table.insert().values(values)
eq_(
{
k: v.type._type_affinity
for (k, v) in stmt.compile(
dialect=postgresql.dialect()
).binds.items()
},
{
"foo": Integer,
"data_m2": String,
"id_m0": Integer,
"id_m2": Integer,
"foo_m1": Integer,
"data_m1": String,
"id_m1": Integer,
"foo_m2": Integer,
"data_m0": String,
},
)
self.assert_compile(
stmt,
"INSERT INTO sometable (id, data, foo) VALUES "
"(%(id_m0)s, %(data_m0)s, %(foo)s), "
"(%(id_m1)s, %(data_m1)s, %(foo_m1)s), "
"(%(id_m2)s, %(data_m2)s, %(foo_m2)s)",
checkparams=checkparams,
dialect=postgresql.dialect(),
)
def test_sql_functions(self):
metadata = MetaData()
table = Table(
"sometable",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String),
Column("foo", Integer),
)
values = [
{"id": 1, "data": "foo", "foo": func.foob()},
{"id": 2, "data": "bar", "foo": func.foob()},
{"id": 3, "data": "bar", "foo": func.bar()},
{"id": 4, "data": "bar", "foo": 15},
{"id": 5, "data": "bar", "foo": func.foob()},
]
checkparams = {
"id_m0": 1,
"data_m0": "foo",
"id_m1": 2,
"data_m1": "bar",
"id_m2": 3,
"data_m2": "bar",
"id_m3": 4,
"data_m3": "bar",
"foo_m3": 15,
"id_m4": 5,
"data_m4": "bar",
}
self.assert_compile(
table.insert().values(values),
"INSERT INTO sometable (id, data, foo) VALUES "
"(%(id_m0)s, %(data_m0)s, foob()), "
"(%(id_m1)s, %(data_m1)s, foob()), "
"(%(id_m2)s, %(data_m2)s, bar()), "
"(%(id_m3)s, %(data_m3)s, %(foo_m3)s), "
"(%(id_m4)s, %(data_m4)s, foob())",
checkparams=checkparams,
dialect=postgresql.dialect(),
)
def test_server_default(self):
metadata = MetaData()
table = Table(
"sometable",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String),
Column("foo", Integer, server_default=func.foobar()),
)
values = [
{"id": 1, "data": "data1"},
{"id": 2, "data": "data2", "foo": "plainfoo"},
{"id": 3, "data": "data3"},
]
checkparams = {
"id_m0": 1,
"id_m1": 2,
"id_m2": 3,
"data_m0": "data1",
"data_m1": "data2",
"data_m2": "data3",
}
self.assert_compile(
table.insert().values(values),
"INSERT INTO sometable (id, data) VALUES "
"(%(id_m0)s, %(data_m0)s), "
"(%(id_m1)s, %(data_m1)s), "
"(%(id_m2)s, %(data_m2)s)",
checkparams=checkparams,
dialect=postgresql.dialect(),
)
def test_server_default_absent_value(self):
metadata = MetaData()
table = Table(
"sometable",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String),
Column("foo", Integer, server_default=func.foobar()),
)
values = [
{"id": 1, "data": "data1", "foo": "plainfoo"},
{"id": 2, "data": "data2"},
{"id": 3, "data": "data3", "foo": "otherfoo"},
]
assert_raises_message(
exc.CompileError,
"INSERT value for column sometable.foo is explicitly rendered "
"as a boundparameter in the VALUES clause; a Python-side value or "
"SQL expression is required",
table.insert().values(values).compile,
)
| MultirowTest |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 907276,
"end": 907684
} | class ____(sgqlc.types.Type, Node, UniformResourceLocatable):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("commit", "pull_request")
commit = sgqlc.types.Field(sgqlc.types.non_null(Commit), graphql_name="commit")
pull_request = sgqlc.types.Field(
sgqlc.types.non_null(PullRequest), graphql_name="pullRequest"
)
| PullRequestCommit |
python | great-expectations__great_expectations | tests/expectations/test_expectation.py | {
"start": 20096,
"end": 22501
} | class ____:
@pytest.mark.unit
def test_hash_consistency_with_equality(self):
expectation1 = gxe.ExpectColumnValuesToNotBeNull(
column="test_column", mostly=0.95, meta={"test": "value"}, notes="test notes"
)
expectation2 = gxe.ExpectColumnValuesToNotBeNull(
column="test_column", mostly=0.95, meta={"test": "value"}, notes="test notes"
)
assert expectation1 == expectation2
assert hash(expectation1) == hash(expectation2)
@pytest.mark.unit
def test_hash_different_for_different_columns(self):
expectation1 = gxe.ExpectColumnValuesToNotBeNull(column="test_column_1")
expectation2 = gxe.ExpectColumnValuesToNotBeNull(column="test_column_2")
assert expectation1 != expectation2
assert hash(expectation1) != hash(expectation2)
@pytest.mark.unit
def test_hash_different_for_different_mostly(self):
expectation1 = gxe.ExpectColumnValuesToNotBeNull(column="test_column", mostly=0.95)
expectation2 = gxe.ExpectColumnValuesToNotBeNull(column="test_column", mostly=0.90)
assert expectation1 != expectation2
assert hash(expectation1) != hash(expectation2)
@pytest.mark.unit
def test_hash_different_for_different_meta(self):
expectation1 = gxe.ExpectColumnValuesToNotBeNull(
column="test_column", meta={"test": "value1"}
)
expectation2 = gxe.ExpectColumnValuesToNotBeNull(
column="test_column", meta={"test": "value2"}
)
assert expectation1 != expectation2
assert hash(expectation1) != hash(expectation2)
@pytest.mark.unit
def test_hash_excludes_rendered_content(self):
expectation1 = gxe.ExpectColumnValuesToNotBeNull(column="test_column")
expectation2 = gxe.ExpectColumnValuesToNotBeNull(column="test_column")
expectation1.render()
assert expectation1 == expectation2
assert hash(expectation1) == hash(expectation2)
@pytest.mark.unit
def test_hash_stable_across_runs(self):
expectation = gxe.ExpectColumnValuesToNotBeNull(
column="test_column", mostly=0.95, meta={"test": "value"}, notes="test notes"
)
hash1 = hash(expectation)
hash2 = hash(expectation)
hash3 = hash(expectation)
assert hash1 == hash2 == hash3
@pytest.mark.unit
| TestExpectationHash |
python | getsentry__sentry | src/sentry/types/ratelimit.py | {
"start": 866,
"end": 1788
} | class ____:
"""
Rate Limit response metadata
Attributes:
is_limited (bool): request is rate limited
current (int): number of requests done in the current window
remaining (int): number of requests left in the current window
limit (int): max number of requests per window
window (int): window size in seconds
reset_time (int): UTC Epoch time in seconds when the current window expires
"""
rate_limit_type: RateLimitType
current: int
remaining: int
limit: int
window: int
group: str
reset_time: int
concurrent_limit: int | None
concurrent_requests: int | None
@property
def concurrent_remaining(self) -> int | None:
if self.concurrent_limit is not None and self.concurrent_requests is not None:
return self.concurrent_limit - self.concurrent_requests
return None
@dataclass
| RateLimitMeta |
python | huggingface__transformers | src/transformers/models/parakeet/modeling_parakeet.py | {
"start": 19029,
"end": 21071
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: ParakeetEncoderConfig, layer_idx: Optional[int] = None):
super().__init__()
self.gradient_checkpointing = False
self.feed_forward1 = ParakeetEncoderFeedForward(config)
self.self_attn = ParakeetEncoderAttention(config, layer_idx)
self.conv = ParakeetEncoderConvolutionModule(config)
self.feed_forward2 = ParakeetEncoderFeedForward(config)
self.norm_feed_forward1 = nn.LayerNorm(config.hidden_size)
self.norm_self_att = nn.LayerNorm(config.hidden_size)
self.norm_conv = nn.LayerNorm(config.hidden_size)
self.norm_feed_forward2 = nn.LayerNorm(config.hidden_size)
self.norm_out = nn.LayerNorm(config.hidden_size)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_embeddings: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.feed_forward1(self.norm_feed_forward1(hidden_states))
hidden_states = residual + 0.5 * hidden_states # the conformer architecture uses a factor of 0.5
normalized_hidden_states = self.norm_self_att(hidden_states)
attn_output, _ = self.self_attn(
hidden_states=normalized_hidden_states,
attention_mask=attention_mask,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = hidden_states + attn_output
conv_output = self.conv(self.norm_conv(hidden_states), attention_mask=attention_mask)
hidden_states = hidden_states + conv_output
ff2_output = self.feed_forward2(self.norm_feed_forward2(hidden_states))
hidden_states = hidden_states + 0.5 * ff2_output # the conformer architecture uses a factor of 0.5
hidden_states = self.norm_out(hidden_states)
return hidden_states
@auto_docstring
| ParakeetEncoderBlock |
python | allegroai__clearml | clearml/backend_api/services/v2_23/frames.py | {
"start": 111050,
"end": 111307
} | class ____(Response):
"""
Response of frames.download_for_dataview endpoint.
"""
_service = "frames"
_action = "download_for_dataview"
_version = "2.23"
_schema = {"definitions": {}, "type": "string"}
| DownloadForDataviewResponse |
python | astropy__astropy | astropy/modeling/core.py | {
"start": 2218,
"end": 2308
} | class ____(TypeError):
"""Used for incorrect models definitions."""
| ModelDefinitionError |
python | dask__distributed | distributed/shuffle/tests/test_shuffle.py | {
"start": 55638,
"end": 66752
} | class ____(AbstractShuffleTestPool):
_shuffle_run_id_iterator = itertools.count()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._executor = ThreadPoolExecutor(2)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
try:
self._executor.shutdown(cancel_futures=True)
except Exception: # pragma: no cover
self._executor.shutdown()
def new_shuffle(
self,
name,
meta,
worker_for_mapping,
directory,
loop,
disk,
drop_column,
Shuffle=DataFrameShuffleRun,
):
s = Shuffle(
column="_partition",
meta=meta,
worker_for=worker_for_mapping,
directory=directory / name,
id=ShuffleId(name),
run_id=next(AbstractShuffleTestPool._shuffle_run_id_iterator),
span_id=None,
local_address=name,
executor=self._executor,
rpc=self,
digest_metric=lambda name, value: None,
scheduler=self,
memory_limiter_disk=ResourceLimiter(10000000),
memory_limiter_comms=ResourceLimiter(10000000),
disk=disk,
drop_column=drop_column,
loop=loop,
)
self.shuffles[name] = s
return s
# 36 parametrizations
# Runtime each ~0.1s
@pytest.mark.skipif(not pa, reason="Requires PyArrow")
@pytest.mark.parametrize("n_workers", [1, 10])
@pytest.mark.parametrize("n_input_partitions", [1, 2, 10])
@pytest.mark.parametrize("npartitions", [1, 20])
@pytest.mark.parametrize("barrier_first_worker", [True, False])
@pytest.mark.parametrize("disk", [True, False])
@pytest.mark.parametrize("drop_column", [True, False])
@gen_test()
async def test_basic_lowlevel_shuffle(
tmp_path,
n_workers,
n_input_partitions,
npartitions,
barrier_first_worker,
disk,
drop_column,
):
loop = IOLoop.current()
dfs = []
rows_per_df = 10
for ix in range(n_input_partitions):
df = pd.DataFrame({"x": range(rows_per_df * ix, rows_per_df * (ix + 1))})
df["_partition"] = df.x % npartitions
dfs.append(df)
workers = list("abcdefghijklmn")[:n_workers]
worker_for_mapping = {}
for part in range(npartitions):
worker_for_mapping[part] = _get_worker_for_range_sharding(
npartitions, part, workers
)
assert len(set(worker_for_mapping.values())) == min(n_workers, npartitions)
meta = dfs[0].head(0)
with DataFrameShuffleTestPool() as local_shuffle_pool:
shuffles = []
for ix in range(n_workers):
shuffles.append(
local_shuffle_pool.new_shuffle(
name=workers[ix],
meta=meta,
worker_for_mapping=worker_for_mapping,
directory=tmp_path,
loop=loop,
disk=disk,
drop_column=drop_column,
)
)
random.seed(42)
if barrier_first_worker:
barrier_worker = shuffles[0]
else:
barrier_worker = random.sample(shuffles, k=1)[0]
run_ids = []
try:
for ix, df in enumerate(dfs):
s = shuffles[ix % len(shuffles)]
run_ids.append(await asyncio.to_thread(s.add_partition, df, ix))
await barrier_worker.barrier(run_ids=run_ids)
total_bytes_sent = 0
total_bytes_recvd = 0
total_bytes_recvd_shuffle = 0
for s in shuffles:
metrics = s.heartbeat()
assert metrics["comm"]["total"] == metrics["comm"]["written"]
total_bytes_sent += metrics["comm"]["written"]
total_bytes_recvd += metrics["disk"]["total"]
total_bytes_recvd_shuffle += s.total_recvd
assert total_bytes_recvd_shuffle == total_bytes_sent
all_parts = []
for part, worker in worker_for_mapping.items():
s = local_shuffle_pool.shuffles[worker]
all_parts.append(
asyncio.to_thread(
s.get_output_partition, part, f"key-{part}", meta=meta
)
)
all_parts = await asyncio.gather(*all_parts)
df_after = pd.concat(all_parts)
finally:
await asyncio.gather(*[s.close() for s in shuffles])
assert len(df_after) == len(pd.concat(dfs))
@pytest.mark.skipif(not pa, reason="Requires PyArrow")
@gen_test()
async def test_error_offload(tmp_path, loop_in_thread):
dfs = []
rows_per_df = 10
n_input_partitions = 2
npartitions = 2
for ix in range(n_input_partitions):
df = pd.DataFrame({"x": range(rows_per_df * ix, rows_per_df * (ix + 1))})
df["_partition"] = df.x % npartitions
dfs.append(df)
meta = dfs[0].head(0)
workers = ["A", "B"]
worker_for_mapping = {}
partitions_for_worker = defaultdict(list)
for part in range(npartitions):
worker_for_mapping[part] = w = _get_worker_for_range_sharding(
npartitions, part, workers
)
partitions_for_worker[w].append(part)
class ErrorOffload(DataFrameShuffleRun):
async def offload(self, func, *args):
raise RuntimeError("Error during deserialization")
with DataFrameShuffleTestPool() as local_shuffle_pool:
sA = local_shuffle_pool.new_shuffle(
name="A",
meta=meta,
worker_for_mapping=worker_for_mapping,
directory=tmp_path,
loop=loop_in_thread,
disk=True,
drop_column=True,
Shuffle=ErrorOffload,
)
sB = local_shuffle_pool.new_shuffle(
name="B",
meta=meta,
worker_for_mapping=worker_for_mapping,
directory=tmp_path,
loop=loop_in_thread,
disk=True,
drop_column=True,
)
try:
sB.add_partition(dfs[0], 0)
with pytest.raises(RuntimeError, match="Error during deserialization"):
sB.add_partition(dfs[1], 1)
await sB.barrier(run_ids=[sB.run_id, sB.run_id])
finally:
await asyncio.gather(*[s.close() for s in [sA, sB]])
@pytest.mark.skipif(not pa, reason="Requires PyArrow")
@gen_test()
async def test_error_send(tmp_path, loop_in_thread):
dfs = []
rows_per_df = 10
n_input_partitions = 1
npartitions = 2
for ix in range(n_input_partitions):
df = pd.DataFrame({"x": range(rows_per_df * ix, rows_per_df * (ix + 1))})
df["_partition"] = df.x % npartitions
dfs.append(df)
meta = dfs[0].head(0)
workers = ["A", "B"]
worker_for_mapping = {}
partitions_for_worker = defaultdict(list)
for part in range(npartitions):
worker_for_mapping[part] = w = _get_worker_for_range_sharding(
npartitions, part, workers
)
partitions_for_worker[w].append(part)
class ErrorSend(DataFrameShuffleRun):
async def send(self, *args: Any, **kwargs: Any) -> OKMessage | ErrorMessage:
raise RuntimeError("Error during send")
with DataFrameShuffleTestPool() as local_shuffle_pool:
sA = local_shuffle_pool.new_shuffle(
name="A",
meta=meta,
worker_for_mapping=worker_for_mapping,
directory=tmp_path,
loop=loop_in_thread,
disk=True,
drop_column=True,
Shuffle=ErrorSend,
)
sB = local_shuffle_pool.new_shuffle(
name="B",
meta=meta,
worker_for_mapping=worker_for_mapping,
directory=tmp_path,
loop=loop_in_thread,
disk=True,
drop_column=True,
)
try:
sA.add_partition(dfs[0], 0)
with pytest.raises(RuntimeError, match="Error during send"):
await sA.barrier(run_ids=[sA.run_id])
finally:
await asyncio.gather(*[s.close() for s in [sA, sB]])
@pytest.mark.skipif(not pa, reason="Requires PyArrow")
@pytest.mark.parametrize("Error", [P2PConsistencyError, ValueError])
@gen_test()
async def test_error_receive(tmp_path, loop_in_thread, Error):
dfs = []
rows_per_df = 10
n_input_partitions = 1
npartitions = 2
for ix in range(n_input_partitions):
df = pd.DataFrame({"x": range(rows_per_df * ix, rows_per_df * (ix + 1))})
df["_partition"] = df.x % npartitions
dfs.append(df)
meta = dfs[0].head(0)
workers = ["A", "B"]
worker_for_mapping = {}
partitions_for_worker = defaultdict(list)
for part in range(npartitions):
worker_for_mapping[part] = w = _get_worker_for_range_sharding(
npartitions, part, workers
)
partitions_for_worker[w].append(part)
class ErrorReceive(DataFrameShuffleRun):
async def _receive(self, data: list[tuple[int, bytes]]) -> None:
raise Error("Error during receive")
with DataFrameShuffleTestPool() as local_shuffle_pool:
sA = local_shuffle_pool.new_shuffle(
name="A",
meta=meta,
worker_for_mapping=worker_for_mapping,
directory=tmp_path,
loop=loop_in_thread,
disk=True,
drop_column=True,
Shuffle=ErrorReceive,
)
sB = local_shuffle_pool.new_shuffle(
name="B",
meta=meta,
worker_for_mapping=worker_for_mapping,
directory=tmp_path,
loop=loop_in_thread,
disk=True,
drop_column=True,
)
try:
sB.add_partition(dfs[0], 0)
with pytest.raises(Error, match="Error during receive"):
await sB.barrier(run_ids=[sB.run_id])
finally:
await asyncio.gather(*[s.close() for s in [sA, sB]])
@gen_cluster(client=True)
async def test_meaningful_out_of_disk_error(c, s, a, b):
class OutOfDiskShardsBuffer(DiskShardsBuffer):
def _write_frames(self, frames, id):
code = errno.ENOSPC
raise OSError(code, os.strerror(code))
df = dask.datasets.timeseries(
start="2000-01-01",
end="2000-01-10",
dtypes={"x": float, "y": float},
freq="10 s",
)
with dask.config.set(
{"dataframe.shuffle.method": "p2p", "distributed.p2p.storage.disk": True}
):
shuffled = df.shuffle("x", npartitions=10, force=True)
with pytest.raises(P2POutOfDiskError, match="out of available disk space"):
with mock.patch(
"distributed.shuffle._core.DiskShardsBuffer",
OutOfDiskShardsBuffer,
):
await c.compute(shuffled)
await assert_worker_cleanup(a)
await assert_worker_cleanup(b)
await c.close()
await assert_scheduler_cleanup(s)
| DataFrameShuffleTestPool |
python | huggingface__transformers | src/transformers/models/deformable_detr/modeling_deformable_detr.py | {
"start": 22734,
"end": 27499
} | class ____(nn.Module):
"""
Multiscale deformable attention as proposed in Deformable DETR.
"""
def __init__(self, config: DeformableDetrConfig, num_heads: int, n_points: int):
super().__init__()
self.attn = MultiScaleDeformableAttention()
if config.d_model % num_heads != 0:
raise ValueError(
f"embed_dim (d_model) must be divisible by num_heads, but got {config.d_model} and {num_heads}"
)
dim_per_head = config.d_model // num_heads
# check if dim_per_head is power of 2
if not ((dim_per_head & (dim_per_head - 1) == 0) and dim_per_head != 0):
warnings.warn(
"You'd better set embed_dim (d_model) in DeformableDetrMultiscaleDeformableAttention to make the"
" dimension of each attention head a power of 2 which is more efficient in the authors' CUDA"
" implementation."
)
self.im2col_step = 64
self.d_model = config.d_model
self.n_levels = config.num_feature_levels
self.n_heads = num_heads
self.n_points = n_points
self.sampling_offsets = nn.Linear(config.d_model, num_heads * self.n_levels * n_points * 2)
self.attention_weights = nn.Linear(config.d_model, num_heads * self.n_levels * n_points)
self.value_proj = nn.Linear(config.d_model, config.d_model)
self.output_proj = nn.Linear(config.d_model, config.d_model)
self.disable_custom_kernels = config.disable_custom_kernels
def with_pos_embed(self, tensor: torch.Tensor, position_embeddings: Optional[Tensor]):
return tensor if position_embeddings is None else tensor + position_embeddings
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
encoder_hidden_states=None,
encoder_attention_mask=None,
position_embeddings: Optional[torch.Tensor] = None,
reference_points=None,
spatial_shapes=None,
spatial_shapes_list=None,
level_start_index=None,
output_attentions: bool = False,
):
# add position embeddings to the hidden states before projecting to queries and keys
if position_embeddings is not None:
hidden_states = self.with_pos_embed(hidden_states, position_embeddings)
batch_size, num_queries, _ = hidden_states.shape
batch_size, sequence_length, _ = encoder_hidden_states.shape
total_elements = sum(height * width for height, width in spatial_shapes_list)
if total_elements != sequence_length:
raise ValueError(
"Make sure to align the spatial shapes with the sequence length of the encoder hidden states"
)
value = self.value_proj(encoder_hidden_states)
if attention_mask is not None:
# we invert the attention_mask
value = value.masked_fill(~attention_mask[..., None], float(0))
value = value.view(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
sampling_offsets = self.sampling_offsets(hidden_states).view(
batch_size, num_queries, self.n_heads, self.n_levels, self.n_points, 2
)
attention_weights = self.attention_weights(hidden_states).view(
batch_size, num_queries, self.n_heads, self.n_levels * self.n_points
)
attention_weights = F.softmax(attention_weights, -1).view(
batch_size, num_queries, self.n_heads, self.n_levels, self.n_points
)
# batch_size, num_queries, n_heads, n_levels, n_points, 2
num_coordinates = reference_points.shape[-1]
if num_coordinates == 2:
offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
sampling_locations = (
reference_points[:, :, None, :, None, :]
+ sampling_offsets / offset_normalizer[None, None, None, :, None, :]
)
elif num_coordinates == 4:
sampling_locations = (
reference_points[:, :, None, :, None, :2]
+ sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
)
else:
raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {reference_points.shape[-1]}")
output = self.attn(
value,
spatial_shapes,
spatial_shapes_list,
level_start_index,
sampling_locations,
attention_weights,
self.im2col_step,
)
output = self.output_proj(output)
return output, attention_weights
| DeformableDetrMultiscaleDeformableAttention |
python | openai__openai-python | tests/test_utils/test_typing.py | {
"start": 280,
"end": 344
} | class ____(Generic[_T, _T2, _T3]): ...
| BaseGenericMultipleTypeArgs |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 60918,
"end": 62844
} | class ____(nn.Module):
"""
ModuleList of experts.
"""
def __init__(self, config: Qwen3OmniMoeThinkerConfig):
super().__init__()
self.num_experts = config.num_experts
self.hidden_dim = config.hidden_size
self.intermediate_dim = config.moe_intermediate_size
self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
self.act_fn = ACT2FN[config.hidden_act]
def forward(
self,
hidden_states: torch.Tensor,
top_k_index: torch.Tensor,
top_k_weights: torch.Tensor,
) -> torch.Tensor:
final_hidden_states = torch.zeros_like(hidden_states)
num_experts = top_k_weights.shape[1]
with torch.no_grad():
expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=num_experts + 1)
expert_mask = expert_mask.permute(2, 1, 0)
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
for expert_idx in expert_hit:
expert_idx = expert_idx[0]
if expert_idx == num_experts:
continue
_, token_idx = torch.where(expert_mask[expert_idx])
current_state = hidden_states[token_idx]
gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
current_hidden_states = self.act_fn(gate) * up
current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
current_hidden_states = current_hidden_states * top_k_weights[token_idx, expert_idx, None]
final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
return final_hidden_states
| Qwen3OmniMoeThinkerTextExperts |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_export.py | {
"start": 22980,
"end": 24191
} | class ____(AdminTestMixin, TestCase):
"""
If a custom field is declared, export should work
even if no `fields` declaration is present.
(issue 1953)
"""
class _BookResource(ModelResource):
name = Field(attribute="author__name", column_name="Author Name")
class Meta:
model = Book
def setUp(self):
super().setUp()
self.author = Author.objects.create(id=11, name="Ian Fleming")
self.book = Book.objects.create(
name="Moonraker", author=self.author, published=date(1955, 4, 5)
)
@patch("import_export.mixins.BaseExportMixin.choose_export_resource_class")
def test_export_with_declared_author_name_field(
self, mock_choose_export_resource_class
):
mock_choose_export_resource_class.return_value = self._BookResource
data = {
"format": "0",
"resource": "0",
"bookresource_name": True,
}
self._prepend_form_prefix(data)
response = self._post_url_response(self.book_export_url, data)
s = "Author Name\r\nIan Fleming\r\n"
self.assertEqual(s, response.content.decode())
| DeclaredFieldWithAttributeExportTest |
python | pytorch__pytorch | test/nn/test_packed_sequence.py | {
"start": 183,
"end": 21346
} | class ____(TestCase):
_type_by_name = {
"torch.DoubleTensor": (torch.DoubleTensor, "double"),
"torch.FloatTensor": (torch.FloatTensor, "float"),
# We leave out `'torch.HalfTensor': (torch.HalfTensor, 'half'),`
# because of an error in `pad_packed_sequence`
# > AttributeError: 'torch.HalfTensor' object has no attribute 'fill_'
"torch.LongTensor": (torch.LongTensor, "long"),
"torch.IntTensor": (torch.IntTensor, "int"),
"torch.ShortTensor": (torch.ShortTensor, "short"),
"torch.CharTensor": (torch.CharTensor, "char"),
"torch.ByteTensor": (torch.ByteTensor, "byte"),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.batch_size = 5
self.max_length = 6
def _ordered_sequence(self, tensor_type):
"""Create ordered list of random sequences"""
seqs = [
tensor_type(random.randint(1, self.max_length))
for _ in range(self.batch_size)
]
if tensor_type == torch.ByteTensor:
seqs = [s.random_(0, 256) for s in seqs]
else:
seqs = [s.random_(-128, 128) for s in seqs]
ordered = sorted(seqs, key=len, reverse=True)
return ordered
def _padded_sequence(self, tensor_type):
"""Create Tensor of random padded sequences"""
ordered = self._ordered_sequence(tensor_type)
lengths = [len(i) for i in ordered]
padded_tensor = rnn_utils.pad_sequence(ordered)
return padded_tensor, lengths
def test_type_casts(self):
"""Test type casting of `PackedSequence` against type casting of tensor"""
for input_type, _ in self._type_by_name.values():
for expected_type_str, (_, cast_str) in self._type_by_name.items():
for enforce_sorted in [True, False]:
padded, lengths = self._padded_sequence(input_type)
packed = rnn_utils.pack_padded_sequence(
padded, lengths, enforce_sorted=enforce_sorted
)
# Apply cast to `PackedSequence` instance and unpack
masked = getattr(packed, cast_str)()
unpacked, _ = rnn_utils.pad_packed_sequence(masked)
self.assertEqual(unpacked.type(), expected_type_str)
def test_wrong_order(self):
a = torch.ones(25, 300)
b = torch.ones(22, 300)
b_a = rnn_utils.pad_sequence([b, a])
self.assertRaises(
RuntimeError,
lambda: rnn_utils.pack_padded_sequence(b_a, [22, 25], enforce_sorted=True),
)
def test_pad_sequence_with_tensor_sequences(self):
seq_tuple_input = torch.nn.utils.rnn.pad_sequence(
(torch.tensor([[7, 6]]), torch.tensor([[-7, -1]]))
)
seq_tensor_input = torch.nn.utils.rnn.pad_sequence(
torch.tensor([[[7, 6]], [[-7, -1]]])
)
self.assertEqual(seq_tuple_input, seq_tensor_input)
self.assertEqual(seq_tuple_input.shape, torch.Size([1, 2, 2]))
def test_pad_sequence_with_non_iterable_sequences(self):
msg = r"Expected iterable for input sequences, but got arg of type"
with self.assertRaisesRegex(RuntimeError, msg):
torch.nn.utils.rnn.pad_sequence(5)
def test_total_length(self):
padded, lengths = self._padded_sequence(torch.FloatTensor)
max_length = max(lengths)
packed = rnn_utils.pack_padded_sequence(padded, lengths)
# test ValueError if total_length < max_length
for total_length in (-1, 0, max_length - 1):
for batch_first in (True, False):
def err_fn():
rnn_utils.pad_packed_sequence(
packed, batch_first=batch_first, total_length=total_length
)
self.assertRaisesRegex(
ValueError,
r"Expected total_length to be at least the "
r"length of the longest sequence in input",
err_fn,
)
# test that pad_packed_sequence returns results of correct length
for batch_first in (True, False):
no_extra_pad, _ = rnn_utils.pad_packed_sequence(
packed, batch_first=batch_first
)
for total_length_delta in (0, 1, 8):
total_length = max_length + total_length_delta
unpacked, lengths_out = rnn_utils.pad_packed_sequence(
packed, batch_first=batch_first, total_length=total_length
)
self.assertEqual(lengths, lengths_out)
self.assertEqual(unpacked.size(1 if batch_first else 0), total_length)
if total_length_delta == 0:
ref_output = no_extra_pad
elif batch_first:
extra_pad = no_extra_pad.new_zeros(
self.batch_size, total_length_delta
)
ref_output = torch.cat([no_extra_pad, extra_pad], 1)
else:
extra_pad = no_extra_pad.new_zeros(
total_length_delta, self.batch_size
)
ref_output = torch.cat([no_extra_pad, extra_pad], 0)
self.assertEqual(unpacked, ref_output)
def test_to(self):
for enforce_sorted in (True, False):
padded, lengths = self._padded_sequence(torch.IntTensor)
a = rnn_utils.pack_padded_sequence(
padded, lengths, enforce_sorted=enforce_sorted
).cpu()
self.assertIs(a, a.to("cpu"))
self.assertIs(a, a.cpu())
self.assertIs(a, a.to("cpu", dtype=torch.int32))
self.assertEqual(a.long(), a.to(torch.int64))
if torch.cuda.is_available():
for cuda in [
"cuda",
"cuda:0" if torch.cuda.device_count() == 1 else "cuda:1",
]:
b = a.cuda(device=cuda)
self.assertIs(b, b.to(cuda))
self.assertIs(b, b.cuda())
self.assertEqual(a, b.to("cpu"))
self.assertEqual(b, a.to(cuda))
self.assertEqual(a, b.to("cpu", dtype=torch.int32))
self.assertIs(b, b.to(dtype=torch.int32))
self.assertEqual(b.long(), b.to(dtype=torch.int64))
def test_to_memory_format(self):
m = torch.nn.Conv2d(in_channels=16, out_channels=32, kernel_size=2, bias=True)
m = m.to(memory_format=torch.channels_last)
for param in m.parameters():
if param.dim() == 4:
self.assertTrue(param.is_contiguous(memory_format=torch.channels_last))
def test_pad_sequence(self):
def pad(tensor, length):
return torch.cat(
[
tensor.data,
tensor.data.new(
length - tensor.size(0), *tensor.size()[1:]
).zero_(),
]
)
# single dimensional
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5])
c = torch.tensor([6])
# batch_first = true
expected = torch.tensor([[4, 5, 0], [1, 2, 3], [6, 0, 0]])
padded = rnn_utils.pad_sequence([b, a, c], True)
self.assertEqual(padded, expected)
# batch_first = false
padded = rnn_utils.pad_sequence([b, a, c])
self.assertEqual(padded, expected.transpose(0, 1))
# padding_side = "left", batch_first=True
expected = torch.tensor([[0, 4, 5], [1, 2, 3], [0, 0, 6]])
padded = rnn_utils.pad_sequence(
[b, a, c],
batch_first=True,
padding_side="left",
)
self.assertEqual(padded, expected)
# padding_side = "left", batch_first=False
padded = rnn_utils.pad_sequence(
[b, a, c],
batch_first=False,
padding_side="left",
)
self.assertEqual(padded, expected.transpose(0, 1))
# pad with non-zero value
expected = torch.tensor([[4, 5, 1], [1, 2, 3], [6, 1, 1]])
padded = rnn_utils.pad_sequence([b, a, c], True, 1)
self.assertEqual(padded, expected)
# Test pad sorted sequence
expected = torch.tensor([[1, 2, 3], [4, 5, 0], [6, 0, 0]])
padded = rnn_utils.pad_sequence([a, b, c], True)
self.assertEqual(padded, expected)
# more dimensions
maxlen = 9
for num_dim in (0, 1, 2, 3):
sequences: list[torch.Tensor] = []
trailing_dims = [4] * num_dim
for i in range(1, maxlen + 1):
seq_len = i * i
sequences.append(torch.rand(seq_len, 5, *trailing_dims))
random.shuffle(sequences)
# batch first = true
expected = torch.stack([pad(seq, maxlen * maxlen) for seq in sequences])
padded = rnn_utils.pad_sequence(sequences, True)
self.assertEqual(padded, expected)
# batch first = false
padded = rnn_utils.pad_sequence(sequences)
self.assertEqual(padded, expected.transpose(0, 1))
# padding_side = "left", batch_first=True
expected = torch.stack(
[pad(seq.flip(0), maxlen * maxlen).flip(0) for seq in sequences]
)
padded = rnn_utils.pad_sequence(
sequences,
batch_first=True,
padding_side="left",
)
self.assertEqual(padded, expected)
# padding_side = "left", batch_first=False
padded = rnn_utils.pad_sequence(
sequences,
batch_first=False,
padding_side="left",
)
self.assertEqual(padded, expected.transpose(0, 1))
def test_unpad_sequence(self):
# single dimensional
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5])
c = torch.tensor([6])
sequences = [a, b, c]
lengths = torch.as_tensor([v.size(0) for v in sequences])
for batch_first in [True, False]:
padded_sequences = rnn_utils.pad_sequence(
sequences, batch_first=batch_first
)
unpadded_sequences = rnn_utils.unpad_sequence(
padded_sequences, lengths, batch_first=batch_first
)
self.assertEqual(sequences, unpadded_sequences)
# more dimensions
maxlen = 9
for num_dim in (0, 1, 2, 3):
sequences = []
trailing_dims = [4] * num_dim
for i in range(1, maxlen + 1):
seq_len = i * i
sequences.append(torch.rand(seq_len, 5, *trailing_dims))
random.shuffle(sequences)
lengths = torch.as_tensor([v.size(0) for v in sequences])
padded_sequences = rnn_utils.pad_sequence(
sequences, batch_first=batch_first
)
unpadded_sequences = rnn_utils.unpad_sequence(
padded_sequences, lengths, batch_first=batch_first
)
self.assertEqual(sequences, unpadded_sequences)
def test_pack_sequence(self):
def _compatibility_test(sequences, lengths, batch_first, enforce_sorted=False):
padded = rnn_utils.pad_sequence(sequences, batch_first)
packed = rnn_utils.pack_sequence(sequences, enforce_sorted)
unpacked = rnn_utils.pad_packed_sequence(packed, batch_first)
self.assertEqual(padded, unpacked[0])
pack_padded = rnn_utils.pack_padded_sequence(
padded, lengths, batch_first, enforce_sorted
)
self.assertEqual(packed, pack_padded)
# single dimensional
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5])
c = torch.tensor([6])
packed = rnn_utils.pack_sequence([a, b, c], enforce_sorted=False)
expected = torch.tensor([1, 4, 6, 2, 5, 3])
self.assertEqual(packed.batch_sizes, [3, 2, 1])
self.assertEqual(packed.data.data, expected)
self.assertEqual(packed.sorted_indices, [0, 1, 2])
self.assertEqual(packed.unsorted_indices, [0, 1, 2])
packed_unsorted = rnn_utils.pack_sequence([b, c, a], enforce_sorted=False)
self.assertEqual(packed_unsorted.batch_sizes, [3, 2, 1])
self.assertEqual(packed_unsorted.data.data, expected)
self.assertEqual(packed_unsorted.sorted_indices, [2, 0, 1])
self.assertEqual(packed_unsorted.unsorted_indices, [1, 2, 0])
# single dimensional, enforce_sorted = True
packed_enforce_sorted = rnn_utils.pack_sequence([a, b, c], enforce_sorted=True)
self.assertEqual(packed_enforce_sorted.batch_sizes, [3, 2, 1])
self.assertEqual(packed_enforce_sorted.data.data, expected)
self.assertTrue(packed_enforce_sorted.sorted_indices is None)
self.assertTrue(packed_enforce_sorted.unsorted_indices is None)
with self.assertRaisesRegex(RuntimeError, "must be sorted in decreasing order"):
rnn_utils.pack_sequence([b, c, a], enforce_sorted=True)
with self.assertRaisesRegex(
RuntimeError, "You can pass `enforce_sorted=False`"
):
rnn_utils.pack_sequence([b, c, a], enforce_sorted=True)
# more dimensions
maxlen = 9
for num_dim in (0, 1, 2, 3):
sequences = []
lengths = []
trailing_dims = [4] * num_dim
for i in range(maxlen, 0, -1):
seq_len = i * i
lengths.append(seq_len)
sequences.append(torch.rand(seq_len, 5, *trailing_dims))
unsorted_sequences = [s.clone() for s in sequences]
random.shuffle(unsorted_sequences)
unsorted_sequences_lengths = [t.size(0) for t in unsorted_sequences]
# compatibility with other utilities
for batch_first in (True, False):
for enforce_sorted in (True, False):
_compatibility_test(sequences, lengths, batch_first, enforce_sorted)
_compatibility_test(
unsorted_sequences, unsorted_sequences_lengths, batch_first
)
def test_unpack_sequence(self):
# single dimensional
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5])
c = torch.tensor([6])
sequences = [a, b, c]
packed_sequences = rnn_utils.pack_sequence(sequences, enforce_sorted=False)
unpacked_sequences = rnn_utils.unpack_sequence(packed_sequences)
self.assertEqual(sequences, unpacked_sequences)
# more dimensions
maxlen = 9
for num_dim in (0, 1, 2, 3):
sequences = []
trailing_dims = [4] * num_dim
for i in range(1, maxlen + 1):
seq_len = i * i
sequences.append(torch.rand(seq_len, 5, *trailing_dims))
random.shuffle(sequences)
packed_sequences = rnn_utils.pack_sequence(sequences, enforce_sorted=False)
unpacked_sequences = rnn_utils.unpack_sequence(packed_sequences)
self.assertEqual(sequences, unpacked_sequences)
def test_pack_padded_sequence(self):
def generate_test_case(sorted_lengths, should_shuffle):
def pad(tensor, length):
return torch.cat(
[
tensor,
tensor.new(length - tensor.size(0), *tensor.size()[1:]).zero_(),
]
)
max_length = sorted_lengths[0]
batch_sizes = [
sum(map(bool, filter(lambda x: x >= i, sorted_lengths)))
for i in range(1, max_length + 1)
]
padded = torch.cat(
[
pad(
i * 100 + torch.arange(1.0, 5 * l + 1).view(l, 1, 5), max_length
)
for i, l in enumerate(sorted_lengths, 1)
],
1,
)
expected_data = [
[
torch.arange(1.0, 6) + (i + 1) * 100 + 5 * n
for i in range(batch_size)
]
for n, batch_size in enumerate(batch_sizes)
]
expected_data = list(itertools.chain.from_iterable(expected_data))
expected_data = torch.stack(expected_data, dim=0)
if should_shuffle:
# Shuffle the padded sequence to create an unsorted sequence
permutation = list(range(len(sorted_lengths)))
random.shuffle(permutation)
unsorted_indices = torch.tensor(permutation)
padded = padded.index_select(1, unsorted_indices)
lengths = torch.tensor(sorted_lengths).index_select(0, unsorted_indices)
else:
unsorted_indices = None
lengths = sorted_lengths
return (
padded.requires_grad_(),
lengths,
expected_data,
batch_sizes,
unsorted_indices,
)
test_cases = [
# sorted_lengths, should_shuffle
[[10, 8, 4, 2, 2, 2, 1], False],
[[11, 10, 8, 6, 4, 3, 1], False],
[[11, 10, 8, 6, 4, 3, 1], True],
]
for test_case, batch_first in itertools.product(test_cases, (True, False)):
sorted_lengths, should_shuffle = test_case
(
padded,
lengths,
expected_data,
batch_sizes,
unsorted_indices,
) = generate_test_case(sorted_lengths, should_shuffle)
src = padded
if batch_first:
src = src.transpose(0, 1)
# check output
packed = rnn_utils.pack_padded_sequence(
src, lengths, batch_first=batch_first, enforce_sorted=not should_shuffle
)
self.assertEqual(packed.data.data, expected_data)
self.assertEqual(packed.batch_sizes, batch_sizes)
self.assertEqual(packed.unsorted_indices, unsorted_indices)
# test inverse
unpacked, unpacked_len = rnn_utils.pad_packed_sequence(
packed, batch_first=batch_first
)
self.assertEqual(unpacked, src)
self.assertEqual(unpacked_len, lengths)
# check grad
if padded.grad is not None:
padded.grad.data.zero_()
grad_output = unpacked.data.clone().normal_()
unpacked.backward(grad_output)
if batch_first:
grad_output.transpose_(0, 1)
for i, l in enumerate(lengths):
self.assertEqual(padded.grad.data[:l, i], grad_output[:l, i])
if l < 10:
self.assertEqual(padded.grad.data[l:, i].abs().sum(), 0)
# test error messages
with self.assertRaisesRegex(
RuntimeError, "You can pass `enforce_sorted=False`"
):
packed = rnn_utils.pack_padded_sequence(torch.randn(3, 3), [1, 3, 2])
with self.assertRaisesRegex(RuntimeError, "empty tensor"):
packed = rnn_utils.pack_padded_sequence(torch.randn(0, 0), [])
with self.assertRaisesRegex(RuntimeError, "empty tensor"):
packed = rnn_utils.pack_padded_sequence(
torch.randn([0, 1, 10]), torch.randn([11, 14, 14, 2]), True
)
def test_empty_packed_sequence(self):
"""
Regression test for https://github.com/pytorch/pytorch/issues/149622
Tests that pad_packed_sequence and unpack_sequence handle empty tensors
without segmentation fault (CVE-2025-2998, CVE-2025-2999)
"""
# Test case 1: pad_packed_sequence with empty tensors
# Previously caused segmentation fault
empty_data = torch.randn(0, 5)
empty_batch_sizes = torch.tensor([], dtype=torch.int64)
empty_packed = rnn_utils.PackedSequence(
empty_data, empty_batch_sizes, None, None
)
# Should not crash - either return empty result or raise informative error
with self.assertRaises(RuntimeError):
rnn_utils.pad_packed_sequence(empty_packed, batch_first=True)
# Test case 2: unpack_sequence with empty tensors
# Previously caused segmentation fault
empty_data = torch.tensor([])
empty_batch_sizes = torch.tensor([], dtype=torch.int64)
packed = rnn_utils.PackedSequence(
data=empty_data, batch_sizes=empty_batch_sizes
)
# Should not crash - either return empty list or raise informative error
with self.assertRaises(RuntimeError):
rnn_utils.unpack_sequence(packed)
if __name__ == "__main__":
run_tests()
| PackedSequenceTest |
python | plotly__plotly.py | plotly/graph_objs/streamtube/_stream.py | {
"start": 233,
"end": 3526
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "streamtube"
_path_str = "streamtube.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set to 50, only the newest
50 points will be displayed on the plot.
The 'maxpoints' property is a number and may be specified as:
- An int or float in the interval [0, 10000]
Returns
-------
int|float
"""
return self["maxpoints"]
@maxpoints.setter
def maxpoints(self, val):
self["maxpoints"] = val
@property
def token(self):
"""
The stream id number links a data trace on a plot with a
stream. See https://chart-studio.plotly.com/settings for more
details.
The 'token' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["token"]
@token.setter
def token(self, val):
self["token"] = val
@property
def _prop_descriptions(self):
return """\
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details.
"""
def __init__(self, arg=None, maxpoints=None, token=None, **kwargs):
"""
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.streamtube.Stream`
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details.
Returns
-------
Stream
"""
super().__init__("stream")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.streamtube.Stream
constructor must be a dict or
an instance of :class:`plotly.graph_objs.streamtube.Stream`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("maxpoints", arg, maxpoints)
self._set_property("token", arg, token)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Stream |
python | neetcode-gh__leetcode | python/0380-insert-delete-getrandom-o1.py | {
"start": 28,
"end": 671
} | class ____:
def __init__(self):
self.dict = {}
self.list = []
def insert(self, val: int) -> bool:
if val in self.dict:
return False
self.dict[val] = len(self.list)
self.list.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.dict:
return False
idx, last_element = self.dict[val], self.list[-1]
self.list[idx], self.dict[last_element] = last_element, idx
self.list.pop()
del self.dict[val]
return True
def getRandom(self) -> int:
return choice(self.list)
| RandomizedSet |
python | scikit-learn__scikit-learn | sklearn/feature_extraction/text.py | {
"start": 31900,
"end": 53193
} | class ____(_VectorizerMixin, BaseEstimator):
r"""Convert a collection of text documents to a matrix of token counts.
This implementation produces a sparse representation of the counts using
scipy.sparse.csr_matrix.
If you do not provide an a-priori dictionary and you do not use an analyzer
that does some kind of feature selection then the number of features will
be equal to the vocabulary size found by analyzing the data.
For an efficiency comparison of the different feature extractors, see
:ref:`sphx_glr_auto_examples_text_plot_hashing_vs_dict_vectorizer.py`.
Read more in the :ref:`User Guide <text_feature_extraction>`.
Parameters
----------
input : {'filename', 'file', 'content'}, default='content'
- If `'filename'`, the sequence passed as an argument to fit is
expected to be a list of filenames that need reading to fetch
the raw content to analyze.
- If `'file'`, the sequence items must have a 'read' method (file-like
object) that is called to fetch the bytes in memory.
- If `'content'`, the input is expected to be a sequence of items that
can be of type string or byte.
encoding : str, default='utf-8'
If bytes or files are given to analyze, this encoding is used to
decode.
decode_error : {'strict', 'ignore', 'replace'}, default='strict'
Instruction on what to do if a byte sequence is given to analyze that
contains characters not of the given `encoding`. By default, it is
'strict', meaning that a UnicodeDecodeError will be raised. Other
values are 'ignore' and 'replace'.
strip_accents : {'ascii', 'unicode'} or callable, default=None
Remove accents and perform other character normalization
during the preprocessing step.
'ascii' is a fast method that only works on characters that have
a direct ASCII mapping.
'unicode' is a slightly slower method that works on any characters.
None (default) means no character normalization is performed.
Both 'ascii' and 'unicode' use NFKD normalization from
:func:`unicodedata.normalize`.
lowercase : bool, default=True
Convert all characters to lowercase before tokenizing.
preprocessor : callable, default=None
Override the preprocessing (strip_accents and lowercase) stage while
preserving the tokenizing and n-grams generation steps.
Only applies if ``analyzer`` is not callable.
tokenizer : callable, default=None
Override the string tokenization step while preserving the
preprocessing and n-grams generation steps.
Only applies if ``analyzer == 'word'``.
stop_words : {'english'}, list, default=None
If 'english', a built-in stop word list for English is used.
There are several known issues with 'english' and you should
consider an alternative (see :ref:`stop_words`).
If a list, that list is assumed to contain stop words, all of which
will be removed from the resulting tokens.
Only applies if ``analyzer == 'word'``.
If None, no stop words will be used. In this case, setting `max_df`
to a higher value, such as in the range (0.7, 1.0), can automatically detect
and filter stop words based on intra corpus document frequency of terms.
token_pattern : str or None, default=r"(?u)\\b\\w\\w+\\b"
Regular expression denoting what constitutes a "token", only used
if ``analyzer == 'word'``. The default regexp select tokens of 2
or more alphanumeric characters (punctuation is completely ignored
and always treated as a token separator).
If there is a capturing group in token_pattern then the
captured group content, not the entire match, becomes the token.
At most one capturing group is permitted.
ngram_range : tuple (min_n, max_n), default=(1, 1)
The lower and upper boundary of the range of n-values for different
word n-grams or char n-grams to be extracted. All values of n such
such that min_n <= n <= max_n will be used. For example an
``ngram_range`` of ``(1, 1)`` means only unigrams, ``(1, 2)`` means
unigrams and bigrams, and ``(2, 2)`` means only bigrams.
Only applies if ``analyzer`` is not callable.
analyzer : {'word', 'char', 'char_wb'} or callable, default='word'
Whether the feature should be made of word n-gram or character
n-grams.
Option 'char_wb' creates character n-grams only from text inside
word boundaries; n-grams at the edges of words are padded with space.
If a callable is passed it is used to extract the sequence of features
out of the raw, unprocessed input.
.. versionchanged:: 0.21
Since v0.21, if ``input`` is ``filename`` or ``file``, the data is
first read from the file and then passed to the given callable
analyzer.
max_df : float in range [0.0, 1.0] or int, default=1.0
When building the vocabulary ignore terms that have a document
frequency strictly higher than the given threshold (corpus-specific
stop words).
If float, the parameter represents a proportion of documents, integer
absolute counts.
This parameter is ignored if vocabulary is not None.
min_df : float in range [0.0, 1.0] or int, default=1
When building the vocabulary ignore terms that have a document
frequency strictly lower than the given threshold. This value is also
called cut-off in the literature.
If float, the parameter represents a proportion of documents, integer
absolute counts.
This parameter is ignored if vocabulary is not None.
max_features : int, default=None
If not None, build a vocabulary that only consider the top
`max_features` ordered by term frequency across the corpus.
Otherwise, all features are used.
This parameter is ignored if vocabulary is not None.
vocabulary : Mapping or iterable, default=None
Either a Mapping (e.g., a dict) where keys are terms and values are
indices in the feature matrix, or an iterable over terms. If not
given, a vocabulary is determined from the input documents. Indices
in the mapping should not be repeated and should not have any gap
between 0 and the largest index.
binary : bool, default=False
If True, all non zero counts are set to 1. This is useful for discrete
probabilistic models that model binary events rather than integer
counts.
dtype : dtype, default=np.int64
Type of the matrix returned by fit_transform() or transform().
Attributes
----------
vocabulary_ : dict
A mapping of terms to feature indices.
fixed_vocabulary_ : bool
True if a fixed vocabulary of term to indices mapping
is provided by the user.
See Also
--------
HashingVectorizer : Convert a collection of text documents to a
matrix of token counts.
TfidfVectorizer : Convert a collection of raw documents to a matrix
of TF-IDF features.
Examples
--------
>>> from sklearn.feature_extraction.text import CountVectorizer
>>> corpus = [
... 'This is the first document.',
... 'This document is the second document.',
... 'And this is the third one.',
... 'Is this the first document?',
... ]
>>> vectorizer = CountVectorizer()
>>> X = vectorizer.fit_transform(corpus)
>>> vectorizer.get_feature_names_out()
array(['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third',
'this'], ...)
>>> print(X.toarray())
[[0 1 1 1 0 0 1 0 1]
[0 2 0 1 0 1 1 0 1]
[1 0 0 1 1 0 1 1 1]
[0 1 1 1 0 0 1 0 1]]
>>> vectorizer2 = CountVectorizer(analyzer='word', ngram_range=(2, 2))
>>> X2 = vectorizer2.fit_transform(corpus)
>>> vectorizer2.get_feature_names_out()
array(['and this', 'document is', 'first document', 'is the', 'is this',
'second document', 'the first', 'the second', 'the third', 'third one',
'this document', 'this is', 'this the'], ...)
>>> print(X2.toarray())
[[0 0 1 1 0 0 1 0 0 0 0 1 0]
[0 1 0 1 0 1 0 1 0 0 1 0 0]
[1 0 0 1 0 0 0 0 1 1 0 1 0]
[0 0 1 0 1 0 1 0 0 0 0 0 1]]
"""
# raw_documents should not be in the routing mechanism. It should have been
# called X in the first place.
__metadata_request__fit = {"raw_documents": metadata_routing.UNUSED}
__metadata_request__transform = {"raw_documents": metadata_routing.UNUSED}
_parameter_constraints: dict = {
"input": [StrOptions({"filename", "file", "content"})],
"encoding": [str],
"decode_error": [StrOptions({"strict", "ignore", "replace"})],
"strip_accents": [StrOptions({"ascii", "unicode"}), None, callable],
"lowercase": ["boolean"],
"preprocessor": [callable, None],
"tokenizer": [callable, None],
"stop_words": [StrOptions({"english"}), list, None],
"token_pattern": [str, None],
"ngram_range": [tuple],
"analyzer": [StrOptions({"word", "char", "char_wb"}), callable],
"max_df": [
Interval(RealNotInt, 0, 1, closed="both"),
Interval(Integral, 1, None, closed="left"),
],
"min_df": [
Interval(RealNotInt, 0, 1, closed="both"),
Interval(Integral, 1, None, closed="left"),
],
"max_features": [Interval(Integral, 1, None, closed="left"), None],
"vocabulary": [Mapping, HasMethods("__iter__"), None],
"binary": ["boolean"],
"dtype": "no_validation", # delegate to numpy
}
def __init__(
self,
*,
input="content",
encoding="utf-8",
decode_error="strict",
strip_accents=None,
lowercase=True,
preprocessor=None,
tokenizer=None,
stop_words=None,
token_pattern=r"(?u)\b\w\w+\b",
ngram_range=(1, 1),
analyzer="word",
max_df=1.0,
min_df=1,
max_features=None,
vocabulary=None,
binary=False,
dtype=np.int64,
):
self.input = input
self.encoding = encoding
self.decode_error = decode_error
self.strip_accents = strip_accents
self.preprocessor = preprocessor
self.tokenizer = tokenizer
self.analyzer = analyzer
self.lowercase = lowercase
self.token_pattern = token_pattern
self.stop_words = stop_words
self.max_df = max_df
self.min_df = min_df
self.max_features = max_features
self.ngram_range = ngram_range
self.vocabulary = vocabulary
self.binary = binary
self.dtype = dtype
def _sort_features(self, X, vocabulary):
"""Sort features by name
Returns a reordered matrix and modifies the vocabulary in place
"""
sorted_features = sorted(vocabulary.items())
map_index = np.empty(len(sorted_features), dtype=X.indices.dtype)
for new_val, (term, old_val) in enumerate(sorted_features):
vocabulary[term] = new_val
map_index[old_val] = new_val
X.indices = map_index.take(X.indices, mode="clip")
return X
def _limit_features(self, X, vocabulary, high=None, low=None, limit=None):
"""Remove too rare or too common features.
Prune features that are non zero in more samples than high or less
documents than low, modifying the vocabulary, and restricting it to
at most the limit most frequent.
This does not prune samples with zero features.
"""
if high is None and low is None and limit is None:
return X, set()
# Calculate a mask based on document frequencies
dfs = _document_frequency(X)
mask = np.ones(len(dfs), dtype=bool)
if high is not None:
mask &= dfs <= high
if low is not None:
mask &= dfs >= low
if limit is not None and mask.sum() > limit:
tfs = np.asarray(X.sum(axis=0)).ravel()
mask_inds = (-tfs[mask]).argsort()[:limit]
new_mask = np.zeros(len(dfs), dtype=bool)
new_mask[np.where(mask)[0][mask_inds]] = True
mask = new_mask
new_indices = np.cumsum(mask) - 1 # maps old indices to new
for term, old_index in list(vocabulary.items()):
if mask[old_index]:
vocabulary[term] = new_indices[old_index]
else:
del vocabulary[term]
kept_indices = np.where(mask)[0]
if len(kept_indices) == 0:
raise ValueError(
"After pruning, no terms remain. Try a lower min_df or a higher max_df."
)
return X[:, kept_indices]
def _count_vocab(self, raw_documents, fixed_vocab):
"""Create sparse feature matrix, and vocabulary where fixed_vocab=False"""
if fixed_vocab:
vocabulary = self.vocabulary_
else:
# Add a new value when a new vocabulary item is seen
vocabulary = defaultdict()
vocabulary.default_factory = vocabulary.__len__
analyze = self.build_analyzer()
j_indices = []
indptr = []
values = _make_int_array()
indptr.append(0)
for doc in raw_documents:
feature_counter = {}
for feature in analyze(doc):
try:
feature_idx = vocabulary[feature]
if feature_idx not in feature_counter:
feature_counter[feature_idx] = 1
else:
feature_counter[feature_idx] += 1
except KeyError:
# Ignore out-of-vocabulary items for fixed_vocab=True
continue
j_indices.extend(feature_counter.keys())
values.extend(feature_counter.values())
indptr.append(len(j_indices))
if not fixed_vocab:
# disable defaultdict behaviour
vocabulary = dict(vocabulary)
if not vocabulary:
raise ValueError(
"empty vocabulary; perhaps the documents only contain stop words"
)
if indptr[-1] > np.iinfo(np.int32).max: # = 2**31 - 1
if _IS_32BIT:
raise ValueError(
(
"sparse CSR array has {} non-zero "
"elements and requires 64 bit indexing, "
"which is unsupported with 32 bit Python."
).format(indptr[-1])
)
indices_dtype = np.int64
else:
indices_dtype = np.int32
j_indices = np.asarray(j_indices, dtype=indices_dtype)
indptr = np.asarray(indptr, dtype=indices_dtype)
values = np.frombuffer(values, dtype=np.intc)
X = sp.csr_matrix(
(values, j_indices, indptr),
shape=(len(indptr) - 1, len(vocabulary)),
dtype=self.dtype,
)
X.sort_indices()
return vocabulary, X
def fit(self, raw_documents, y=None):
"""Learn a vocabulary dictionary of all tokens in the raw documents.
Parameters
----------
raw_documents : iterable
An iterable which generates either str, unicode or file objects.
y : None
This parameter is ignored.
Returns
-------
self : object
Fitted vectorizer.
"""
self.fit_transform(raw_documents)
return self
@_fit_context(prefer_skip_nested_validation=True)
def fit_transform(self, raw_documents, y=None):
"""Learn the vocabulary dictionary and return document-term matrix.
This is equivalent to fit followed by transform, but more efficiently
implemented.
Parameters
----------
raw_documents : iterable
An iterable which generates either str, unicode or file objects.
y : None
This parameter is ignored.
Returns
-------
X : array of shape (n_samples, n_features)
Document-term matrix.
"""
# We intentionally don't call the transform method to make
# fit_transform overridable without unwanted side effects in
# TfidfVectorizer.
if isinstance(raw_documents, str):
raise ValueError(
"Iterable over raw text documents expected, string object received."
)
self._validate_ngram_range()
self._warn_for_unused_params()
self._validate_vocabulary()
max_df = self.max_df
min_df = self.min_df
max_features = self.max_features
if self.fixed_vocabulary_ and self.lowercase:
for term in self.vocabulary:
if any(map(str.isupper, term)):
warnings.warn(
"Upper case characters found in"
" vocabulary while 'lowercase'"
" is True. These entries will not"
" be matched with any documents"
)
break
vocabulary, X = self._count_vocab(raw_documents, self.fixed_vocabulary_)
if self.binary:
X.data.fill(1)
if not self.fixed_vocabulary_:
n_doc = X.shape[0]
max_doc_count = max_df if isinstance(max_df, Integral) else max_df * n_doc
min_doc_count = min_df if isinstance(min_df, Integral) else min_df * n_doc
if max_doc_count < min_doc_count:
raise ValueError("max_df corresponds to < documents than min_df")
if max_features is not None:
X = self._sort_features(X, vocabulary)
X = self._limit_features(
X, vocabulary, max_doc_count, min_doc_count, max_features
)
if max_features is None:
X = self._sort_features(X, vocabulary)
self.vocabulary_ = vocabulary
return X
def transform(self, raw_documents):
"""Transform documents to document-term matrix.
Extract token counts out of raw text documents using the vocabulary
fitted with fit or the one provided to the constructor.
Parameters
----------
raw_documents : iterable
An iterable which generates either str, unicode or file objects.
Returns
-------
X : sparse matrix of shape (n_samples, n_features)
Document-term matrix.
"""
if isinstance(raw_documents, str):
raise ValueError(
"Iterable over raw text documents expected, string object received."
)
self._check_vocabulary()
# use the same matrix-building strategy as fit_transform
_, X = self._count_vocab(raw_documents, fixed_vocab=True)
if self.binary:
X.data.fill(1)
return X
def inverse_transform(self, X):
"""Return terms per document with nonzero entries in X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Document-term matrix.
Returns
-------
X_original : list of arrays of shape (n_samples,)
List of arrays of terms.
"""
self._check_vocabulary()
# We need CSR format for fast row manipulations.
X = check_array(X, accept_sparse="csr")
n_samples = X.shape[0]
terms = np.array(list(self.vocabulary_.keys()))
indices = np.array(list(self.vocabulary_.values()))
inverse_vocabulary = terms[np.argsort(indices)]
if sp.issparse(X):
return [
inverse_vocabulary[X[i, :].nonzero()[1]].ravel()
for i in range(n_samples)
]
else:
return [
inverse_vocabulary[np.flatnonzero(X[i, :])].ravel()
for i in range(n_samples)
]
def get_feature_names_out(self, input_features=None):
"""Get output feature names for transformation.
Parameters
----------
input_features : array-like of str or None, default=None
Not used, present here for API consistency by convention.
Returns
-------
feature_names_out : ndarray of str objects
Transformed feature names.
"""
self._check_vocabulary()
return np.asarray(
[t for t, i in sorted(self.vocabulary_.items(), key=itemgetter(1))],
dtype=object,
)
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.input_tags.string = True
tags.input_tags.two_d_array = False
return tags
def _make_int_array():
"""Construct an array.array of a type suitable for scipy.sparse indices."""
return array.array(str("i"))
| CountVectorizer |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/session.py | {
"start": 776,
"end": 975
} | class ____(Base):
__tablename__ = "user"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
addresses: Mapped[List[Address]] = relationship(back_populates="user")
| User |
python | apache__airflow | providers/snowflake/tests/unit/snowflake/operators/test_snowflake.py | {
"start": 7079,
"end": 9705
} | class ____:
@mock.patch("airflow.providers.common.sql.operators.sql.BaseSQLOperator.__init__")
def test_overwrite_params(
self,
mock_base_op,
operator_class,
kwargs,
):
operator_class(
task_id="snowflake_params_check",
snowflake_conn_id="snowflake_default",
warehouse="test_warehouse",
database="test_database",
role="test_role",
schema="test_schema",
authenticator="oath",
session_parameters={"QUERY_TAG": "test_tag"},
**kwargs,
)
mock_base_op.assert_called_once_with(
conn_id="snowflake_default",
database=None,
task_id="snowflake_params_check",
hook_params={
"warehouse": "test_warehouse",
"database": "test_database",
"role": "test_role",
"schema": "test_schema",
"authenticator": "oath",
"session_parameters": {"QUERY_TAG": "test_tag"},
},
default_args={},
)
def create_context(task, dag=None):
if dag is None:
dag = DAG(dag_id="dag", schedule=None)
tzinfo = pendulum.timezone("UTC")
logical_date = timezone.datetime(2022, 1, 1, 1, 0, 0, tzinfo=tzinfo)
if AIRFLOW_V_3_0_PLUS:
from airflow.models.dag_version import DagVersion
sync_dag_to_db(dag)
dag_version = DagVersion.get_latest_version(dag.dag_id)
task_instance = TaskInstance(task=task, run_id="test_run_id", dag_version_id=dag_version.id)
dag_run = DagRun(
dag_id=dag.dag_id,
logical_date=logical_date,
run_id=DagRun.generate_run_id(
run_type=DagRunType.MANUAL, logical_date=logical_date, run_after=logical_date
),
)
else:
dag_run = DagRun(
dag_id=dag.dag_id,
execution_date=logical_date,
run_id=DagRun.generate_run_id(DagRunType.MANUAL, logical_date),
)
task_instance = TaskInstance(task=task)
task_instance.dag_run = dag_run
task_instance.xcom_push = mock.Mock()
date_key = "logical_date" if AIRFLOW_V_3_0_PLUS else "execution_date"
return {
"dag": dag,
"ts": logical_date.isoformat(),
"task": task,
"ti": task_instance,
"task_instance": task_instance,
"run_id": dag_run.run_id,
"dag_run": dag_run,
"data_interval_end": logical_date,
date_key: logical_date,
}
@pytest.mark.db_test
| TestSnowflakeCheckOperatorsForParams |
python | pennersr__django-allauth | examples/react-spa/backend/backend/drf_demo/serializers.py | {
"start": 41,
"end": 152
} | class ____(serializers.Serializer):
x = serializers.FloatField()
y = serializers.FloatField()
| AddSerializer |
python | kamyu104__LeetCode-Solutions | Python/gcd-sort-of-an-array.py | {
"start": 926,
"end": 1764
} | class ____(object):
def gcdSort(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def modified_sieve_of_eratosthenes(n, lookup, uf): # Time: O(n * log(logn)), Space: O(n)
if n < 2:
return
is_prime = [True]*(n+1)
for i in xrange(2, len(is_prime)):
if not is_prime[i]:
continue
for j in xrange(i+i, len(is_prime), i):
is_prime[j] = False
if j in lookup: # modified
uf.union_set(i-1, j-1)
max_num = max(nums)
uf = UnionFind(max_num)
modified_sieve_of_eratosthenes(max_num, set(nums), uf)
return all(uf.find_set(a-1) == uf.find_set(b-1) for a, b in itertools.izip(nums, sorted(nums)))
| Solution |
python | huggingface__transformers | src/transformers/models/gemma3n/feature_extraction_gemma3n.py | {
"start": 4253,
"end": 14961
} | class ____(SequenceFeatureExtractor):
"""An audio feature extractor Universal Speech Models https://huggingface.co/papers/2303.01037.
Args:
feature_size (`int`, *optional*, defaults to 128):
The feature dimension of the extracted features.
sampling_rate (`int`, *optional*, defaults to 16000):
The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
padding_value (`float`, *optional*, defaults to 0.0):
Padding value used to pad the audio. Should correspond to silences.
return_attention_mask (`bool`, *optional*, defaults to `True`):
Whether to return the attention mask for the generated MEL spectrograms.
frame_length_ms (`float`, *optional*, defaults to 32.0):
The length of a frame in milliseconds.
hop_length_ms (`float`, *optional*, defaults to 10.0):
Length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients.
min_frequency (`float`, *optional*, defaults to 125.0):
The minimum frequency (in Hz) for the Mel filterbank.
max_frequency (`float`, *optional*, defaults to 7600.0):
The maximum frequency (in Hz) for the Mel filterbank.
preemphasis (`float`, *optional*, defaults to 0.97):
The preemphasis coefficient.
preemphasis_htk_flavor (`bool`, *optional*, defaults to `True`):
Whether to use HTK-style preemphasis.
fft_overdrive (`bool`, *optional*, defaults to `True`):
Whether to use FFT overdrive.
dither (`float`, *optional*, defaults to 0.0):
Adds dithering. In other words, adds a small Gaussian noise to each frame.
E.g. use 0.0001 to add dithering with a normal distribution centered
around 0.0 with standard deviation 0.0001 (assuming [-1,+1] range of raw_speech).
The value 0.0 means no dithering.
Dithering has similar effect as `spectrogram(mel_floor=...)`. It reduces
the high log_mel_fbank values for signals with hard-zero sections,
when VAD cutoff is present in the signal.
input_scale_factor (`float`, *optional*, defaults to 1.0):
Scaling factor applied to the input waveform.
mel_floor (`float`, *optional*, defaults to 1e-05):
Minimum value for Mel spectrograms to avoid log(0).
per_bin_mean (`Optional[Sequence[float]]`, *optional*):
Mean values for per-bin normalization.
per_bin_stddev (`Optional[Sequence[float]]`, *optional*):
Standard deviation values for per-bin normalization.
"""
model_input_names = ["input_features", "input_features_mask"]
def __init__(
self,
feature_size: int = 128,
sampling_rate: int = 16_000,
padding_value: float = 0.0,
return_attention_mask: bool = True,
frame_length_ms: float = 32.0,
hop_length_ms: float = 10.0,
min_frequency: float = 125.0,
max_frequency: float = 7600.0,
preemphasis: float = 0.97,
preemphasis_htk_flavor: bool = True,
fft_overdrive: bool = True,
dither: float = 0.0,
input_scale_factor: float = 1.0,
mel_floor: float = 1e-5,
per_bin_mean: Optional[Sequence[float]] = None,
per_bin_stddev: Optional[Sequence[float]] = None,
**kwargs,
):
super().__init__(
feature_size=feature_size,
sampling_rate=sampling_rate,
padding_value=padding_value,
return_attention_mask=return_attention_mask,
**kwargs,
)
self.min_frequency = min_frequency
self.max_frequency = max_frequency
self.preemphasis = preemphasis
self.preemphasis_htk_flavor = preemphasis_htk_flavor
self.fft_overdrive = fft_overdrive
self.dither = dither
self.input_scale_factor = input_scale_factor
self.frame_length = int(round(sampling_rate * frame_length_ms / 1000.0))
self.hop_length = int(round(sampling_rate * hop_length_ms / 1000.0))
self.mel_floor = np.array(mel_floor, dtype=np.float64)
fft_length = 2 ** math.ceil(math.log2(self.frame_length))
if self.fft_overdrive:
fft_length *= 2
self.fft_length = fft_length
hann_arange = np.arange(self.frame_length, dtype=np.float32)
window = 0.5 * (1 - np.cos(2 * np.pi * hann_arange / self.frame_length))
self.window = window.astype(np.float32)
self.mel_filters = create_fb_matrix(
n_freqs=self.fft_length // 2 + 1,
f_min=min_frequency,
f_max=max_frequency,
n_mels=feature_size,
sample_rate=self.sampling_rate,
norm=None,
fft_length=fft_length,
)
if per_bin_mean is not None:
self.per_bin_mean = np.array(per_bin_mean).reshape(1, 1, feature_size)
else:
self.per_bin_mean = None
if per_bin_stddev is not None:
self.per_bin_stddev = np.array(per_bin_stddev).reshape(1, 1, feature_size)
else:
self.per_bin_stddev = None
def _extract_spectrogram(self, waveform: np.ndarray, attention_mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
""""""
if waveform.ndim == 1: # If single waveform, add batch dimension
waveform = np.expand_dims(waveform, axis=0)
if self.dither > 0.0:
waveform = waveform + self.dither * np.random.randn(*waveform.shape).astype(waveform.dtype)
if self.input_scale_factor != 1.0:
waveform = waveform * self.input_scale_factor
frame_size_for_unfold = self.frame_length + 1
# NumPy equivalent of unfold for [B, NumFrames, frame_size_for_unfold]
frames_to_process = _unfold(waveform, dimension=-1, size=frame_size_for_unfold, step=self.hop_length)
if self.preemphasis > 0.0:
if self.preemphasis_htk_flavor:
first_in_frame = frames_to_process[..., :1] * (1.0 - self.preemphasis)
rest_in_frame = frames_to_process[..., 1:-1] - self.preemphasis * frames_to_process[..., :-2]
frames = np.concatenate([first_in_frame, rest_in_frame], axis=-1)
else:
frames = frames_to_process[..., 1:] - self.preemphasis * frames_to_process[..., :-1]
else:
frames = frames_to_process[..., :-1]
frames = frames * self.window # Broadcasting window
stft = np.fft.rfft(frames, n=self.fft_length, axis=-1)
magnitude_spec = np.abs(stft)
mel_spec = np.matmul(magnitude_spec, self.mel_filters)
log_mel_spec = np.log(np.maximum(mel_spec, self.mel_floor))
if self.per_bin_mean is not None:
log_mel_spec = log_mel_spec - self.per_bin_mean # Broadcasting
if self.per_bin_stddev is not None:
log_mel_spec = log_mel_spec / self.per_bin_stddev # Broadcasting
mel_spectrogram = log_mel_spec.squeeze(0)
mask = attention_mask[:: self.hop_length].astype(bool)
# TODO: The filtered mask is always exactly 3 elements longer than the mel_spectrogram. Why???
return mel_spectrogram, mask[: mel_spectrogram.shape[0]]
def __call__(
self,
raw_speech: Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]],
padding: Union[bool, str, PaddingStrategy] = "longest",
max_length: Optional[int] = 480_000,
truncation: bool = True,
pad_to_multiple_of: Optional[int] = 128,
return_tensors: Optional[Union[str, TensorType]] = None,
return_attention_mask: Optional[bool] = True,
**kwargs,
) -> BatchFeature:
"""Creates a batch of MEL spectrograms from the provided raw speech.
This implementation uses a different algorithm for windowing and preemphasis compared to the built-in
`transformers.audio_utils.spectrogram()` function that _will_ result in different outputs. Consider this
carefully when selecting an audio feature extractor, especially with pre-trained models.
Args:
raw_speech:
The audio for which MEL spectrograms are created.
padding (`Union[bool, str, PaddingStrategy]`, *optional*, defaults to `"longest"`):
The padding strategy to use for batches of audio with different lengths.
max_length (`int`, *optional*, defaults to 480000):
If provided, defines the maximum length of the audio to allow. Audio longer than this will be
truncated if `truncation=True`.
truncation (`bool`, *optional*, defaults to `True`):
Whether or not to truncate audio above `max_length`.
pad_to_multiple_of (`int`, *optional*, defaults to 128):
When padding, pad to a multiple of this value. The default value is defined for optimal TPU support.
return_tensors (`Union[str, TensorType]`, *optional*, defaults to `None`):
The type of tensors to return (e.g., NumPy, or Torch).
return_attention_mask (`bool`, *optional*, defaults to `True`):
Whether to return the attention mask for the generated MEL spectrograms.
"""
is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
is_batched_sequence = isinstance(raw_speech, Sequence) and isinstance(raw_speech[0], (np.ndarray, Sequence))
is_batched = is_batched_numpy or is_batched_sequence
# Always return a batch
if not is_batched:
raw_speech = [raw_speech]
raw_speech = [np.asarray([rs]).T for rs in raw_speech]
batched_speech = self.pad(
BatchFeature({"input_features": raw_speech}),
padding=padding,
max_length=max_length,
truncation=truncation,
pad_to_multiple_of=pad_to_multiple_of,
return_attention_mask=return_attention_mask,
)
prepared_speech = []
prepared_speech_mask = []
for speech, mask in zip(batched_speech.input_features, batched_speech.attention_mask):
speech, mask = self._extract_spectrogram(speech.T, mask)
prepared_speech.append(speech.astype(np.float32))
prepared_speech_mask.append(mask)
return BatchFeature(
{"input_features": prepared_speech, "input_features_mask": prepared_speech_mask},
tensor_type=return_tensors,
)
__all__ = ["Gemma3nAudioFeatureExtractor"]
| Gemma3nAudioFeatureExtractor |
python | pyinstaller__pyinstaller | tests/unit/test_modulegraph/test_edge_data.py | {
"start": 147,
"end": 23244
} | class ____ (unittest.TestCase):
if not hasattr(unittest.TestCase, 'assertIsInstance'):
def assertIsInstance(self, value, types):
if not isinstance(value, types):
self.fail("%r is not an instance of %r"%(value, types))
def test_regular_import(self):
root = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'testpkg-edgedata')
mf = modulegraph.ModuleGraph(path=[ root ] + sys.path)
script_name = os.path.join(root, 'script.py')
mf.add_script(script_name)
script_node = mf.find_node(script_name)
self.assertIsInstance(script_node, modulegraph.Script)
node = mf.find_node('toplevel_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=False, fromlist=False))
node = mf.find_node('toplevel_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=False, fromlist=False))
node = mf.find_node('toplevel_class_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=False, fromlist=False))
node = mf.find_node('toplevel_class_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=False, fromlist=False))
node = mf.find_node('toplevel_conditional_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=False, fromlist=False))
node = mf.find_node('toplevel_conditional_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=False, fromlist=False))
node = mf.find_node('toplevel_conditional_import_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=True, fromlist=False))
node = mf.find_node('toplevel_conditional_import_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=True, fromlist=False))
node = mf.find_node('toplevel_conditional_import2_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=True, fromlist=False))
node = mf.find_node('toplevel_conditional_import2_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=True, fromlist=False))
node = mf.find_node('toplevel_import_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=True, fromlist=False))
node = mf.find_node('toplevel_import_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=True, fromlist=False))
node = mf.find_node('toplevel_import2_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=True, fromlist=False))
node = mf.find_node('toplevel_import2_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=True, fromlist=False))
node = mf.find_node('function_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=False, fromlist=False))
node = mf.find_node('function_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=False, fromlist=False))
node = mf.find_node('function_class_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=False, fromlist=False))
node = mf.find_node('function_class_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=False, fromlist=False))
node = mf.find_node('function_conditional_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=False, fromlist=False))
node = mf.find_node('function_conditional_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=False, fromlist=False))
node = mf.find_node('function_conditional_import_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=True, fromlist=False))
node = mf.find_node('function_conditional_import_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=True, fromlist=False))
node = mf.find_node('function_conditional_import2_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=True, fromlist=False))
node = mf.find_node('function_conditional_import2_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=True, fromlist=False))
node = mf.find_node('function_import_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=True, fromlist=False))
node = mf.find_node('function_import_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=True, fromlist=False))
node = mf.find_node('function_import2_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=True, fromlist=False))
node = mf.find_node('function_import2_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=True, fromlist=False))
def test_multi_import(self):
root = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'testpkg-edgedata')
mf = modulegraph.ModuleGraph(path=[ root ] + sys.path)
script_name = os.path.join(root, 'script_multi_import.py')
mf.add_script(script_name)
script_node = mf.find_node(script_name)
self.assertIsInstance(script_node, modulegraph.Script)
# FIXME PyInstaller: original _load_tail returned a MissingModule if
# (_save)_import_module did return None. PyInstaller changed this in
# cae47e4f5b51a94ac3ceb5d093283ba0cc895589 and raises an ImportError.
# Thus the MissingModule node (which was expected to be created when
# scanning the script above) doesn't exist and findNode will return
# None, which makes this test fail.
#node = mf.find_node('os.path')
#ed = mf.edgeData(script_node, node)
#self.assertIsInstance(ed, modulegraph.DependencyInfo)
#self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=True, fromlist=False))
node = mf.find_node('os')
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=False, fromlist=False))
node = mf.find_node('sys')
ed = mf.edgeData(script_node, node)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=False, fromlist=False))
node = mf.find_node('platform')
ed = mf.edgeData(script_node, node)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=False, fromlist=False))
node = mf.find_node('email')
ed = mf.edgeData(script_node, node)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=False, fromlist=False))
def test_from_imports(self):
root = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'testpkg-edgedata')
mf = modulegraph.ModuleGraph(path=[ root ] + sys.path)
script_name = os.path.join(root, 'script_from_import.py')
mf.add_script(script_name)
script_node = mf.find_node(script_name)
self.assertIsInstance(script_node, modulegraph.Script)
node = mf.find_node('pkg.toplevel_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.toplevel_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.toplevel_class_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.toplevel_class_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.toplevel_conditional_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.toplevel_conditional_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.toplevel_conditional_import_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.toplevel_conditional_import_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.toplevel_conditional_import2_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.toplevel_conditional_import2_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=False, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.toplevel_import_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.toplevel_import_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.toplevel_import2_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.toplevel_import2_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=False, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.function_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.function_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.function_class_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.function_class_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.function_conditional_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.function_conditional_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=False, fromlist=True))
node = mf.find_node('pkg.function_conditional_import_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.function_conditional_import_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.function_conditional_import2_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.function_conditional_import2_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=True, function=True, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.function_import_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.function_import_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.function_import2_existing')
self.assertIsInstance(node, modulegraph.SourceModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=True, fromlist=True))
node = mf.find_node('pkg.function_import2_nonexisting')
self.assertIsInstance(node, modulegraph.MissingModule)
ed = mf.edgeData(script_node, node)
self.assertIsInstance(ed, modulegraph.DependencyInfo)
self.assertEqual(ed, modulegraph.DependencyInfo(conditional=False, function=True, tryexcept=True, fromlist=True))
if __name__ == "__main__":
unittest.main()
| TestEdgeData |
python | tensorflow__tensorflow | tensorflow/lite/python/authoring/authoring.py | {
"start": 1922,
"end": 2031
} | class ____(Exception):
"""Raised when an error occurs with TFLite compatibility."""
pass
| CompatibilityError |
python | kamyu104__LeetCode-Solutions | Python/number-of-nodes-in-the-sub-tree-with-the-same-label.py | {
"start": 1644,
"end": 2548
} | class ____(object):
def countSubTrees(self, n, edges, labels):
"""
:type n: int
:type edges: List[List[int]]
:type labels: str
:rtype: List[int]
"""
def dfs(labels, adj, node, parent, result):
count = [0]*26
for child in adj[node]:
if child == parent:
continue
new_count = dfs(labels, adj, child, node, result)
for k in xrange(len(new_count)):
count[k] += new_count[k]
count[ord(labels[node]) - ord('a')] += 1
result[node] = count[ord(labels[node]) - ord('a')]
return count
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
result = [0]*n
dfs(labels, adj, 0, -1, result)
return result
| Solution2 |
python | jmcnamara__XlsxWriter | xlsxwriter/test/contenttypes/test_initialisation.py | {
"start": 307,
"end": 864
} | class ____(unittest.TestCase):
"""
Test initialisation of the ContentTypes class and call a method.
"""
def setUp(self):
self.fh = StringIO()
self.contenttypes = ContentTypes()
self.contenttypes._set_filehandle(self.fh)
def test_xml_declaration(self):
"""Test ContentTypes xml_declaration()"""
self.contenttypes._xml_declaration()
exp = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n"""
got = self.fh.getvalue()
self.assertEqual(exp, got)
| TestInitialisation |
python | pypa__pip | src/pip/_vendor/distlib/resources.py | {
"start": 2035,
"end": 2157
} | class ____(object):
def __init__(self, finder, name):
self.finder = finder
self.name = name
| ResourceBase |
python | encode__django-rest-framework | tests/browsable_api/test_browsable_nested_api.py | {
"start": 264,
"end": 412
} | class ____(serializers.Serializer):
one = serializers.IntegerField(max_value=10)
two = serializers.IntegerField(max_value=10)
| NestedSerializer |
python | django-import-export__django-import-export | tests/core/migrations/0006_auto_20171130_0147.py | {
"start": 43,
"end": 343
} | class ____(migrations.Migration):
dependencies = [
("core", "0005_addparentchild"),
]
operations = [
migrations.AlterField(
model_name="category",
name="name",
field=models.CharField(max_length=100, unique=True),
),
]
| Migration |
python | xlwings__xlwings | xlwings/_xlmac.py | {
"start": 4537,
"end": 10648
} | class ____(base_classes.App):
def __init__(self, spec=None, add_book=None, xl=None, visible=True):
if xl is None:
self._xl = appscript.app(
name=spec or "Microsoft Excel",
newinstance=True,
terms=mac_dict,
hide=not visible,
)
if visible:
self.activate() # Makes it behave like on Windows
elif isinstance(xl, int):
self._xl = appscript.app(pid=xl, terms=mac_dict)
else:
self._xl = xl
@property
def xl(self):
return self._xl
@xl.setter
def xl(self, value):
self._xl = value
@property
def api(self):
return self.xl
@property
def engine(self):
return engine
@property
def path(self):
return hfs_to_posix_path(self.xl.path.get())
@property
def pid(self):
data = (
self.xl.AS_appdata.target()
.addressdesc.coerce(aem.kae.typeKernelProcessID)
.data
)
(pid,) = struct.unpack("i", data)
return pid
@property
def version(self):
return self.xl.version.get()
@property
def selection(self):
sheet = self.books.active.sheets.active
try:
# fails if e.g. chart is selected
return Range(sheet, self.xl.selection.get_address())
except CommandError:
return None
def activate(self, steal_focus=False):
asn = subprocess.check_output(
["lsappinfo", "visibleprocesslist", "-includehidden"]
).decode("utf-8")
frontmost_asn = asn.split(" ")[0]
pid_info_frontmost = subprocess.check_output(
["lsappinfo", "info", "-only", "pid", frontmost_asn]
).decode("utf-8")
pid_frontmost = int(pid_info_frontmost.split("=")[1])
try:
appscript.app("System Events").processes[
its.unix_id == self.pid
].frontmost.set(True)
if not steal_focus:
appscript.app("System Events").processes[
its.unix_id == pid_frontmost
].frontmost.set(True)
except CommandError:
pass # may require root privileges (GH 1966)
@property
def visible(self):
try:
return (
appscript.app("System Events")
.processes[its.unix_id == self.pid]
.visible.get()[0]
)
except CommandError:
return None # may require root privileges (GH 1966)
@visible.setter
def visible(self, visible):
try:
appscript.app("System Events").processes[
its.unix_id == self.pid
].visible.set(visible)
except CommandError:
pass # may require root privileges (GH 1966)
def quit(self):
self.xl.quit(saving=kw.no)
def kill(self):
psutil.Process(self.pid).kill()
@property
def screen_updating(self):
return self.xl.screen_updating.get()
@screen_updating.setter
def screen_updating(self, value):
self.xl.screen_updating.set(value)
@property
def display_alerts(self):
return self.xl.display_alerts.get()
@display_alerts.setter
def display_alerts(self, value):
self.xl.display_alerts.set(value)
@property
def enable_events(self):
return self.xl.enable_events.get()
@enable_events.setter
def enable_events(self, value):
self.xl.enable_events.set(value)
@property
def interactive(self):
# TODO: replace with specific error when Exceptions are refactored
raise xlwings.XlwingsError(
"Getting or setting 'app.interactive' isn't supported on macOS."
)
@interactive.setter
def interactive(self, value):
# TODO: replace with specific error when Exceptions are refactored
raise xlwings.XlwingsError(
"Getting or setting 'app.interactive' isn't supported on macOS."
)
@property
def startup_path(self):
return hfs_to_posix_path(self.xl.startup_path.get())
@property
def calculation(self):
return calculation_k2s[self.xl.calculation.get()]
@calculation.setter
def calculation(self, value):
self.xl.calculation.set(calculation_s2k[value])
def calculate(self):
self.xl.calculate()
@property
def books(self):
return Books(self)
@property
def hwnd(self):
return None
def run(self, macro, args):
kwargs = {"arg{0}".format(i): n for i, n in enumerate(args, 1)}
return self.xl.run_VB_macro(macro, **kwargs)
@property
def status_bar(self):
return self.xl.status_bar.get()
@status_bar.setter
def status_bar(self, value):
self.xl.status_bar.set(value)
@property
def cut_copy_mode(self):
modes = {kw.cut_mode: "cut", kw.copy_mode: "copy"}
return modes.get(self.xl.cut_copy_mode.get())
@cut_copy_mode.setter
def cut_copy_mode(self, value):
self.xl.cut_copy_mode.set(value)
def alert(self, prompt, title, buttons, mode, callback):
# OSAX (Open Scripting Architecture Extension) instance for StandardAdditions
# See /System/Library/ScriptingAdditions/StandardAdditions.osax
sa = osax.OSAX(pid=self.pid)
sa.activate() # Activate app so dialog box will be visible
modes = {
None: kw.informational,
"info": kw.informational,
"critical": kw.critical,
}
buttons_dict = {
None: "OK",
"ok": "OK",
"ok_cancel": ["Cancel", "OK"],
"yes_no": ["No", "Yes"],
"yes_no_cancel": ["Cancel", "No", "Yes"],
}
rv = sa.display_alert(
"" if title is None else title,
message="" if prompt is None else prompt,
buttons=buttons_dict[buttons],
as_=modes[mode],
)
return rv[kw.button_returned].lower()
| App |
python | Pylons__pyramid | docs/quick_tutorial/more_view_classes/tutorial/views.py | {
"start": 105,
"end": 1202
} | class ____:
def __init__(self, request):
self.request = request
self.view_name = 'TutorialViews'
@property
def full_name(self):
first = self.request.matchdict['first']
last = self.request.matchdict['last']
return first + ' ' + last
@view_config(route_name='home', renderer='home.pt')
def home(self):
return {'page_title': 'Home View'}
# Retrieving /howdy/first/last the first time
@view_config(renderer='hello.pt')
def hello(self):
return {'page_title': 'Hello View'}
# Posting to /howdy/first/last via the "Edit" submit button
@view_config(request_method='POST', renderer='edit.pt')
def edit(self):
new_name = self.request.params['new_name']
return {'page_title': 'Edit View', 'new_name': new_name}
# Posting to /howdy/first/last via the "Delete" submit button
@view_config(request_method='POST', request_param='form.delete',
renderer='delete.pt')
def delete(self):
print ('Deleted')
return {'page_title': 'Delete View'}
| TutorialViews |
python | bokeh__bokeh | src/bokeh/models/css.py | {
"start": 2449,
"end": 3128
} | class ____(StyleSheet):
""" Imported stylesheet equivalent to ``<link rel="stylesheet" href="${url}">``.
.. note::
Depending on the context, this stylesheet will be appended either to
the parent shadow root, if used in a component, or otherwise to
the ``<head>`` element. If you want to append globally regardless of
the context, use ``GlobalImportedStyleSheet`` instead.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
url = Required(String, help="""
The location of an external stylesheet.
""")
| ImportedStyleSheet |
python | ApeWorX__ape | src/ape/types/coverage.py | {
"start": 2193,
"end": 3399
} | class ____(BaseModel):
"""
An item that can get hit during coverage. Examples of coverage items are
line segments, which are generally calculated from groupings of AST nodes
occupying the same location, that can be tracked by their PC values. During
a transaction's trace, we find these values and we find the corresponding
coverage item and increment the hit count. Another example of a coverage item
is a compiler-builtin check, also marked by a PC value. If we encounter such
PC in a trace, its hit count is incremented. Builtin compiler checks may or
may not correspond to an actual location in the source code, depending on the
type of check.
"""
location: Optional[SourceLocation] = None
"""
The location of the item (line, column, endline, endcolumn).
If multiple PCs share an exact location, it is only tracked as one.
"""
pcs: set[int]
"""
The PCs for this node.
"""
hit_count: NonNegativeInt = 0
"""
The times this node was hit.
"""
tag: Optional[str] = None
"""
An additional tag to mark this statement with.
This is useful if the location field is empty.
"""
| CoverageStatement |
python | django-extensions__django-extensions | tests/management/commands/test_show_urls.py | {
"start": 628,
"end": 1972
} | class ____(TestCase):
"""Tests if show_urls command raises exceptions."""
def test_should_raise_CommandError_when_format_style_does_not_exists(self):
with self.assertRaisesRegex(
CommandError,
"Format style 'invalid_format' does not exist. Options: aligned, dense, json, pretty-json, table, verbose",
):
call_command("show_urls", "--format=invalid_format")
def test_should_raise_CommandError_when_doesnt_have_urlconf_attr(self):
with self.assertRaisesRegex(
CommandError,
'Settings module <Settings "tests.testapp.settings"> does not have the attribute INVALID_URLCONF.',
):
call_command("show_urls", "--urlconf=INVALID_URLCONF")
@override_settings(INVALID_URLCONF="")
def test_should_raise_CommandError_when_doesnt_have_urlconf_attr_print_exc(self):
m_traceback = Mock()
with self.assertRaisesRegex(
CommandError, "Error occurred while trying to load : Empty module name"
):
with patch.dict("sys.modules", traceback=m_traceback):
call_command("show_urls", "--urlconf=INVALID_URLCONF", "--traceback")
self.assertTrue(m_traceback.print_exc.called)
@override_settings(ROOT_URLCONF="tests.management.commands.test_show_urls")
| ShowUrlsExceptionsTests |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/forms.py | {
"start": 1902,
"end": 2162
} | class ____(ReprForm):
def __init__(self, field_count=5, **kwargs):
super().__init__(**kwargs)
for i in range(field_count):
field_name = f"field-{i}"
self.fields[field_name] = forms.CharField(required=False)
| DynamicForm |
python | facebook__pyre-check | tools/upgrade/commands/tests/configurationless_test.py | {
"start": 500,
"end": 8849
} | class ____(TestCase):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.configurationless = Configurationless(
repository=Repository(),
path=Path("."),
includes=["**.py"],
commit=False,
force_remigrate=False,
)
@classmethod
def get_configuration(
cls,
path: Path,
*,
strict: Optional[bool] = True,
targets: Optional[List[str]] = None,
source_directories: Optional[List[str]] = None,
ignore_all_errors: Optional[List[str]] = None,
exclude: Optional[List[str]] = None,
) -> Configuration:
if targets is not None:
sources = {"targets": targets}
elif source_directories is not None:
sources = {"source_directories": source_directories}
else:
print(f"{targets} {source_directories}\n: {locals()}")
raise ValueError("source_directories and targets can't both be None")
configuration_json = {
"strict": strict,
**sources,
"version": "abcdef12345",
"ignore_all_errors": ignore_all_errors or [],
"exclude": exclude or [],
}
return Configuration(path, configuration_json)
@classmethod
def get_options(
cls,
*,
global_configuration: Optional[Configuration] = None,
local_configuration: Optional[Configuration] = None,
ignore_all_errors_prefixes: Optional[Iterable[str]] = None,
exclude_patterns: Optional[Iterable[str]] = None,
) -> ConfigurationlessOptions:
if global_configuration is None:
global_configuration = cls.get_configuration(
Path("../.pyre_configuration"),
source_directories=["."],
ignore_all_errors=None,
exclude=None,
)
if local_configuration is None:
local_configuration = cls.get_configuration(
Path(".pyre_configuration.local"),
targets=["//path/to/my:target"],
ignore_all_errors=(
list(ignore_all_errors_prefixes)
if ignore_all_errors_prefixes is not None
else None
),
exclude=(
list(exclude_patterns) if exclude_patterns is not None else None
),
)
return ConfigurationlessOptions(
global_configuration=global_configuration,
local_configuration=local_configuration,
)
def test_get_default_global_mode_no_configuration(self) -> None:
global_configuration = self.get_configuration(
Path("../.pyre_configuration.json"),
source_directories=["."],
strict=None,
)
options = self.get_options(global_configuration=global_configuration)
self.assertEqual(
options.default_global_mode,
LocalMode.UNSAFE,
)
def test_get_default_global_mode_strict_configuration(self) -> None:
options = self.get_options()
self.assertEqual(
options.default_global_mode,
LocalMode.STRICT,
)
def test_get_default_global_mode_unsafe_configuration(self) -> None:
global_configuration = self.get_configuration(
Path("../.pyre_configuration.json"), source_directories=["."], strict=False
)
options = self.get_options(global_configuration=global_configuration)
self.assertEqual(
options.default_global_mode,
LocalMode.UNSAFE,
)
def test_get_default_mode_local_strict(self) -> None:
global_configuration = self.get_configuration(
Path("../.pyre_configuration.json"), source_directories=["."], strict=False
)
local_configuration = self.get_configuration(
Path("./local_configuration.json"), targets=["..."]
)
options = self.get_options(
local_configuration=local_configuration,
global_configuration=global_configuration,
)
self.assertEqual(
options.default_local_mode,
LocalMode.STRICT,
)
def test_get_default_mode_local_empty_global_strict(self) -> None:
local_configuration = self.get_configuration(
Path("./local_configuration.json"), targets=["..."], strict=None
)
options = self.get_options(local_configuration=local_configuration)
self.assertEqual(
options.default_local_mode,
LocalMode.STRICT,
)
def test_get_default_mode_local_empty_global_unsafe(self) -> None:
global_configuration = self.get_configuration(
Path("../.pyre_configuration.json"), source_directories=["."], strict=False
)
local_configuration = self.get_configuration(
Path("./local_configuration.json"), targets=["..."], strict=None
)
options = self.get_options(
global_configuration=global_configuration,
local_configuration=local_configuration,
)
self.assertEqual(
options.default_local_mode,
LocalMode.UNSAFE,
)
def test_get_default_mode_local_unsafe_global_strict(self) -> None:
local_configuration = self.get_configuration(
Path("./local_configuration.json"), targets=["..."], strict=False
)
options = self.get_options(local_configuration=local_configuration)
self.assertEqual(
options.default_local_mode,
LocalMode.UNSAFE,
)
def test_get_mode_to_apply_file_in_ignore(self) -> None:
options = self.get_options(
ignore_all_errors_prefixes=["path/to/ignore"],
exclude_patterns=[r".*/exclude/.*"],
)
self.assertEqual(
options.get_file_mode_to_apply(
Path("path/to/ignore/file.py"),
),
LocalMode.IGNORE,
)
def test_get_file_mode_to_apply_file_in_ignore_root_path(self) -> None:
options = self.get_options(ignore_all_errors_prefixes=["//path/to/ignore"])
with mock.patch.object(
Configuration,
"find_project_configuration",
return_value=options.global_configuration.get_path(),
):
self.assertEqual(
options.get_file_mode_to_apply(
Path("path/to/ignore/file.py").resolve(),
),
LocalMode.STRICT,
)
self.assertEqual(
options.get_file_mode_to_apply(
Path("../path/to/ignore/file.py").resolve(),
),
LocalMode.IGNORE,
)
def test_get_mode_to_apply_file_project_mode_same_as_global(self) -> None:
options = self.get_options()
self.assertEqual(
options.get_file_mode_to_apply(
Path("path/to/file.py"),
),
LocalMode.STRICT,
)
def test_get_mode_to_apply_file_project_mode_local_unsafe(self) -> None:
local_configuration = self.get_configuration(
Path("../.pyre_configuration.json"), source_directories=["."], strict=False
)
options = self.get_options(local_configuration=local_configuration)
self.assertEqual(
options.get_file_mode_to_apply(
Path("path/to/file.py"),
),
LocalMode.UNSAFE,
)
def test_get_mode_to_apply_file_project_mode_local_strict(self) -> None:
global_configuration = self.get_configuration(
Path(".pyre_configuration.json"),
source_directories=["."],
strict=False,
)
local_configuration = self.get_configuration(
Path("../.pyre_configuration.json"), source_directories=["."], strict=True
)
options = self.get_options(
global_configuration=global_configuration,
local_configuration=local_configuration,
)
self.assertEqual(
options.get_file_mode_to_apply(Path("path/to/file.py")),
LocalMode.STRICT,
)
| TestConfigurationless |
python | coleifer__peewee | tests/apsw_ext.py | {
"start": 363,
"end": 545
} | class ____(object):
def Create(self, db, modulename, dbname, tablename, *args):
schema = 'CREATE TABLE x(value)'
return schema, VTable()
Connect = Create
| VTSource |
python | numba__numba | numba/tests/test_listobject.py | {
"start": 982,
"end": 1914
} | class ____(MemoryLeakMixin, TestCase):
"""Test list creation, append and len. """
def test_list_create(self):
@njit
def foo(n):
l = listobject.new_list(int32)
for i in range(n):
l.append(i)
return len(l)
for i in (0, 1, 2, 100):
self.assertEqual(foo(i), i)
def test_list_create_no_jit(self):
with override_config('DISABLE_JIT', True):
with forbid_codegen():
l = listobject.new_list(int32)
self.assertEqual(type(l), list)
def test_nonempty_list_create_no_jit(self):
# See Issue #6001: https://github.com/numba/numba/issues/6001
with override_config('DISABLE_JIT', True):
with forbid_codegen():
l = List([1, 2, 3])
self.assertEqual(type(l), list)
self.assertEqual(l, [1, 2, 3])
| TestCreateAppendLength |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.