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 | pola-rs__polars | py-polars/src/polars/catalog/unity/models.py | {
"start": 1099,
"end": 2305
} | class ____:
"""Information for a catalog table."""
name: str
comment: str | None
table_id: str
table_type: TableType
storage_location: str | None
data_source_format: DataSourceFormat | None
columns: list[ColumnInfo] | None
properties: dict[str, str]
created_at: datetime | None
created_by: str | None
updated_at: datetime | None
updated_by: str | None
def get_polars_schema(self) -> Schema | None:
"""
Get the native polars schema of this table.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
"""
issue_unstable_warning(
"`get_polars_schema` functionality is considered unstable."
)
if self.columns is None:
return None
schema = Schema()
for column_info in self.columns:
if column_info.name in schema:
msg = f"duplicate column name: {column_info.name}"
raise DuplicateError(msg)
schema[column_info.name] = column_info.get_polars_dtype()
return schema
@dataclass
| TableInfo |
python | huggingface__transformers | src/transformers/models/speecht5/modeling_speecht5.py | {
"start": 60336,
"end": 68536
} | class ____(SpeechT5PreTrainedModel):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`SpeechT5DecoderLayer`]
"""
def __init__(self, config: SpeechT5Config):
super().__init__(config)
self.layerdrop = config.decoder_layerdrop
self.layers = nn.ModuleList([SpeechT5DecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)])
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
def forward(
self,
hidden_states: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.Tensor] = None,
) -> Union[tuple, BaseModelOutputWithPastAndCrossAttentions]:
r"""
Args:
hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, feature_size)`):
Features extracted from the speech or text input by the decoder prenet.
attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
of the decoder.
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
than the model's internal embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
input_shape = hidden_states.size()[:-1]
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warning_once(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
)
use_cache = False
if use_cache and past_key_values is None:
past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
attention_mask = _prepare_4d_causal_attention_mask(
attention_mask, input_shape, hidden_states, past_key_values_length
)
# expand encoder attention mask
if encoder_hidden_states is not None and encoder_attention_mask is not None:
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
encoder_attention_mask = _prepare_4d_attention_mask(
encoder_attention_mask, hidden_states.dtype, tgt_len=input_shape[-1]
)
synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
# decoder layers
all_hidden_states = () if output_hidden_states else None
all_self_attentions = () if output_attentions else None
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
for idx, decoder_layer in enumerate(self.layers):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
skip_the_layer = False
if self.training:
dropout_probability = torch.rand([])
skip_the_layer = dropout_probability < self.layerdrop
if skip_the_layer and not synced_gpus:
continue
layer_outputs = decoder_layer(
hidden_states,
attention_mask,
encoder_hidden_states, # as a positional argument for gradient checkpointing
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
output_attentions=output_attentions,
use_cache=use_cache,
cache_position=cache_position,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_self_attentions = all_self_attentions + (layer_outputs[1],)
if encoder_hidden_states is not None:
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(
v
for v in [hidden_states, past_key_values, all_hidden_states, all_self_attentions, all_cross_attentions]
if v is not None
)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
cross_attentions=all_cross_attentions,
)
| SpeechT5Decoder |
python | ethereum__web3.py | ens/exceptions.py | {
"start": 14,
"end": 97
} | class ____(Exception):
"""
Base class for all ENS Errors
"""
| ENSException |
python | huggingface__transformers | src/transformers/models/layoutlm/modeling_layoutlm.py | {
"start": 5766,
"end": 8243
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
self.config = config
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.attention_dropout = config.attention_probs_dropout_prob
self.scaling = self.attention_head_size**-0.5
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = False,
**kwargs,
) -> tuple[torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.attention_head_size)
query_states = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
key_states = self.key(hidden_states).view(hidden_shape).transpose(1, 2)
value_states = self.value(hidden_states).view(hidden_shape).transpose(1, 2)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
return outputs
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->LayoutLM
| LayoutLMSelfAttention |
python | fastai__fastai | fastai/torch_core.py | {
"start": 19056,
"end": 19285
} | class ____(TensorBase):
_show_args = ArrayImageBase._show_args
def show(self, ctx=None, **kwargs):
return show_image(self, ctx=ctx, **{**self._show_args, **kwargs})
# %% ../nbs/00_torch_core.ipynb 107
| TensorImageBase |
python | keras-team__keras | keras/src/ops/core.py | {
"start": 14445,
"end": 16457
} | class ____(Operation):
def __init__(self, shape, *, name=None):
super().__init__(name=name)
self.shape = shape
def call(self, inputs, start_indices):
return backend.core.slice(inputs, start_indices, self.shape)
def compute_output_spec(self, inputs, start_indices):
if any(s == -1 for s in self.shape) and isinstance(
start_indices, KerasTensor
):
raise ValueError(
"When using -1 in `shape`, `start_indices` should not be a "
"KerasTensor. "
)
# If self.shape[i] is -1, all remaining elements in dimension i are
# included in the slice.
final_shape = tuple(
inputs.shape[i] - start_indices[i] if s == -1 else s
for i, s in enumerate(self.shape)
)
return KerasTensor(final_shape, dtype=inputs.dtype)
@keras_export("keras.ops.slice")
def slice(inputs, start_indices, shape):
"""Return a slice of an input tensor.
At a high level, this operation is an explicit replacement for array slicing
e.g. `inputs[start_indices: start_indices + shape]`.
Unlike slicing via brackets, this operation will accept tensor start
indices on all backends, which is useful when indices dynamically computed
via other tensor operations.
```python
inputs = np.zeros((5, 5))
start_indices = np.array([3, 3])
shape = np.array([2, 2])
inputs = keras.ops.slice(inputs, start_indices, shape)
```
Args:
inputs: A tensor, the tensor to be updated.
start_indices: A list/tuple of shape `(inputs.ndim,)`, specifying
the starting indices for updating.
shape: The full shape of the returned slice.
Returns:
A tensor, has the same shape and dtype as `inputs`.
"""
if any_symbolic_tensors((inputs, start_indices)):
return Slice(shape=shape).symbolic_call(inputs, start_indices)
return backend.core.slice(inputs, start_indices, shape)
| Slice |
python | django-guardian__django-guardian | guardian/testapp/tests/test_indexes.py | {
"start": 7292,
"end": 10402
} | class ____(TestCase):
"""Test performance improvements from indexes."""
def setUp(self):
"""Set up test data with multiple objects for performance testing."""
self.users = [User.objects.create_user(username=f"user{i}", email=f"user{i}@example.com") for i in range(10)]
self.groups = [Group.objects.create(name=f"group{i}") for i in range(5)]
self.projects = [Project.objects.create(name=f"Project {i}") for i in range(20)]
self.content_type = ContentType.objects.get_for_model(Project)
self.permission = Permission.objects.get(content_type=self.content_type, codename="add_project")
# Create multiple permissions for performance testing
for user in self.users:
for project in self.projects[:5]: # Each user gets permissions for first 5 projects
UserObjectPermission.objects.create(
user=user, permission=self.permission, content_type=self.content_type, object_pk=str(project.pk)
)
for group in self.groups:
for project in self.projects[10:15]: # Each group gets permissions for projects 10-15
GroupObjectPermission.objects.create(
group=group, permission=self.permission, content_type=self.content_type, object_pk=str(project.pk)
)
def test_user_permission_lookup_performance(self):
"""Test that user permission lookups are efficient with indexes."""
user = self.users[0]
project = self.projects[0]
# This query should be fast due to the index on (user, content_type, object_pk)
with self.assertNumQueries(1):
permissions = list(
UserObjectPermission.objects.filter(
user=user, content_type=self.content_type, object_pk=str(project.pk)
)
)
self.assertEqual(len(permissions), 1)
def test_group_permission_lookup_performance(self):
"""Test that group permission lookups are efficient with indexes."""
group = self.groups[0]
project = self.projects[10]
# This query should be fast due to the index on (group, content_type, object_pk)
with self.assertNumQueries(1):
permissions = list(
GroupObjectPermission.objects.filter(
group=group, content_type=self.content_type, object_pk=str(project.pk)
)
)
self.assertEqual(len(permissions), 1)
def test_specific_permission_lookup_performance(self):
"""Test that specific permission lookups are efficient with indexes."""
user = self.users[0]
project = self.projects[0]
# This query should be fast due to the index on (permission, user, content_type, object_pk)
with self.assertNumQueries(1):
exists = UserObjectPermission.objects.filter(
permission=self.permission, user=user, content_type=self.content_type, object_pk=str(project.pk)
).exists()
self.assertTrue(exists)
| IndexPerformanceTestCase |
python | pytorch__pytorch | torchgen/model.py | {
"start": 86122,
"end": 86378
} | class ____:
dtype: Argument
layout: Argument
device: Argument
pin_memory: Argument
def all(self) -> Sequence[Argument]:
return [self.dtype, self.layout, self.device, self.pin_memory]
@dataclass(frozen=True)
| TensorOptionsArguments |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_embedding_v3.py | {
"start": 3558,
"end": 3951
} | class ____:
"""Config for sparsecore embedding."""
disable_table_stacking: bool = False
max_ids_per_chip_per_sample: int = 64
max_ids_per_table: Optional[Dict[str, int]] = None
max_unique_ids_per_table: Optional[Dict[str, int]] = None
allow_id_dropping: bool = False
initialize_tables_on_host: bool = True
enable_fast_table_initialization: bool = False
| SparseCoreEmbeddingConfig |
python | numba__numba | numba/tests/test_parfors.py | {
"start": 156122,
"end": 163721
} | class ____(TestPrangeBase):
# env mutating test
_numba_parallel_test_ = False
def get_gufunc_asm(self, func, schedule_type, *args, **kwargs):
fastmath = kwargs.pop('fastmath', False)
cpu_name = kwargs.pop('cpu_name', 'skylake-avx512')
assertions = kwargs.pop('assertions', True)
# force LLVM to use zmm registers for vectorization
# https://reviews.llvm.org/D67259
cpu_features = kwargs.pop('cpu_features', '-prefer-256-bit')
env_opts = {'NUMBA_CPU_NAME': cpu_name,
'NUMBA_CPU_FEATURES': cpu_features,
}
overrides = []
for k, v in env_opts.items():
overrides.append(override_env_config(k, v))
with overrides[0], overrides[1]:
sig = tuple([numba.typeof(x) for x in args])
pfunc_vectorizable = self.generate_prange_func(func, None)
if fastmath == True:
cres = self.compile_parallel_fastmath(pfunc_vectorizable, sig)
else:
cres = self.compile_parallel(pfunc_vectorizable, sig)
# get the gufunc asm
asm = self._get_gufunc_asm(cres)
if assertions:
schedty = re.compile(r'call\s+\w+\*\s+@do_scheduling_(\w+)\(')
matches = schedty.findall(cres.library.get_llvm_str())
self.assertGreaterEqual(len(matches), 1) # at least 1 parfor call
self.assertEqual(matches[0], schedule_type)
self.assertNotEqual(asm, {})
return asm
@linux_only
@TestCase.run_test_in_subprocess
def test_vectorizer_fastmath_asm(self):
""" This checks that if fastmath is set and the underlying hardware
is suitable, and the function supplied is amenable to fastmath based
vectorization, that the vectorizer actually runs.
"""
# This function will benefit from `fastmath` if run on a suitable
# target. The vectorizer should unwind the loop and generate
# packed dtype=double add and sqrt instructions.
def will_vectorize(A):
n = len(A)
acc = 0
for i in range(n):
acc += np.sqrt(i)
return acc
arg = np.zeros(10)
fast_asm = self.get_gufunc_asm(will_vectorize, 'unsigned', arg,
fastmath=True)
slow_asm = self.get_gufunc_asm(will_vectorize, 'unsigned', arg,
fastmath=False)
for v in fast_asm.values():
# should unwind and call vector sqrt then vector add
# all on packed doubles using zmm's
self.assertTrue('vaddpd' in v)
self.assertTrue('vsqrtpd' in v or '__svml_sqrt' in v)
self.assertTrue('zmm' in v)
for v in slow_asm.values():
# vector variants should not be present
self.assertTrue('vaddpd' not in v)
self.assertTrue('vsqrtpd' not in v)
# check scalar variant is present
self.assertTrue('vsqrtsd' in v and '__svml_sqrt' not in v)
self.assertTrue('vaddsd' in v)
# check no zmm addressing is present
self.assertTrue('zmm' not in v)
@linux_only
@TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '0'})
def test_unsigned_refusal_to_vectorize(self):
""" This checks that if fastmath is set and the underlying hardware
is suitable, and the function supplied is amenable to fastmath based
vectorization, that the vectorizer actually runs.
"""
def will_not_vectorize(A):
n = len(A)
for i in range(-n, 0):
A[i] = np.sqrt(A[i])
return A
def will_vectorize(A):
n = len(A)
for i in range(n):
A[i] = np.sqrt(A[i])
return A
arg = np.zeros(10)
# Boundschecking breaks vectorization
self.assertFalse(config.BOUNDSCHECK)
novec_asm = self.get_gufunc_asm(will_not_vectorize, 'signed', arg,
fastmath=True)
vec_asm = self.get_gufunc_asm(will_vectorize, 'unsigned', arg,
fastmath=True)
for v in novec_asm.values():
# vector variant should not be present
self.assertTrue('vsqrtpd' not in v)
# check scalar variant is present
self.assertTrue('vsqrtsd' in v)
# check no zmm addressing is present
self.assertTrue('zmm' not in v)
for v in vec_asm.values():
# should unwind and call vector sqrt then vector mov
# all on packed doubles using zmm's
self.assertTrue('vsqrtpd' in v or '__svml_sqrt' in v)
self.assertTrue('vmovupd' in v)
self.assertTrue('zmm' in v)
@linux_only
# needed as 32bit doesn't have equivalent signed/unsigned instruction
# generation for this function
@TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '0'})
def test_signed_vs_unsigned_vec_asm(self):
""" This checks vectorization for signed vs unsigned variants of a
trivial accumulator, the only meaningful difference should be the
presence of signed vs. unsigned unpack instructions (for the
induction var).
"""
def signed_variant():
n = 4096
A = 0.
for i in range(-n, 0):
A += i
return A
def unsigned_variant():
n = 4096
A = 0.
for i in range(n):
A += i
return A
# Boundschecking breaks the diff check below because of the pickled exception
self.assertFalse(config.BOUNDSCHECK)
signed_asm = self.get_gufunc_asm(signed_variant, 'signed',
fastmath=True)
unsigned_asm = self.get_gufunc_asm(unsigned_variant, 'unsigned',
fastmath=True)
def strip_instrs(asm):
acc = []
for x in asm.splitlines():
spd = x.strip()
# filter out anything that isn't a trivial instruction
# and anything with the gufunc id as it contains an address
if spd != '' and not (spd.startswith('.')
or spd.startswith('_')
or spd.startswith('"')
or '__numba_parfor_gufunc' in spd):
acc.append(re.sub('[\t]', '', spd))
return acc
for k, v in signed_asm.items():
signed_instr = strip_instrs(v)
break
for k, v in unsigned_asm.items():
unsigned_instr = strip_instrs(v)
break
from difflib import SequenceMatcher as sm
# make sure that the only difference in instruction (if there is a
# difference) is the char 'u'. For example:
# vcvtsi2sdq vs. vcvtusi2sdq
self.assertEqual(len(signed_instr), len(unsigned_instr))
for a, b in zip(signed_instr, unsigned_instr):
if a == b:
continue
else:
s = sm(lambda x: x == '\t', a, b)
ops = s.get_opcodes()
for op in ops:
if op[0] == 'insert':
self.assertEqual(b[op[-2]:op[-1]], 'u')
@skip_parfors_unsupported
| TestParforsVectorizer |
python | django-import-export__django-import-export | import_export/widgets.py | {
"start": 2024,
"end": 3658
} | class ____:
"""
A Widget handles converting between import and export representations.
"""
def __init__(self, coerce_to_string=True):
"""
:param coerce_to_string: If True, :meth:`~import_export.widgets.Widget.render`
will return a string representation of the value, otherwise the value is
returned.
"""
self.coerce_to_string = coerce_to_string
def clean(self, value, row=None, **kwargs):
"""
Returns an appropriate python object for an imported value.
For example, a date string will be converted to a python datetime instance.
:param value: The value to be converted to a native type.
:param row: A dict containing row key/value pairs.
:param **kwargs: Optional kwargs.
"""
return value
def render(self, value, obj=None, **kwargs):
"""
Returns an export representation of a python value.
:param value: The python value to be rendered.
:param obj: The model instance from which the value is taken.
This parameter is deprecated and will be removed in a future release.
:return: By default, this value will be a string, with ``None`` values returned
as empty strings.
"""
return force_str(value) if value is not None else ""
def _obj_deprecation_warning(self, obj):
if obj is not None:
warn(
"The 'obj' parameter is deprecated and will be removed "
"in a future release",
DeprecationWarning,
stacklevel=2,
)
| Widget |
python | numpy__numpy | numpy/polynomial/tests/test_polyutils.py | {
"start": 2058,
"end": 3759
} | class ____:
def test_getdomain(self):
# test for real values
x = [1, 10, 3, -1]
tgt = [-1, 10]
res = pu.getdomain(x)
assert_almost_equal(res, tgt)
# test for complex values
x = [1 + 1j, 1 - 1j, 0, 2]
tgt = [-1j, 2 + 1j]
res = pu.getdomain(x)
assert_almost_equal(res, tgt)
def test_mapdomain(self):
# test for real values
dom1 = [0, 4]
dom2 = [1, 3]
tgt = dom2
res = pu.mapdomain(dom1, dom1, dom2)
assert_almost_equal(res, tgt)
# test for complex values
dom1 = [0 - 1j, 2 + 1j]
dom2 = [-2, 2]
tgt = dom2
x = dom1
res = pu.mapdomain(x, dom1, dom2)
assert_almost_equal(res, tgt)
# test for multidimensional arrays
dom1 = [0, 4]
dom2 = [1, 3]
tgt = np.array([dom2, dom2])
x = np.array([dom1, dom1])
res = pu.mapdomain(x, dom1, dom2)
assert_almost_equal(res, tgt)
# test that subtypes are preserved.
class MyNDArray(np.ndarray):
pass
dom1 = [0, 4]
dom2 = [1, 3]
x = np.array([dom1, dom1]).view(MyNDArray)
res = pu.mapdomain(x, dom1, dom2)
assert_(isinstance(res, MyNDArray))
def test_mapparms(self):
# test for real values
dom1 = [0, 4]
dom2 = [1, 3]
tgt = [1, .5]
res = pu. mapparms(dom1, dom2)
assert_almost_equal(res, tgt)
# test for complex values
dom1 = [0 - 1j, 2 + 1j]
dom2 = [-2, 2]
tgt = [-1 + 1j, 1 - 1j]
res = pu.mapparms(dom1, dom2)
assert_almost_equal(res, tgt)
| TestDomain |
python | catalyst-team__catalyst | tests/pipelines/test_mnist_multimodel.py | {
"start": 678,
"end": 8805
} | class ____(dl.Runner):
def predict_batch(self, batch):
# model inference step
return self.model(batch[0].to(self.device))
def on_loader_start(self, runner):
super().on_loader_start(runner)
self.meters = {
key: metrics.AdditiveMetric(compute_on_call=False)
for key in ["loss", "accuracy01", "accuracy03"]
}
def handle_batch(self, batch):
# model train/valid step
# unpack the batch
x, y = batch
# <--- multi-model usage --->
# run model forward pass
x_ = self.model["encoder"](x)
logits = self.model["head"](x_)
# <--- multi-model usage --->
# compute the loss
loss = self.criterion(logits, y)
# compute other metrics of interest
accuracy01, accuracy03 = metrics.accuracy(logits, y, topk=(1, 3))
# log metrics
self.batch_metrics.update(
{"loss": loss, "accuracy01": accuracy01, "accuracy03": accuracy03}
)
for key in ["loss", "accuracy01", "accuracy03"]:
self.meters[key].update(self.batch_metrics[key].item(), self.batch_size)
# run model backward pass
if self.is_train_loader:
self.engine.backward(loss)
self.optimizer.step()
self.optimizer.zero_grad()
def on_loader_end(self, runner):
for key in ["loss", "accuracy01", "accuracy03"]:
self.loader_metrics[key] = self.meters[key].compute()[0]
super().on_loader_end(runner)
def train_experiment(engine=None):
with TemporaryDirectory() as logdir:
# <--- multi-model setup --->
encoder = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 128))
head = nn.Linear(128, 10)
model = {"encoder": encoder, "head": head}
optimizer = optim.Adam(
[{"params": encoder.parameters()}, {"params": head.parameters()}], lr=0.02
)
# <--- multi-model setup --->
criterion = nn.CrossEntropyLoss()
loaders = {
"train": DataLoader(
MNIST(DATA_ROOT, train=True),
batch_size=32,
),
"valid": DataLoader(
MNIST(DATA_ROOT, train=False),
batch_size=32,
),
}
runner = CustomRunner()
# model training
runner.train(
engine=engine,
model=model,
criterion=criterion,
optimizer=optimizer,
loaders=loaders,
logdir=logdir,
num_epochs=1,
verbose=False,
valid_loader="valid",
valid_metric="loss",
minimize_valid_metric=True,
)
def train_experiment_from_configs(*auxiliary_configs: str):
run_experiment_from_configs(
Path(__file__).parent / "configs",
f"{Path(__file__).stem}.yml",
*auxiliary_configs,
)
# Device
@mark.skipif(not IS_CPU_REQUIRED, reason="CUDA device is not available")
def test_run_on_cpu():
train_experiment(dl.CPUEngine())
@mark.skipif(
not IS_CONFIGS_REQUIRED or not IS_CPU_REQUIRED, reason="CPU device is not available"
)
def test_config_run_on_cpu():
train_experiment_from_configs("engine_cpu.yml")
@mark.skipif(
not all([IS_GPU_REQUIRED, IS_CUDA_AVAILABLE]), reason="CUDA device is not available"
)
def test_run_on_torch_cuda0():
train_experiment(dl.GPUEngine())
@mark.skipif(
not IS_CONFIGS_REQUIRED or not all([IS_GPU_REQUIRED, IS_CUDA_AVAILABLE]),
reason="CUDA device is not available",
)
def test_config_run_on_torch_cuda0():
train_experiment_from_configs("engine_gpu.yml")
@mark.skipif(
not all([IS_GPU_AMP_REQUIRED, IS_CUDA_AVAILABLE, SETTINGS.amp_required]),
reason="No CUDA or AMP found",
)
def test_run_on_amp():
train_experiment(dl.GPUEngine(fp16=True))
@mark.skipif(
not IS_CONFIGS_REQUIRED
or not all([IS_GPU_AMP_REQUIRED, IS_CUDA_AVAILABLE, SETTINGS.amp_required]),
reason="No CUDA or AMP found",
)
def test_config_run_on_amp():
train_experiment_from_configs("engine_gpu_amp.yml")
# DP
@mark.skipif(
not all([IS_DP_REQUIRED, IS_CUDA_AVAILABLE, NUM_CUDA_DEVICES >= 2]),
reason="No CUDA>=2 found",
)
def test_run_on_torch_dp():
train_experiment(dl.DataParallelEngine())
@mark.skipif(
not IS_CONFIGS_REQUIRED
or not all([IS_DP_REQUIRED, IS_CUDA_AVAILABLE, NUM_CUDA_DEVICES >= 2]),
reason="No CUDA>=2 found",
)
def test_config_run_on_torch_dp():
train_experiment_from_configs("engine_dp.yml")
@mark.skipif(
not all(
[
IS_DP_AMP_REQUIRED,
IS_CUDA_AVAILABLE,
NUM_CUDA_DEVICES >= 2,
SETTINGS.amp_required,
]
),
reason="No CUDA>=2 or AMP found",
)
def test_run_on_amp_dp():
train_experiment(dl.DataParallelEngine(fp16=True))
@mark.skipif(
not IS_CONFIGS_REQUIRED
or not all(
[
IS_DP_AMP_REQUIRED,
IS_CUDA_AVAILABLE,
NUM_CUDA_DEVICES >= 2,
SETTINGS.amp_required,
]
),
reason="No CUDA>=2 or AMP found",
)
def test_config_run_on_amp_dp():
train_experiment_from_configs("engine_dp_amp.yml")
# DDP
# @mark.skipif(
# not all([IS_DDP_REQUIRED, IS_CUDA_AVAILABLE, NUM_CUDA_DEVICES >= 2]),
# reason="No CUDA>=2 found",
# )
# def test_run_on_torch_ddp():
# train_experiment(dl.DistributedDataParallelEngine())
# @mark.skipif(
# not IS_CONFIGS_REQUIRED
# or not all([IS_DDP_REQUIRED, IS_CUDA_AVAILABLE, NUM_CUDA_DEVICES >= 2]),
# reason="No CUDA>=2 found",
# )
# def test_config_run_on_torch_ddp():
# train_experiment_from_configs("engine_ddp.yml")
# @mark.skipif(
# not all(
# [
# IS_DDP_AMP_REQUIRED,
# IS_CUDA_AVAILABLE,
# NUM_CUDA_DEVICES >= 2,
# SETTINGS.amp_required,
# ]
# ),
# reason="No CUDA>=2 or AMP found",
# )
# def test_run_on_amp_ddp():
# train_experiment(dl.DistributedDataParallelEngine(fp16=True))
# @mark.skipif(
# not IS_CONFIGS_REQUIRED
# or not all(
# [
# IS_DDP_AMP_REQUIRED,
# IS_CUDA_AVAILABLE,
# NUM_CUDA_DEVICES >= 2,
# SETTINGS.amp_required,
# ]
# ),
# reason="No CUDA>=2 or AMP found",
# )
# def test_config_run_on_amp_ddp():
# train_experiment_from_configs("engine_ddp_amp.yml")
# def _train_fn(local_rank, world_size):
# process_group_kwargs = {
# "backend": "nccl",
# "world_size": world_size,
# }
# os.environ["WORLD_SIZE"] = str(world_size)
# os.environ["RANK"] = str(local_rank)
# os.environ["LOCAL_RANK"] = str(local_rank)
# dist.init_process_group(**process_group_kwargs)
# train_experiment(dl.Engine())
# dist.destroy_process_group()
# @mark.skipif(
# not all([IS_DDP_REQUIRED, IS_CUDA_AVAILABLE, NUM_CUDA_DEVICES >= 2]),
# reason="No CUDA>=2 found",
# )
# def test_run_on_torch_ddp_spawn():
# world_size: int = torch.cuda.device_count()
# mp.spawn(
# _train_fn,
# args=(world_size,),
# nprocs=world_size,
# join=True,
# )
# def _train_fn_amp(local_rank, world_size):
# process_group_kwargs = {
# "backend": "nccl",
# "world_size": world_size,
# }
# os.environ["WORLD_SIZE"] = str(world_size)
# os.environ["RANK"] = str(local_rank)
# os.environ["LOCAL_RANK"] = str(local_rank)
# dist.init_process_group(**process_group_kwargs)
# train_experiment(dl.Engine(fp16=True))
# dist.destroy_process_group()
# @mark.skipif(
# not all(
# [
# IS_DDP_AMP_REQUIRED,
# IS_CUDA_AVAILABLE,
# NUM_CUDA_DEVICES >= 2,
# SETTINGS.amp_required,
# ]
# ),
# reason="No CUDA>=2 or AMP found",
# )
# def test_run_on_torch_ddp_amp_spawn():
# world_size: int = torch.cuda.device_count()
# mp.spawn(
# _train_fn_amp,
# args=(world_size,),
# nprocs=world_size,
# join=True,
# )
# dist.destroy_process_group()
| CustomRunner |
python | getsentry__sentry | src/sentry/interfaces/exception.py | {
"start": 11706,
"end": 15780
} | class ____(Interface):
"""
An exception consists of a list of values. In most cases, this list
contains a single exception, with an optional stacktrace interface.
Each exception has a mandatory ``value`` argument and optional ``type`` and
``module`` arguments describing the exception class type and module
namespace.
You can also optionally bind a stacktrace interface to an exception. The
spec is identical to ``stacktrace``.
>>> {
>>> "values": [{
>>> "type": "ValueError",
>>> "value": "My exception value",
>>> "module": "__builtins__",
>>> "mechanism": {
>>> # see sentry.interfaces.Mechanism
>>> },
>>> "stacktrace": {
>>> # see stacktrace
>>> }
>>> }]
>>> }
Values should be sent oldest to newest, this includes both the stacktrace
and the exception itself.
.. note:: This interface can be passed as the 'exception' key in addition
to the full interface path.
"""
score = 2000
grouping_variants = ["system", "app"]
def exceptions(self):
return get_path(self.values, filter=True)
def __getitem__(self, key):
return self.exceptions()[key]
def __iter__(self):
return iter(self.exceptions())
def __len__(self) -> int:
return len(self.exceptions())
@classmethod
def to_python(cls, data, **kwargs):
values = []
for i, v in enumerate(get_path(data, "values", default=[])):
if not v:
# Cannot skip over None-values, need to preserve offsets
values.append(v)
else:
values.append(SingleException.to_python(v, **kwargs))
return super().to_python(
{"values": values, "exc_omitted": data.get("exc_omitted")}, **kwargs
)
# TODO(ja): Fix all following methods when to_python is refactored. All
# methods below might throw if None exceptions are in ``values``.
def to_json(self):
return prune_empty_keys(
{
"values": [v and v.to_json() for v in self.values] or None,
"exc_omitted": self.exc_omitted,
}
)
def get_api_context(self, is_public=False, platform=None):
return {
"values": [
v.get_api_context(is_public=is_public, platform=platform) for v in self.values if v
],
"hasSystemFrames": any(
v.stacktrace.get_has_system_frames() for v in self.values if v and v.stacktrace
),
"excOmitted": self.exc_omitted,
}
def get_api_meta(self, meta, is_public=False, platform=None):
if not meta:
return meta
result = {}
values = meta.get("values", meta)
for index, value in values.items():
exc = self.values[int(index)]
if exc is not None:
result[index] = exc.get_api_meta(value, is_public=is_public, platform=platform)
return {"values": result}
def to_string(self, event) -> str:
if not self.values:
return ""
output = []
for exc in self.values:
if not exc:
continue
output.append(f"{exc.type}: {exc.value}\n")
if exc.stacktrace:
output.append(
exc.stacktrace.get_stacktrace(
event, system_frames=False, max_frames=5, header=False
)
+ "\n\n"
)
return "".join(output).strip()
def get_stacktrace(self, *args, **kwargs):
exc = self.values[-1]
if exc.stacktrace:
return exc.stacktrace.get_stacktrace(*args, **kwargs)
return ""
def iter_tags(self):
if not self.values or not self.values[-1]:
return
mechanism = self.values[-1].mechanism
if mechanism:
yield from mechanism.iter_tags()
| Exception |
python | getsentry__sentry | src/sentry/core/endpoints/organization_member_team_details.py | {
"start": 2044,
"end": 2404
} | class ____(TypedDict):
isActive: bool
# This must be manually kept up to date, because we cannot dynamically
# unpack into static type annotations. See https://github.com/microsoft/pylance-release/issues/4084
teamRole: Literal["contributor", "admin"]
@extend_schema_serializer(exclude_fields=["isActive"])
| OrganizationMemberTeamSerializerResponse |
python | google__pytype | pytype/rewrite/output.py | {
"start": 229,
"end": 8325
} | class ____:
"""Abstract -> pytd converter."""
def __init__(self, ctx: abstract.ContextType):
self._ctx = ctx
def to_pytd_def(self, val: abstract.BaseValue) -> pytd.Node:
"""Returns the pytd definition of the abstract value.
For example, if the abstract value is:
InterpreterClass(name='C', members={'x': PythonConstant(0)})
then to_pytd_def() produces:
pytd.Class(name='C',
constants=(pytd.Constant(name='x', type=pytd.NamedType(int)),))
Args:
val: The abstract value.
"""
if isinstance(val, abstract.SimpleClass):
return self._class_to_pytd_def(val)
elif isinstance(val, abstract.BaseFunction):
return self._function_to_pytd_def(val)
else:
raise NotImplementedError(
f'to_pytd_def() not implemented for {val.__class__.__name__}: {val}'
)
def _class_to_pytd_def(self, val: abstract.SimpleClass) -> pytd.Class:
"""Converts an abstract class to a pytd.Class."""
methods = []
constants = []
classes = []
instance = val.instantiate()
for member_name, member_val in val.members.items():
if member_name in _IGNORED_CLASS_ATTRIBUTES:
continue
if isinstance(member_val, abstract.SimpleFunction):
member_val = member_val.bind_to(instance)
try:
member_type = self.to_pytd_def(member_val)
except NotImplementedError:
member_type = self.to_pytd_type(member_val)
if isinstance(member_type, pytd.Function):
methods.append(member_type)
elif isinstance(member_type, pytd.Class):
classes.append(member_type)
else:
class_member_type = pytd.GenericType(
base_type=pytd.NamedType('typing.ClassVar'),
parameters=(member_type,),
)
constants.append(
pytd.Constant(name=member_name, type=class_member_type)
)
for member_name, member_val in instance.members.items():
member_type = self.to_pytd_type(member_val)
constants.append(pytd.Constant(name=member_name, type=member_type))
keywords = tuple(
(k, self.to_pytd_type_of_instance(v)) for k, v in val.keywords.items()
)
bases = tuple(self.to_pytd_type_of_instance(base) for base in val.bases)
return pytd.Class(
name=val.name,
keywords=keywords,
bases=bases,
methods=tuple(methods),
constants=tuple(constants),
classes=tuple(classes),
decorators=(),
slots=None,
template=(),
)
def _signature_to_pytd(self, sig: abstract.Signature) -> pytd.Signature:
"""Converts a signature to a pytd.Signature."""
def get_pytd(param_name):
if param_name in sig.annotations:
return self.to_pytd_type_of_instance(sig.annotations[param_name])
else:
return pytd.AnythingType()
params = []
for i, param_name in enumerate(sig.param_names):
if i < sig.posonly_count:
param_kind = pytd.ParameterKind.POSONLY
else:
param_kind = pytd.ParameterKind.REGULAR
params.append((param_name, param_kind))
params.extend(
(param_name, pytd.ParameterKind.KWONLY)
for param_name in sig.kwonly_params
)
pytd_params = tuple(
pytd.Parameter(
name=param_name,
type=get_pytd(param_name),
kind=param_kind,
optional=param_name in sig.defaults,
mutated_type=None,
)
for param_name, param_kind in params
)
if sig.varargs_name:
starargs = pytd.Parameter(
name=sig.varargs_name,
type=get_pytd(sig.varargs_name),
kind=pytd.ParameterKind.REGULAR,
optional=True,
mutated_type=None,
)
else:
starargs = None
if sig.kwargs_name:
starstarargs = pytd.Parameter(
name=sig.kwargs_name,
type=get_pytd(sig.kwargs_name),
kind=pytd.ParameterKind.REGULAR,
optional=True,
mutated_type=None,
)
else:
starstarargs = None
if 'return' in sig.annotations:
ret_type = self.to_pytd_type_of_instance(sig.annotations['return'])
else:
ret_type = pytd.AnythingType()
return pytd.Signature(
params=pytd_params,
starargs=starargs,
starstarargs=starstarargs,
return_type=ret_type,
exceptions=(),
template=(),
)
def _function_to_pytd_def(
self,
val: abstract.SimpleFunction | abstract.BoundFunction,
) -> pytd.Function:
"""Converts an abstract function to a pytd.Function."""
pytd_sigs = []
for sig in val.signatures:
pytd_sig = self._signature_to_pytd(sig)
if 'return' not in sig.annotations:
ret = val.analyze_signature(sig)
ret_type = self.to_pytd_type(ret.get_return_value())
pytd_sig = pytd_sig.Replace(return_type=ret_type)
pytd_sigs.append(pytd_sig)
return pytd.Function(
name=val.name.rsplit('.', 1)[-1],
signatures=tuple(pytd_sigs),
kind=pytd.MethodKind.METHOD,
)
def to_pytd_type(self, val: abstract.BaseValue) -> pytd.Type:
"""Returns the type of the abstract value, as a pytd node.
For example, if the abstract value is:
PythonConstant(0)
then to_pytd_type() produces:
pytd.NamedType(int)
Args:
val: The abstract value.
"""
if val is self._ctx.consts.Any:
return pytd.AnythingType()
elif isinstance(val, abstract.Union):
return pytd_utils.JoinTypes(self.to_pytd_type(v) for v in val.options)
elif isinstance(val, abstract.PythonConstant):
return pytd.NamedType(f'builtins.{val.constant.__class__.__name__}')
elif isinstance(val, abstract.FunctionArgDict):
return pytd.NamedType('builtins.dict')
elif isinstance(val, abstract.SimpleClass):
return pytd.GenericType(
base_type=pytd.NamedType('builtins.type'),
parameters=(pytd.NamedType(val.name),),
)
elif isinstance(val, abstract.BaseInstance):
return pytd.NamedType(val.cls.name)
elif isinstance(val, (abstract.BaseFunction, abstract.BoundFunction)):
if len(val.signatures) > 1:
fixed_length_posargs_only = False
else:
sig = val.signatures[0]
fixed_length_posargs_only = (
not sig.defaults
and not sig.varargs_name
and not sig.kwonly_params
and not sig.kwargs_name
)
if fixed_length_posargs_only:
(pytd_sig,) = self.to_pytd_def(val).signatures
params = tuple(param.type for param in pytd_sig.params)
return pytd.CallableType(
base_type=pytd.NamedType('typing.Callable'),
parameters=params + (pytd_sig.return_type,),
)
else:
ret = abstract.join_values(
self._ctx, [frame.get_return_value() for frame in val.analyze()]
)
return pytd.GenericType(
base_type=pytd.NamedType('typing.Callable'),
parameters=(pytd.AnythingType(), self.to_pytd_type(ret)),
)
else:
raise NotImplementedError(
f'to_pytd_type() not implemented for {val.__class__.__name__}: {val}'
)
def to_pytd_type_of_instance(self, val: abstract.BaseValue) -> pytd.Type:
"""Returns the type of an instance of the abstract value, as a pytd node.
For example, if the abstract value is:
InterpreterClass(C)
then to_pytd_type_of_instance() produces:
pytd.NamedType(C)
Args:
val: The abstract value.
"""
if val is self._ctx.consts.Any:
return pytd.AnythingType()
elif val is self._ctx.consts[None]:
return pytd.NamedType('builtins.NoneType')
elif isinstance(val, abstract.Union):
return pytd_utils.JoinTypes(
self.to_pytd_type_of_instance(v) for v in val.options
)
elif isinstance(val, abstract.SimpleClass):
return pytd.NamedType(val.name)
else:
raise NotImplementedError(
'to_pytd_type_of_instance() not implemented for '
f'{val.__class__.__name__}: {val}'
)
| PytdConverter |
python | ray-project__ray | python/ray/llm/_internal/serve/core/configs/openai_api_models.py | {
"start": 1734,
"end": 1828
} | class ____(vLLMErrorInfo):
model_config = ConfigDict(arbitrary_types_allowed=True)
| ErrorInfo |
python | google__pytype | pytype/imports_map.py | {
"start": 138,
"end": 704
} | class ____:
"""Parsed --imports_info.
Attributes:
items: Map from module path to full file path on disk.
unused: Unused files. Stored here, so they can be emitted as unused inputs.
See --unused_imports_info_files option.
"""
items: Mapping[str, str] = dataclasses.field(default_factory=dict)
unused: Sequence[str] = dataclasses.field(default_factory=list)
def __getitem__(self, key: str):
return self.items[key]
def __contains__(self, key: str):
return key in self.items
def __len__(self):
return len(self.items)
| ImportsMap |
python | justquick__django-activity-stream | actstream/registry.py | {
"start": 2800,
"end": 4049
} | class ____(dict):
def register(self, *model_classes_or_labels):
for class_or_label in model_classes_or_labels:
model_class = validate(class_or_label)
if model_class not in self:
self[model_class] = setup_generic_relations(model_class)
def unregister(self, *model_classes_or_labels):
for class_or_label in model_classes_or_labels:
model_class = validate(class_or_label)
if model_class in self:
del self[model_class]
def check(self, model_class_or_object):
if getattr(model_class_or_object, '_deferred', None):
model_class_or_object = model_class_or_object._meta.proxy_for_model
if not isclass(model_class_or_object):
model_class_or_object = model_class_or_object.__class__
model_class = validate(model_class_or_object, RuntimeError)
if model_class not in self:
raise ImproperlyConfigured(
'The model %s is not registered. Please use actstream.registry '
'to register it.' % model_class.__name__)
registry = ActionableModelRegistry()
register = registry.register
unregister = registry.unregister
check = registry.check
| ActionableModelRegistry |
python | cython__cython | Cython/Compiler/TypeSlots.py | {
"start": 23561,
"end": 23794
} | class ____(SlotDescriptor):
# Slot descriptor for the method table.
def slot_code(self, scope):
if scope.pyfunc_entries:
return scope.method_table_cname
else:
return "0"
| MethodTableSlot |
python | pytorch__pytorch | .github/scripts/convert_lintrunner_annotations_to_github.py | {
"start": 299,
"end": 1772
} | class ____(NamedTuple):
path: str
start_line: int
end_line: int
start_column: Optional[int]
end_column: Optional[int]
annotation_level: GitHubAnnotationLevel
message: str
title: Optional[str]
raw_details: Optional[str]
PYTORCH_ROOT = Path(
subprocess.check_output(["git", "rev-parse", "--show-toplevel"])
.decode("ascii")
.strip()
)
annotations = []
for line in sys.stdin:
lint_message = json.loads(line)
path = lint_message.get("path")
line = lint_message.get("line")
code = lint_message["code"]
severity = lint_message["severity"]
name = lint_message["name"]
description = lint_message.get("description")
# These fields are required by the GitHub API, but optional in lintrunner.
# If they don't exist, just skip.
if path is None or line is None:
print(f"No path/line for lint: ({code}) {name}", file=sys.stderr)
continue
# normalize path relative to git root
path = Path(path).relative_to(PYTORCH_ROOT)
annotations.append(
GitHubAnnotation(
path=str(path),
start_line=int(line),
end_line=int(line),
start_column=None,
end_column=None,
annotation_level=GitHubAnnotationLevel.FAILURE,
message=description,
title=f"({code}) {name}",
raw_details=None,
)._asdict()
)
print(json.dumps(annotations), flush=True)
| GitHubAnnotation |
python | keras-team__keras | keras/src/backend/common/variables.py | {
"start": 23318,
"end": 24467
} | class ____:
"""Context manager that enables the autocasting of float variables.
Under this context manager, float `Variables`s will be cast to `dtype`
(note that `dtype` must also be float).
"""
def __init__(self, dtype):
if dtype is not None:
dtype = standardize_dtype(dtype)
if not is_float_dtype(dtype):
raise ValueError(
"`AutocastScope` can only be used with "
"a floating-point target dtype, such as 'float16'. "
f"Received: dtype={dtype}"
)
self.dtype = dtype
self.original_scope = None
def maybe_cast(self, value):
from keras.src import backend
if self.dtype is not None and is_float_dtype(value.dtype):
return backend.cast(value, dtype=self.dtype)
return value
def __enter__(self):
self.original_scope = get_autocast_scope()
global_state.set_global_attribute("autocast_scope", self)
def __exit__(self, *args, **kwargs):
global_state.set_global_attribute("autocast_scope", self.original_scope)
| AutocastScope |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-orchestrate/test_flow_routing.py | {
"start": 104,
"end": 411
} | class ____(Executor):
@requests
def add_text(self, docs, **kwargs):
docs[0].text = 'Hello World!'
def test_simple_routing():
f = Flow().add(uses=SimplExecutor)
with f:
docs = f.post(on='/index', inputs=[Document()])
assert docs[0].text == 'Hello World!'
| SimplExecutor |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/overrides.py | {
"start": 3207,
"end": 3403
} | class ____(AnalyzeAllOverrides):
def return_source(self):
return _test_source()
def call_analyze_call_overrides(a: AnalyzeAllOverrides):
a.return_source()
| AnalyzeAllOverridesChild3 |
python | sympy__sympy | sympy/polys/domains/quotientring.py | {
"start": 2541,
"end": 5911
} | class ____(Ring):
"""
Class representing (commutative) quotient rings.
You should not usually instantiate this by hand, instead use the constructor
from the base ring in the construction.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> I = QQ.old_poly_ring(x).ideal(x**3 + 1)
>>> QQ.old_poly_ring(x).quotient_ring(I)
QQ[x]/<x**3 + 1>
Shorter versions are possible:
>>> QQ.old_poly_ring(x)/I
QQ[x]/<x**3 + 1>
>>> QQ.old_poly_ring(x)/[x**3 + 1]
QQ[x]/<x**3 + 1>
Attributes:
- ring - the base ring
- base_ideal - the ideal used to form the quotient
"""
has_assoc_Ring = True
has_assoc_Field = False
dtype = QuotientRingElement
def __init__(self, ring, ideal):
if not ideal.ring == ring:
raise ValueError('Ideal must belong to %s, got %s' % (ring, ideal))
self.ring = ring
self.base_ideal = ideal
self.zero = self(self.ring.zero)
self.one = self(self.ring.one)
def __str__(self):
return str(self.ring) + "/" + str(self.base_ideal)
def __hash__(self):
return hash((self.__class__.__name__, self.dtype, self.ring, self.base_ideal))
def new(self, a):
"""Construct an element of ``self`` domain from ``a``. """
if not isinstance(a, self.ring.dtype):
a = self.ring(a)
# TODO optionally disable reduction?
return self.dtype(self, self.base_ideal.reduce_element(a))
def __eq__(self, other):
"""Returns ``True`` if two domains are equivalent. """
return isinstance(other, QuotientRing) and \
self.ring == other.ring and self.base_ideal == other.base_ideal
def from_ZZ(K1, a, K0):
"""Convert a Python ``int`` object to ``dtype``. """
return K1(K1.ring.convert(a, K0))
from_ZZ_python = from_ZZ
from_QQ_python = from_ZZ_python
from_ZZ_gmpy = from_ZZ_python
from_QQ_gmpy = from_ZZ_python
from_RealField = from_ZZ_python
from_GlobalPolynomialRing = from_ZZ_python
from_FractionField = from_ZZ_python
def from_sympy(self, a):
return self(self.ring.from_sympy(a))
def to_sympy(self, a):
return self.ring.to_sympy(a.data)
def from_QuotientRing(self, a, K0):
if K0 == self:
return a
def poly_ring(self, *gens):
"""Returns a polynomial ring, i.e. ``K[X]``. """
raise NotImplementedError('nested domains not allowed')
def frac_field(self, *gens):
"""Returns a fraction field, i.e. ``K(X)``. """
raise NotImplementedError('nested domains not allowed')
def revert(self, a):
"""
Compute a**(-1), if possible.
"""
I = self.ring.ideal(a.data) + self.base_ideal
try:
return self(I.in_terms_of_generators(1)[0])
except ValueError: # 1 not in I
raise NotReversible('%s not a unit in %r' % (a, self))
def is_zero(self, a):
return self.base_ideal.contains(a.data)
def free_module(self, rank):
"""
Generate a free module of rank ``rank`` over ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2)
(QQ[x]/<x**2 + 1>)**2
"""
return FreeModuleQuotientRing(self, rank)
| QuotientRing |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_spans_performance.py | {
"start": 8689,
"end": 8806
} | class ____(TypedDict):
op: str
group: str
examples: list[ExampleTransaction]
@region_silo_endpoint
| _Example |
python | spyder-ide__spyder | spyder/plugins/externalterminal/api.py | {
"start": 277,
"end": 863
} | class ____(TypedDict):
"""External terminal execution parameters for Python files."""
# True if the external terminal is using custom arguments. False otherwise
args_enabled: bool
# Custom arguments to pass to the external terminal.
args: str
# True if the terminal should remain open once the execution finishes.
# False otherwise.
interact: bool
# True if the terminal is using custom Python arguments. False otherwise.
python_args_enabled: bool
# Custom arguments to pass to the terminal.
python_args: str
| ExtTerminalPyConfiguration |
python | scrapy__scrapy | scrapy/contracts/default.py | {
"start": 1353,
"end": 3111
} | class ____(Contract):
"""Contract to check the output of a callback
general form:
@returns request(s)/item(s) [min=1 [max]]
e.g.:
@returns request
@returns request 2
@returns request 2 10
@returns request 0 10
"""
name = "returns"
object_type_verifiers: dict[str | None, Callable[[Any], bool]] = {
"request": lambda x: isinstance(x, Request),
"requests": lambda x: isinstance(x, Request),
"item": is_item,
"items": is_item,
}
def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
if len(self.args) not in [1, 2, 3]:
raise ValueError(
f"Incorrect argument quantity: expected 1, 2 or 3, got {len(self.args)}"
)
self.obj_name = self.args[0] or None
self.obj_type_verifier = self.object_type_verifiers[self.obj_name]
try:
self.min_bound: float = int(self.args[1])
except IndexError:
self.min_bound = 1
try:
self.max_bound: float = int(self.args[2])
except IndexError:
self.max_bound = float("inf")
def post_process(self, output: list[Any]) -> None:
occurrences = 0
for x in output:
if self.obj_type_verifier(x):
occurrences += 1
assertion = self.min_bound <= occurrences <= self.max_bound
if not assertion:
if self.min_bound == self.max_bound:
expected = str(self.min_bound)
else:
expected = f"{self.min_bound}..{self.max_bound}"
raise ContractFail(
f"Returned {occurrences} {self.obj_name}, expected {expected}"
)
| ReturnsContract |
python | pypa__warehouse | warehouse/admin/bans.py | {
"start": 226,
"end": 913
} | class ____:
def __init__(self, request):
self.request = request
def by_ip(self, ip_address: str) -> bool:
banned = (
self.request.db.query(IpAddress)
.filter_by(ip_address=type_coerce(ip_address, INET), is_banned=True)
.one_or_none()
)
if banned is not None:
login_service = self.request.find_service(IUserService, context=None)
login_service._check_ratelimits(userid=None, tags=["banned:by_ip"])
login_service._hit_ratelimits(userid=None)
return True
return False
def includeme(config):
config.add_request_method(Bans, name="banned", reify=True)
| Bans |
python | scikit-learn__scikit-learn | sklearn/linear_model/_ridge.py | {
"start": 57898,
"end": 58266
} | class ____(LinearClassifierMixin, BaseEstimator):
"""Fake classifier which will directly output the prediction.
We inherit from LinearClassifierMixin to get the proper shape for the
output `y`.
"""
def __init__(self, classes):
self.classes_ = classes
def decision_function(self, y_predict):
return y_predict
| _IdentityClassifier |
python | huggingface__transformers | src/transformers/models/table_transformer/modeling_table_transformer.py | {
"start": 37570,
"end": 45323
} | class ____(TableTransformerPreTrainedModel):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TableTransformerDecoderLayer`].
The decoder updates the query embeddings through multiple self-attention and cross-attention layers.
Some small tweaks for TABLE_TRANSFORMER:
- object_queries and query_position_embeddings are added to the forward pass.
- if self.config.auxiliary_loss is set to True, also returns a stack of activations from all decoding layers.
Args:
config: TableTransformerConfig
"""
def __init__(self, config: TableTransformerConfig):
super().__init__(config)
self.dropout = config.dropout
self.layerdrop = config.decoder_layerdrop
self.layers = nn.ModuleList([TableTransformerDecoderLayer(config) for _ in range(config.decoder_layers)])
# in TABLE_TRANSFORMER, the decoder uses layernorm after the last decoder layer output
self.layernorm = nn.LayerNorm(config.d_model)
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
def forward(
self,
inputs_embeds=None,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
object_queries=None,
query_position_embeddings=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
Args:
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
The query embeddings that are passed into the decoder.
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on certain queries. Mask values selected in `[0, 1]`:
- 1 for queries that are **not masked**,
- 0 for queries that are **masked**.
[What are attention masks?](../glossary#attention-mask)
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
of the decoder.
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
in `[0, 1]`:
- 1 for pixels that are real (i.e. **not masked**),
- 0 for pixels that are padding (i.e. **masked**).
object_queries (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Object queries that are added to the queries and keys in each cross-attention layer.
query_position_embeddings (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
, *optional*): Position embeddings that are added to the values and keys in each self-attention layer.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if inputs_embeds is not None:
hidden_states = inputs_embeds
input_shape = inputs_embeds.size()[:-1]
combined_attention_mask = None
if attention_mask is not None and combined_attention_mask is not None:
# [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
combined_attention_mask = combined_attention_mask + _prepare_4d_attention_mask(
attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
)
# expand encoder attention mask
if encoder_hidden_states is not None and encoder_attention_mask is not None:
# [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
encoder_attention_mask = _prepare_4d_attention_mask(
encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
)
# optional intermediate hidden states
intermediate = () if self.config.auxiliary_loss else None
# decoder layers
all_hidden_states = () if output_hidden_states else None
all_self_attns = () if output_attentions else None
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
for idx, decoder_layer in enumerate(self.layers):
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
if output_hidden_states:
all_hidden_states += (hidden_states,)
if self.training:
dropout_probability = torch.rand([])
if dropout_probability < self.layerdrop:
continue
layer_outputs = decoder_layer(
hidden_states,
combined_attention_mask,
object_queries,
query_position_embeddings,
encoder_hidden_states, # as a positional argument for gradient checkpointing
encoder_attention_mask=encoder_attention_mask,
output_attentions=output_attentions,
)
hidden_states = layer_outputs[0]
if self.config.auxiliary_loss:
hidden_states = self.layernorm(hidden_states)
intermediate += (hidden_states,)
if output_attentions:
all_self_attns += (layer_outputs[1],)
if encoder_hidden_states is not None:
all_cross_attentions += (layer_outputs[2],)
# finally, apply layernorm
hidden_states = self.layernorm(hidden_states)
# add hidden states from the last decoder layer
if output_hidden_states:
all_hidden_states += (hidden_states,)
# stack intermediate decoder activations
if self.config.auxiliary_loss:
intermediate = torch.stack(intermediate)
if not return_dict:
return tuple(
v
for v in [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions, intermediate]
if v is not None
)
return TableTransformerDecoderOutput(
last_hidden_state=hidden_states,
hidden_states=all_hidden_states,
attentions=all_self_attns,
cross_attentions=all_cross_attentions,
intermediate_hidden_states=intermediate,
)
@auto_docstring(
custom_intro="""
The bare Table Transformer Model (consisting of a backbone and encoder-decoder Transformer) outputting raw
hidden-states without any specific head on top.
"""
)
| TableTransformerDecoder |
python | Netflix__metaflow | metaflow/plugins/retry_decorator.py | {
"start": 147,
"end": 1548
} | class ____(StepDecorator):
"""
Specifies the number of times the task corresponding
to a step needs to be retried.
This decorator is useful for handling transient errors, such as networking issues.
If your task contains operations that can't be retried safely, e.g. database updates,
it is advisable to annotate it with `@retry(times=0)`.
This can be used in conjunction with the `@catch` decorator. The `@catch`
decorator will execute a no-op task after all retries have been exhausted,
ensuring that the flow execution can continue.
Parameters
----------
times : int, default 3
Number of times to retry this task.
minutes_between_retries : int, default 2
Number of minutes between retries.
"""
name = "retry"
defaults = {"times": "3", "minutes_between_retries": "2"}
def step_init(self, flow, graph, step, decos, environment, flow_datastore, logger):
# The total number of attempts must not exceed MAX_ATTEMPTS.
# attempts = normal task (1) + retries (N) + @catch fallback (1)
if int(self.attributes["times"]) + 2 > MAX_ATTEMPTS:
raise MetaflowException(
"The maximum number of retries is "
"@retry(times=%d)." % (MAX_ATTEMPTS - 2)
)
def step_task_retry_count(self):
return int(self.attributes["times"]), 0
| RetryDecorator |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/types/python_dict.py | {
"start": 2481,
"end": 4681
} | class ____(DagsterType):
def __init__(self, key_type, value_type):
self.key_type = check.inst_param(key_type, "key_type", DagsterType)
self.value_type = check.inst_param(value_type, "value_type", DagsterType)
can_get_from_config = (
self.value_type.loader is not None
and isinstance(self.key_type, type(String))
) # True if value_type has a DagsterTypeLoader, meaning we can load the input from config,
# otherwise False.
super(_TypedPythonDict, self).__init__(
key=f"TypedPythonDict.{key_type.key}.{value_type.key}",
name=None,
loader=(
TypedDictLoader(self.key_type, self.value_type)
if can_get_from_config
else None
),
type_check_fn=self.type_check_method,
typing_type=typing.Dict[key_type.typing_type, value_type.typing_type],
)
def type_check_method(self, context, value):
from dagster._core.definitions.events import TypeCheck
if not isinstance(value, dict):
return TypeCheck(
success=False,
description=f"Value should be a dict, got a {type(value)}",
)
for key, value in value.items():
key_check = self.key_type.type_check(context, key)
if not key_check.success:
return key_check
value_check = self.value_type.type_check(context, value)
if not value_check.success:
return value_check
return TypeCheck(success=True)
@property
def display_name(self):
return f"Dict[{self.key_type.display_name},{self.value_type.display_name}]"
@property
def inner_types(self):
return [self.key_type, self.value_type] + self.value_type.inner_types
@property
def type_param_keys(self):
return [self.key_type.key, self.value_type.key]
def create_typed_runtime_dict(key_dagster_type, value_dagster_type):
key_type = resolve_dagster_type(key_dagster_type)
value_type = resolve_dagster_type(value_dagster_type)
return _TypedPythonDict(key_type, value_type)
| _TypedPythonDict |
python | joke2k__faker | faker/providers/automotive/sk_SK/__init__.py | {
"start": 63,
"end": 2641
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``sk_SK`` locale.
Sources:
- https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Slovakia
"""
license_plate_prefix = [
"BA",
"BL",
"BT", # Bratislava
"BB", # Banska Bystrica
"BJ", # Bardejov
"BN", # Banovce nad Bebravou
"BR", # Brezno
"BS", # Banska Stiavnica
"BY", # Bytca
"CA", # Cadca
"DK", # Dolny Kubin
"DS", # Dunajska Streda
"DT", # Detva
"GA", # Galanta
"GL", # Gelnica
"HC", # Hlohovec
"HE", # Humenne
"IL", # Ilava
"KA", # Krupina
"KE", # Kosice
"KK", # Kezmarok
"KM", # Kysucke Nove Mesto
"KN", # Komarno
"KS", # Kosice-okolie
"LC", # Lucenec
"LE", # Levoca
"LM", # Liptovsky Mikulas
"LV", # Levice
"MA", # Malacky
"MI", # Michalovce
"ML", # Medzilaborce
"MT", # Martin
"MY", # Myjava
"NR", # Nitra
"NM", # Nove Mesto nad Vahom
"NO", # Namestovo
"NZ", # Nove Zamky
"PB", # Povazska Bystrica
"PD", # Prievidza
"PE", # Partizanske
"PK", # Pezinok
"PN", # Piestany
"PO", # Presov
"PP", # Poprad
"PT", # Poltar
"PU", # Puchov
"RA", # Revuca
"RK", # Ruzomberok
"RS", # Rimavska Sobota
"RV", # Roznava
"SA", # Sala
"SB", # Sabinov
"SC", # Senec
"SE", # Senica
"SI", # Skalica
"SK", # Svidnik
"SL", # Stara Lubovna
"SN", # Spisska Nova Ves
"SO", # Sobrance
"SP", # Stropkov
"SV", # Snina
"TT", # Trnava
"TN", # Trencin
"TO", # Topolcany
"TR", # Turcianske Teplice
"TS", # Tvrdosin
"TV", # Trebisov
"VK", # Velky Krtis
"VT", # Vranov nad Toplou
"ZA", # Zilina
"ZC", # Zarnovica
"ZH", # Ziar nad Hronom
"ZM", # Zlate Moravce
"ZV", # Zvolen
]
license_plate_suffix = ("###??",)
def license_plate(self) -> str:
"""Generate a license plate."""
prefix: str = self.random_element(self.license_plate_prefix)
suffix = self.bothify(
self.random_element(self.license_plate_suffix),
letters=string.ascii_uppercase,
)
return prefix + suffix
| Provider |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/associationproxy.py | {
"start": 12551,
"end": 19796
} | class ____(
interfaces.InspectionAttrInfo,
ORMDescriptor[_T],
_DCAttributeOptions,
_AssociationProxyProtocol[_T],
):
"""A descriptor that presents a read/write view of an object attribute."""
is_attribute = True
extension_type = AssociationProxyExtensionType.ASSOCIATION_PROXY
def __init__(
self,
target_collection: str,
attr: str,
*,
creator: Optional[_CreatorProtocol] = None,
getset_factory: Optional[_GetSetFactoryProtocol] = None,
proxy_factory: Optional[_ProxyFactoryProtocol] = None,
proxy_bulk_set: Optional[_ProxyBulkSetProtocol] = None,
info: Optional[_InfoType] = None,
cascade_scalar_deletes: bool = False,
create_on_none_assignment: bool = False,
attribute_options: Optional[_AttributeOptions] = None,
):
"""Construct a new :class:`.AssociationProxy`.
The :class:`.AssociationProxy` object is typically constructed using
the :func:`.association_proxy` constructor function. See the
description of :func:`.association_proxy` for a description of all
parameters.
"""
self.target_collection = target_collection
self.value_attr = attr
self.creator = creator
self.getset_factory = getset_factory
self.proxy_factory = proxy_factory
self.proxy_bulk_set = proxy_bulk_set
if cascade_scalar_deletes and create_on_none_assignment:
raise exc.ArgumentError(
"The cascade_scalar_deletes and create_on_none_assignment "
"parameters are mutually exclusive."
)
self.cascade_scalar_deletes = cascade_scalar_deletes
self.create_on_none_assignment = create_on_none_assignment
self.key = "_%s_%s_%s" % (
type(self).__name__,
target_collection,
id(self),
)
if info:
self.info = info # type: ignore
if (
attribute_options
and attribute_options != _DEFAULT_ATTRIBUTE_OPTIONS
):
self._has_dataclass_arguments = True
self._attribute_options = attribute_options
else:
self._has_dataclass_arguments = False
self._attribute_options = _DEFAULT_ATTRIBUTE_OPTIONS
@overload
def __get__(
self, instance: Literal[None], owner: Literal[None]
) -> Self: ...
@overload
def __get__(
self, instance: Literal[None], owner: Any
) -> AssociationProxyInstance[_T]: ...
@overload
def __get__(self, instance: object, owner: Any) -> _T: ...
def __get__(
self, instance: object, owner: Any
) -> Union[AssociationProxyInstance[_T], _T, AssociationProxy[_T]]:
if owner is None:
return self
inst = self._as_instance(owner, instance)
if inst:
return inst.get(instance)
assert instance is None
return self
def __set__(self, instance: object, values: _T) -> None:
class_ = type(instance)
self._as_instance(class_, instance).set(instance, values)
def __delete__(self, instance: object) -> None:
class_ = type(instance)
self._as_instance(class_, instance).delete(instance)
def for_class(
self, class_: Type[Any], obj: Optional[object] = None
) -> AssociationProxyInstance[_T]:
r"""Return the internal state local to a specific mapped class.
E.g., given a class ``User``::
class User(Base):
# ...
keywords = association_proxy("kws", "keyword")
If we access this :class:`.AssociationProxy` from
:attr:`_orm.Mapper.all_orm_descriptors`, and we want to view the
target class for this proxy as mapped by ``User``::
inspect(User).all_orm_descriptors["keywords"].for_class(User).target_class
This returns an instance of :class:`.AssociationProxyInstance` that
is specific to the ``User`` class. The :class:`.AssociationProxy`
object remains agnostic of its parent class.
:param class\_: the class that we are returning state for.
:param obj: optional, an instance of the class that is required
if the attribute refers to a polymorphic target, e.g. where we have
to look at the type of the actual destination object to get the
complete path.
"""
return self._as_instance(class_, obj)
def _as_instance(
self, class_: Any, obj: Any
) -> AssociationProxyInstance[_T]:
try:
inst = class_.__dict__[self.key + "_inst"]
except KeyError:
inst = None
# avoid exception context
if inst is None:
owner = self._calc_owner(class_)
if owner is not None:
inst = AssociationProxyInstance.for_proxy(self, owner, obj)
setattr(class_, self.key + "_inst", inst)
else:
inst = None
if inst is not None and not inst._is_canonical:
# the AssociationProxyInstance can't be generalized
# since the proxied attribute is not on the targeted
# class, only on subclasses of it, which might be
# different. only return for the specific
# object's current value
return inst._non_canonical_get_for_object(obj) # type: ignore
else:
return inst # type: ignore # TODO
def _calc_owner(self, target_cls: Any) -> Any:
# we might be getting invoked for a subclass
# that is not mapped yet, in some declarative situations.
# save until we are mapped
try:
insp = inspect(target_cls)
except exc.NoInspectionAvailable:
# can't find a mapper, don't set owner. if we are a not-yet-mapped
# subclass, we can also scan through __mro__ to find a mapped
# class, but instead just wait for us to be called again against a
# mapped class normally.
return None
else:
return insp.mapper.class_manager.class_
def _default_getset(
self, collection_class: Any
) -> Tuple[_GetterProtocol[Any], _SetterProtocol]:
attr = self.value_attr
_getter = operator.attrgetter(attr)
def getter(instance: Any) -> Optional[Any]:
return _getter(instance) if instance is not None else None
if collection_class is dict:
def dict_setter(instance: Any, k: Any, value: Any) -> None:
setattr(instance, attr, value)
return getter, dict_setter
else:
def plain_setter(o: Any, v: Any) -> None:
setattr(o, attr, v)
return getter, plain_setter
def __repr__(self) -> str:
return "AssociationProxy(%r, %r)" % (
self.target_collection,
self.value_attr,
)
# the pep-673 Self type does not work in Mypy for a "hybrid"
# style method that returns type or Self, so for one specific case
# we still need to use the pre-pep-673 workaround.
_Self = TypeVar("_Self", bound="AssociationProxyInstance[Any]")
| AssociationProxy |
python | weaviate__weaviate-python-client | weaviate/collections/tenants/async_.py | {
"start": 179,
"end": 244
} | class ____(_TenantsExecutor[ConnectionAsync]):
pass
| _TenantsAsync |
python | faif__python-patterns | patterns/structural/mvc.py | {
"start": 3054,
"end": 3976
} | class ____:
"""The Controller is the intermediary between the Model and the View."""
def __init__(self, model_class: Model, view_class: View) -> None:
self.model: Model = model_class
self.view: View = view_class
def show_items(self) -> None:
items = list(self.model)
item_type = self.model.item_type
self.view.show_item_list(item_type, items)
def show_item_information(self, item_name: str) -> None:
"""
Show information about a {item_type} item.
:param str item_name: the name of the {item_type} item to show information about
"""
item_type: str = self.model.item_type
try:
item_info: dict = self.model.get(item_name)
except Exception:
self.view.item_not_found(item_type, item_name)
else:
self.view.show_item_information(item_type, item_name, item_info)
| Controller |
python | apache__avro | lang/py/avro/test/test_schema.py | {
"start": 1461,
"end": 1596
} | class ____(TestSchema):
"""A proxy for a valid schema string that provides useful test metadata."""
valid = True
| ValidTestSchema |
python | apache__airflow | airflow-core/src/airflow/utils/types.py | {
"start": 904,
"end": 1664
} | class ____(str, enum.Enum):
"""Class with DagRun types."""
BACKFILL_JOB = "backfill"
SCHEDULED = "scheduled"
MANUAL = "manual"
ASSET_TRIGGERED = "asset_triggered"
def __str__(self) -> str:
return self.value
def generate_run_id(self, *, suffix: str) -> str:
"""
Generate a string for DagRun based on suffix string.
:param suffix: Generate run_id from suffix.
"""
return f"{self}__{suffix}"
@staticmethod
def from_run_id(run_id: str) -> DagRunType:
"""Resolve DagRun type from run_id."""
for run_type in DagRunType:
if run_id and run_id.startswith(f"{run_type.value}__"):
return run_type
return DagRunType.MANUAL
| DagRunType |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/airflow/AIR301_context.py | {
"start": 3958,
"end": 4616
} | class ____(BaseOperator):
def execute(self, next_ds, context):
execution_date = context["execution_date"]
next_ds = context["next_ds"]
next_ds_nodash = context["next_ds_nodash"]
next_execution_date = context["next_execution_date"]
prev_ds = context["prev_ds"]
prev_ds_nodash = context["prev_ds_nodash"]
prev_execution_date = context["prev_execution_date"]
prev_execution_date_success = context["prev_execution_date_success"]
tomorrow_ds = context["tomorrow_ds"]
yesterday_ds = context["yesterday_ds"]
yesterday_ds_nodash = context["yesterday_ds_nodash"]
| CustomOperator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink07.py | {
"start": 315,
"end": 1049
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink07.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Workbook(self.got_filename)
# Turn off default URL format for testing.
workbook.default_url_format = None
worksheet = workbook.add_worksheet()
worksheet.write_url(
"A1", r"external:\\VBOXSVR\share\foo.xlsx", None, r"J:\foo.xlsx"
)
worksheet.write_url("A3", r"external:foo.xlsx")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | pytorch__pytorch | torch/testing/_internal/distributed/_tensor/common_dtensor.py | {
"start": 6104,
"end": 11823
} | class ____(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
assert args.vocab_size is not None
assert args.max_seq_len is not None
self.model_args = args
self.max_seq_len = args.max_seq_len
self.tok_embeddings = nn.Embedding(args.vocab_size, args.dim)
self.pos_embeddings = nn.Embedding(args.max_seq_len, args.dim)
self.dropout = nn.Dropout(args.dropout_p)
self.layers = nn.ModuleList()
for _ in range(args.n_layers):
self.layers.append(TransformerBlock(args))
self.norm = nn.LayerNorm(args.dim)
self.output = nn.Linear(args.dim, args.vocab_size, bias=False)
if args.weight_tying:
self.output.weight = self.tok_embeddings.weight
self.checkpoint_activations = args.checkpoint_activations
def forward(self, tokens):
_bsz, seq_len = tokens.size()
assert seq_len <= self.max_seq_len
h = self.tok_embeddings(tokens)
pos = torch.arange(0, seq_len, device=tokens.device)
p = self.pos_embeddings(pos) # positional embeddings of shape (seq_len, dim)
h = h + p
h = self.dropout(h)
for layer in self.layers:
if self.checkpoint_activations:
h = torch.utils.checkpoint.checkpoint(layer, h, use_reentrant=False)
else:
h = layer(h)
h = self.norm(h)
output = self.output(h).float()
return output
@staticmethod
def parallelize(
module: "Transformer",
device_mesh: DeviceMesh,
use_seq_parallel: bool,
local_output_for_attn: bool = False,
) -> nn.Module:
assert isinstance(module, Transformer), f"Requires Transformer but got {module}"
# Parallelize the root submodules.
if use_seq_parallel:
root_plan = {
"tok_embeddings": RowwiseParallel(
input_layouts=Replicate(), output_layouts=Shard(1)
),
"pos_embeddings": RowwiseParallel(
input_layouts=Replicate(), output_layouts=Shard(0)
),
"norm": SequenceParallel(),
}
else:
root_plan = {
"tok_embeddings": RowwiseParallel(
input_layouts=Replicate(), output_layouts=Replicate()
),
"pos_embeddings": RowwiseParallel(
input_layouts=Replicate(), output_layouts=Replicate()
),
}
module_tp = parallelize_module(module, device_mesh, root_plan)
# Parallelize the attention and feed forward submodules.
for layer in module_tp.layers:
layer_parallelize_plan = {}
if use_seq_parallel:
layer_parallelize_plan["attention"] = PrepareModuleInput(
input_layouts=Shard(1),
desired_input_layouts=Replicate(),
)
# shard the RMSNorms
layer_parallelize_plan["attention_norm"] = SequenceParallel()
layer_parallelize_plan["ffn_norm"] = SequenceParallel()
layer_parallelize_plan["attention.wq"] = ColwiseParallel(
use_local_output=local_output_for_attn
)
layer_parallelize_plan["attention.wk"] = ColwiseParallel(
use_local_output=local_output_for_attn
)
layer_parallelize_plan["attention.wv"] = ColwiseParallel(
use_local_output=local_output_for_attn
)
layer_parallelize_plan["attention.wo"] = (
RowwiseParallel(output_layouts=Shard(1))
if use_seq_parallel
else RowwiseParallel()
)
layer_parallelize_plan["feed_forward.w1"] = (
ColwiseParallel(input_layouts=Shard(1))
if use_seq_parallel
else ColwiseParallel()
)
layer_parallelize_plan["feed_forward.w2"] = (
RowwiseParallel(output_layouts=Shard(1))
if use_seq_parallel
else RowwiseParallel()
)
parallelize_module(layer, device_mesh, layer_parallelize_plan)
# Parallelize the output submodule. If weight tying is enabled, we need to
# make sure output.weight is sharded consistently as tok_embeddings.weight,
# at the cost of the all_reduce operation using RowwiseParallel.
output_parallelize_plan = (
ColwiseParallel(
input_layouts=Shard(1),
output_layouts=Replicate(),
)
if use_seq_parallel
else ColwiseParallel(output_layouts=Replicate())
)
parallelize_module(module_tp.output, device_mesh, output_parallelize_plan)
if local_output_for_attn:
for layer in module_tp.layers:
layer.attention.n_heads = (
module_tp.model_args.n_heads // device_mesh.size()
)
# Manually set output.weight so that parameters and gradients are shared.
if module_tp.model_args.weight_tying:
module_tp.output.weight = module_tp.tok_embeddings.weight
return module_tp
def skip_unless_torch_gpu(method: T) -> T:
"""
Test decorator which skips the test unless there's a GPU available to torch.
>>> # xdoctest: +SKIP
>>> @skip_unless_torch_gpu
>>> def test_some_method(self) -> None:
>>> ...
"""
# The builtin @skip_if_no_gpu relies on os.environ['WORLD_SIZE'] being set.
return cast(T, skip_if_lt_x_gpu(NUM_DEVICES)(method))
| Transformer |
python | readthedocs__readthedocs.org | readthedocs/projects/forms.py | {
"start": 25020,
"end": 26112
} | class ____(forms.Field):
widget = forms.Textarea(
attrs={
"placeholder": "\n".join(
[
"whatsnew.html",
"archive/*",
"tags/*",
"guides/getting-started.html",
"changelog.html",
"release/*",
]
),
},
)
def to_python(self, value):
"""Convert a text area into a list of items (one per line)."""
if not value:
return []
# Normalize paths and filter empty lines:
# - remove trailing spaces
# - skip empty lines
# - remove starting `/`
result = []
for line in value.splitlines():
normalized = line.strip().lstrip("/")
if normalized:
result.append(normalized)
return result
def prepare_value(self, value):
"""Convert a list of items into a text area (one per line)."""
if not value:
return ""
return "\n".join(value)
| OnePerLineList |
python | huggingface__transformers | src/transformers/models/gpt2/tokenization_gpt2.py | {
"start": 1025,
"end": 6169
} | class ____(TokenizersBackend):
"""
Construct a GPT-2 tokenizer. Based on byte-level Byte-Pair-Encoding.
This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
be encoded differently whether it is at the beginning of the sentence (without space) or not:
```python
>>> from transformers import GPT2Tokenizer
>>> tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
>>> tokenizer("Hello world")["input_ids"]
[15496, 995]
>>> tokenizer(" Hello world")["input_ids"]
[18435, 995]
```
You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
<Tip>
When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
</Tip>
This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should refer to
this superclass for more information regarding those methods.
Args:
vocab_file (`str`):
Path to the vocabulary file.
merges_file (`str`):
Path to the merges file.
errors (`str`, *optional*, defaults to `"replace"`):
Paradigm to follow when decoding bytes to UTF-8. See
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.
bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The beginning of sequence token.
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
The end of sequence token.
pad_token (`str`, *optional*):
The token used for padding, for example when batching sequences of different lengths.
add_prefix_space (`bool`, *optional*, defaults to `False`):
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
other word. (GPT2 tokenizer detect beginning of words by the preceding space).
add_bos_token (`bool`, *optional*, defaults to `False`):
Whether or not to add an initial beginning of sentence token to the input. This allows to treat the leading
word just as any other word.
vocab (`dict`, *optional*):
Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
merges (`list`, *optional*):
Custom merges list. If not provided, merges are loaded from merges_file.
"""
vocab_files_names = VOCAB_FILES_NAMES
model_input_names = ["input_ids", "attention_mask"]
slow_tokenizer_class = None
def __init__(
self,
errors="replace",
unk_token="<|endoftext|>",
bos_token="<|endoftext|>",
eos_token="<|endoftext|>",
pad_token=None,
add_prefix_space=False,
add_bos_token=False,
vocab: Optional[dict] = None,
merges: Optional[list] = None,
**kwargs,
):
# self.add_bos_token = add_bos_token
self.add_prefix_space = add_prefix_space
if vocab is not None:
self._vocab = (
{token: idx for idx, (token, _score) in enumerate(vocab)} if isinstance(vocab, list) else vocab
)
else:
self._vocab = {}
if merges is not None:
self._merges = [tuple(merge) if isinstance(merge, list) else merge for merge in merges]
else:
self._merges = []
self._tokenizer = Tokenizer(
BPE(
vocab=self._vocab,
merges=self._merges,
dropout=None,
continuing_subword_prefix="",
end_of_word_suffix="",
fuse_unk=False,
)
)
self._tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
self._tokenizer.decoder = decoders.ByteLevel()
tokenizer_object = self._tokenizer
# Set these before calling super().__init__() so the base class _post_init() can use them
self._add_bos_token = add_bos_token
self._add_eos_token = False
super().__init__(
tokenizer_object=tokenizer_object,
errors=errors,
unk_token=unk_token,
bos_token=bos_token,
eos_token=eos_token,
pad_token=pad_token,
add_prefix_space=add_prefix_space,
add_bos_token=add_bos_token,
**kwargs,
)
# Call _post_init for tokenizers created directly (not from_pretrained)
# For from_pretrained, this will be called again after loading the tokenizer from file
self._post_init()
__all__ = ["GPT2Tokenizer"]
| GPT2Tokenizer |
python | huggingface__transformers | src/transformers/models/git/modeling_git.py | {
"start": 1871,
"end": 2415
} | class ____(ModelOutput):
r"""
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
The image embeddings obtained by applying the projection layer to the pooler_output.
"""
image_embeds: Optional[torch.FloatTensor] = None
last_hidden_state: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
| GitVisionModelOutput |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/await2.py | {
"start": 122,
"end": 590
} | class ____:
def __await__(self) -> Generator[Any, None, int]:
async def foo() -> int:
return 1
return foo().__await__()
async def foo(self) -> int:
return await self
async def func1() -> None:
p = MyAwaitable()
print(await p.foo())
print(await p)
async def func2() -> NoReturn:
raise Exception()
async def func3(x: int | None):
if x is None:
await func2()
print(x.bit_count())
| MyAwaitable |
python | great-expectations__great_expectations | great_expectations/metrics/metric_name.py | {
"start": 24,
"end": 149
} | class ____(str, Enum):
CONDITION = "condition"
COUNT = "count"
UNEXPECTED_COUNT = "unexpected_count"
| MetricNameSuffix |
python | weaviate__weaviate-python-client | weaviate/gql/filter.py | {
"start": 1292,
"end": 1437
} | class ____(Enum):
IMAGE = "image"
AUDIO = "audio"
VIDEO = "video"
THERMAL = "thermal"
DEPTH = "depth"
IMU = "imu"
| MediaType |
python | apache__airflow | airflow-core/tests/unit/always/test_project_structure.py | {
"start": 40936,
"end": 41025
} | class ____(ExampleCoverageTest):
PROVIDER = "docker"
| TestDockerProviderProjectStructure |
python | keras-team__keras | keras/src/saving/saving_lib_test.py | {
"start": 7330,
"end": 30066
} | class ____(testing.TestCase):
def setUp(self):
# Set `_MEMORY_UPPER_BOUND` to zero for testing purpose.
self.original_value = saving_lib._MEMORY_UPPER_BOUND
saving_lib._MEMORY_UPPER_BOUND = 0
return super().setUp()
def tearDown(self):
saving_lib._MEMORY_UPPER_BOUND = self.original_value
return super().tearDown()
def _test_inference_after_instantiation(self, model):
x_ref = np.random.random((2, 4))
y_ref = model(x_ref)
temp_filepath = os.path.join(self.get_temp_dir(), "my_model.keras")
model.save(temp_filepath)
loaded_model = saving_lib.load_model(temp_filepath)
self.assertFalse(model.compiled)
for w_ref, w in zip(model.variables, loaded_model.variables):
self.assertAllClose(w_ref, w)
self.assertAllClose(y_ref, loaded_model(x_ref))
@parameterized.named_parameters(
("subclassed", _get_subclassed_model),
("basic_sequential", _get_basic_sequential_model),
("basic_functional", _get_basic_functional_model),
("custom_sequential", _get_custom_sequential_model),
("custom_functional", _get_custom_functional_model),
("subclassed_functional", _get_subclassed_functional_model),
)
def test_inference_after_instantiation(self, model_fn):
model = model_fn(compile=False)
self._test_inference_after_instantiation(model)
# Test small model path
saving_lib._MEMORY_UPPER_BOUND = 1.0
self._test_inference_after_instantiation(model)
def _test_compile_preserved(self, model):
x_ref = np.random.random((2, 4))
y_ref = np.random.random((2, 1))
model.fit(x_ref, y_ref)
out_ref = model(x_ref)
ref_metrics = model.evaluate(x_ref, y_ref)
temp_filepath = os.path.join(self.get_temp_dir(), "my_model.keras")
model.save(temp_filepath)
loaded_model = saving_lib.load_model(temp_filepath)
self.assertTrue(model.compiled)
self.assertTrue(loaded_model.built)
for w_ref, w in zip(model.variables, loaded_model.variables):
self.assertAllClose(w_ref, w)
self.assertAllClose(out_ref, loaded_model(x_ref))
self.assertEqual(
model.optimizer.__class__, loaded_model.optimizer.__class__
)
self.assertEqual(
model.optimizer.get_config(), loaded_model.optimizer.get_config()
)
for w_ref, w in zip(
model.optimizer.variables, loaded_model.optimizer.variables
):
self.assertAllClose(w_ref, w)
new_metrics = loaded_model.evaluate(x_ref, y_ref)
for ref_m, m in zip(ref_metrics, new_metrics):
self.assertAllClose(ref_m, m)
@parameterized.named_parameters(
("subclassed", _get_subclassed_model),
("basic_sequential", _get_basic_sequential_model),
("basic_functional", _get_basic_functional_model),
("custom_sequential", _get_custom_sequential_model),
("custom_functional", _get_custom_functional_model),
("subclassed_functional", _get_subclassed_functional_model),
)
@pytest.mark.requires_trainable_backend
def test_compile_preserved(self, model_fn):
model = model_fn(compile=True)
self._test_compile_preserved(model)
# Test small model path
saving_lib._MEMORY_UPPER_BOUND = 1.0
self._test_compile_preserved(model)
def test_saving_preserve_unbuilt_state(self):
temp_filepath = os.path.join(self.get_temp_dir(), "my_model.keras")
subclassed_model = CustomModelX()
subclassed_model.save(temp_filepath)
loaded_model = saving_lib.load_model(temp_filepath)
self.assertEqual(subclassed_model.compiled, loaded_model.compiled)
self.assertFalse(subclassed_model.built)
self.assertFalse(loaded_model.built)
@pytest.mark.requires_trainable_backend
def test_saved_module_paths_and_class_names(self):
temp_filepath = os.path.join(self.get_temp_dir(), "my_model.keras")
subclassed_model = _get_subclassed_model()
x = np.random.random((100, 32))
y = np.random.random((100, 1))
subclassed_model.fit(x, y, epochs=1)
subclassed_model.save(temp_filepath)
with zipfile.ZipFile(temp_filepath, "r") as z:
with z.open(saving_lib._CONFIG_FILENAME, "r") as c:
config_json = c.read()
config_dict = json.loads(config_json)
self.assertEqual(
config_dict["registered_name"], "my_custom_package>CustomModelX"
)
self.assertEqual(
config_dict["compile_config"]["optimizer"],
keras.src.saving.serialize_keras_object(
keras.src.optimizers.get("adam")
),
)
self.assertEqual(
config_dict["compile_config"]["loss"]["config"],
"my_custom_package>my_mean_squared_error",
)
@pytest.mark.requires_trainable_backend
def test_saving_custom_assets_and_variables(self):
temp_filepath = os.path.join(self.get_temp_dir(), "my_model.keras")
model = ModelWithCustomSaving()
model.compile(
optimizer="adam",
loss="mse",
)
x = np.random.random((100, 32))
y = np.random.random((100, 1))
model.fit(x, y, epochs=1)
# Assert that the archive has not been saved.
self.assertFalse(os.path.exists(temp_filepath))
model.save(temp_filepath)
loaded_model = saving_lib.load_model(temp_filepath)
self.assertEqual(loaded_model.custom_dense.assets, ASSETS_DATA)
self.assertEqual(
loaded_model.custom_dense.stored_variables.tolist(),
VARIABLES_DATA.tolist(),
)
def _test_compile_overridden_warnings(self, model_type):
temp_filepath = os.path.join(self.get_temp_dir(), "my_model.keras")
model = (
CompileOverridingModel()
if model_type == "subclassed"
else CompileOverridingSequential(
[keras.layers.Embedding(4, 1), MyDense(1), MyDense(1)]
)
)
model.compile("sgd", "mse")
model.save(temp_filepath)
with mock.patch.object(warnings, "warn") as mock_warn:
saving_lib.load_model(temp_filepath)
if not mock_warn.call_args_list:
raise AssertionError("Did not warn.")
self.assertIn(
"`compile()` was not called as part of model loading "
"because the model's `compile()` method is custom. ",
mock_warn.call_args_list[0][0][0],
)
def test_compile_overridden_warnings_sequential(self):
self._test_compile_overridden_warnings("sequential")
def test_compile_overridden_warnings_subclassed(self):
self._test_compile_overridden_warnings("subclassed")
def test_metadata(self):
temp_filepath = Path(
os.path.join(self.get_temp_dir(), "my_model.keras")
)
model = CompileOverridingModel()
model.save(temp_filepath)
with zipfile.ZipFile(temp_filepath, "r") as z:
with z.open(saving_lib._METADATA_FILENAME, "r") as c:
metadata_json = c.read()
metadata = json.loads(metadata_json)
self.assertIn("keras_version", metadata)
self.assertIn("date_saved", metadata)
# def test_gfile_copy_local_called(self):
# temp_filepath = Path(
# os.path.join(self.get_temp_dir(), "my_model.keras")
# )
# model = CompileOverridingModel()
# with mock.patch(
# "re.match", autospec=True
# ) as mock_re_match, mock.patch(
# "tensorflow.compat.v2.io.file_utils.copy", autospec=True
# ) as mock_copy:
# # Mock Remote Path check to true to test gfile copy logic
# mock_re_match.return_value = True
# model.save(temp_filepath)
# mock_re_match.assert_called()
# mock_copy.assert_called()
# self.assertIn(str(temp_filepath), mock_re_match.call_args.args)
# self.assertIn(str(temp_filepath), mock_copy.call_args.args)
def test_save_load_weights_only(self):
temp_filepath = Path(
os.path.join(self.get_temp_dir(), "mymodel.weights.h5")
)
model = _get_basic_functional_model()
ref_input = np.random.random((2, 4))
ref_output = model.predict(ref_input)
saving_lib.save_weights_only(model, temp_filepath)
model = _get_basic_functional_model()
saving_lib.load_weights_only(model, temp_filepath)
self.assertAllClose(model.predict(ref_input), ref_output, atol=1e-6)
# Test with Model method
model = _get_basic_functional_model()
model.load_weights(temp_filepath)
self.assertAllClose(model.predict(ref_input), ref_output, atol=1e-6)
def test_save_weights_only_with_unbuilt_model(self):
temp_filepath = Path(
os.path.join(self.get_temp_dir(), "mymodel.weights.h5")
)
model = _get_subclassed_model()
with self.assertRaisesRegex(
ValueError, "You are saving a model that has not yet been built."
):
saving_lib.save_weights_only(model, temp_filepath)
def test_load_weights_only_with_unbuilt_model(self):
temp_filepath = Path(
os.path.join(self.get_temp_dir(), "mymodel.weights.h5")
)
model = _get_subclassed_model()
x = np.random.random((100, 32))
_ = model.predict(x) # Build the model by calling it on some data
saving_lib.save_weights_only(model, temp_filepath)
saving_lib.load_weights_only(model, temp_filepath)
new_model = _get_subclassed_model()
with self.assertRaisesRegex(
ValueError,
"You are loading weights into a model that has not yet been built.",
):
saving_lib.load_weights_only(new_model, temp_filepath)
def test_load_weights_only_with_keras_file(self):
# Test loading weights from whole saved model
temp_filepath = Path(os.path.join(self.get_temp_dir(), "mymodel.keras"))
model = _get_basic_functional_model()
ref_input = np.random.random((2, 4))
ref_output = model.predict(ref_input)
saving_lib.save_model(model, temp_filepath)
model = _get_basic_functional_model()
saving_lib.load_weights_only(model, temp_filepath)
self.assertAllClose(model.predict(ref_input), ref_output, atol=1e-6)
# Test with Model method
model = _get_basic_functional_model()
model.load_weights(temp_filepath)
self.assertAllClose(model.predict(ref_input), ref_output, atol=1e-6)
def test_save_weights_subclassed_functional(self):
# The subclassed and basic functional model should have the same
# weights structure.
temp_filepath = Path(
os.path.join(self.get_temp_dir(), "mymodel.weights.h5")
)
model = _get_basic_functional_model()
ref_input = np.random.random((2, 4))
ref_output = model.predict(ref_input)
# Test saving basic, loading subclassed.
saving_lib.save_weights_only(model, temp_filepath)
model = _get_subclassed_functional_model()
saving_lib.load_weights_only(model, temp_filepath)
self.assertAllClose(model.predict(ref_input), ref_output, atol=1e-6)
# Test saving subclassed, loading basic.
saving_lib.save_weights_only(model, temp_filepath)
model = _get_basic_functional_model()
saving_lib.load_weights_only(model, temp_filepath)
self.assertAllClose(model.predict(ref_input), ref_output, atol=1e-6)
@pytest.mark.requires_trainable_backend
def test_compile_arg(self):
temp_filepath = os.path.join(self.get_temp_dir(), "mymodel.keras")
model = _get_basic_functional_model()
model.compile("sgd", "mse")
model.fit(np.random.random((2, 4)), np.random.random((2, 1)))
saving_lib.save_model(model, temp_filepath)
model = saving_lib.load_model(temp_filepath)
self.assertEqual(model.compiled, True)
model = saving_lib.load_model(temp_filepath, compile=False)
self.assertEqual(model.compiled, False)
# def test_overwrite(self):
# temp_filepath = os.path.join(self.get_temp_dir(), "mymodel.keras")
# model = _get_basic_functional_model()
# model.save(temp_filepath)
# model.save(temp_filepath, overwrite=True)
# with self.assertRaises(EOFError):
# model.save(temp_filepath, overwrite=False)
# temp_filepath = os.path.join(
# self.get_temp_dir(), "mymodel.weights.h5"
# )
# model = _get_basic_functional_model()
# model.save_weights(temp_filepath)
# model.save_weights(temp_filepath, overwrite=True)
# with self.assertRaises(EOFError):
# model.save_weights(temp_filepath, overwrite=False)
def test_partial_load(self):
temp_filepath = os.path.join(self.get_temp_dir(), "mymodel.keras")
original_model = keras.Sequential(
[
keras.Input(shape=(3,), batch_size=2),
keras.layers.Dense(4),
keras.layers.Dense(5),
]
)
original_model.save(temp_filepath)
# Test with a model that has a differently shaped layer
new_model = keras.Sequential(
[
keras.Input(shape=(3,), batch_size=2),
keras.layers.Dense(4),
keras.layers.Dense(6),
]
)
new_layer_kernel_value = np.array(new_model.layers[1].kernel)
with self.assertRaisesRegex(ValueError, "must match"):
# Doesn't work by default
new_model.load_weights(temp_filepath)
# Now it works
new_model.load_weights(temp_filepath, skip_mismatch=True)
ref_weights = original_model.layers[0].get_weights()
new_weights = new_model.layers[0].get_weights()
self.assertEqual(len(ref_weights), len(new_weights))
for ref_w, w in zip(ref_weights, new_weights):
self.assertAllClose(ref_w, w)
self.assertAllClose(
np.array(new_model.layers[1].kernel), new_layer_kernel_value
)
# Test with a model that has a new layer at the end
new_model = keras.Sequential(
[
keras.Input(shape=(3,), batch_size=2),
keras.layers.Dense(4),
keras.layers.Dense(5),
keras.layers.Dense(5),
]
)
new_layer_kernel_value = np.array(new_model.layers[2].kernel)
with self.assertRaisesRegex(ValueError, "received 0 variables"):
# Doesn't work by default
new_model.load_weights(temp_filepath)
# Now it works
new_model.load_weights(temp_filepath, skip_mismatch=True)
for layer_index in [0, 1]:
ref_weights = original_model.layers[layer_index].get_weights()
new_weights = new_model.layers[layer_index].get_weights()
self.assertEqual(len(ref_weights), len(new_weights))
for ref_w, w in zip(ref_weights, new_weights):
self.assertAllClose(ref_w, w)
self.assertAllClose(
np.array(new_model.layers[2].kernel), new_layer_kernel_value
)
@pytest.mark.requires_trainable_backend
def test_save_to_fileobj(self):
model = keras.Sequential(
[keras.layers.Dense(1, input_shape=(1,)), keras.layers.Dense(1)]
)
model.compile(optimizer="adam", loss="mse")
out = BytesIO()
saving_lib.save_model(model, out)
out.seek(0)
model = saving_lib.load_model(out)
model.fit(np.array([1, 2]), np.array([1, 2]))
pred1 = model.predict(np.array([1, 2]))
out = BytesIO()
saving_lib.save_model(model, out)
out.seek(0)
new_model = saving_lib.load_model(out)
pred2 = new_model.predict(np.array([1, 2]))
self.assertAllClose(pred1, pred2, atol=1e-5)
@parameterized.named_parameters(
("high_memory_config", True),
("low_memory_config", False),
)
def test_save_model_exception_raised(self, is_memory_sufficient):
if is_memory_sufficient:
saving_lib._MEMORY_UPPER_BOUND = 0.5 # 50%
# Assume we have an error in `save_own_variables`.
class RaiseErrorLayer(keras.layers.Layer):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.dense = keras.layers.Dense(units)
def call(self, inputs):
return self.dense(inputs)
def save_own_variables(self, store):
raise ValueError
model = keras.Sequential([keras.Input([1]), RaiseErrorLayer(1)])
filepath = f"{self.get_temp_dir()}/model.keras"
with self.assertRaises(ValueError):
saving_lib.save_model(model, filepath)
# Ensure we don't have a bad "model.weights.h5" inside the zip file.
self.assertTrue(Path(filepath).exists())
with zipfile.ZipFile(filepath) as zf:
all_filenames = zf.namelist()
self.assertNotIn("model.weights.h5", all_filenames)
# Ensure we don't have any temporary files left.
self.assertLen(os.listdir(Path(filepath).parent), 1)
self.assertIn("model.keras", os.listdir(Path(filepath).parent))
@parameterized.named_parameters(
("high_memory_config", True),
("low_memory_config", False),
)
def test_load_model_exception_raised(self, is_memory_sufficient):
if is_memory_sufficient:
saving_lib._MEMORY_UPPER_BOUND = 0.5 # 50%
# Assume we have an error in `load_own_variables`.
class RaiseErrorLayer(keras.layers.Layer):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.dense = keras.layers.Dense(units)
def call(self, inputs):
return self.dense(inputs)
def load_own_variables(self, store):
raise ValueError
model = keras.Sequential([keras.Input([1]), RaiseErrorLayer(1)])
filepath = f"{self.get_temp_dir()}/model.keras"
saving_lib.save_model(model, filepath)
with self.assertRaises(ValueError):
saving_lib.load_model(
filepath, custom_objects={"RaiseErrorLayer": RaiseErrorLayer}
)
# Ensure we don't have any temporary files left.
self.assertLen(os.listdir(Path(filepath).parent), 1)
self.assertIn("model.keras", os.listdir(Path(filepath).parent))
def test_load_model_read_only_system(self):
model = keras.Sequential([keras.Input([1]), keras.layers.Dense(32)])
filepath = f"{self.get_temp_dir()}/model.keras"
saving_lib.save_model(model, filepath)
# Load the model correctly, regardless of whether an OSError occurs.
original_mode = os.stat(Path(filepath).parent).st_mode
os.chmod(Path(filepath).parent, mode=0o555)
model = saving_lib.load_model(filepath)
os.chmod(Path(filepath).parent, mode=original_mode)
# Ensure we don't have any temporary files left.
self.assertLen(os.listdir(Path(filepath).parent), 1)
self.assertIn("model.keras", os.listdir(Path(filepath).parent))
@pytest.mark.skipif(
backend.backend() == "jax",
reason="JAX backend doesn't support Python's multiprocessing",
)
@pytest.mark.skipif(
testing.tensorflow_uses_gpu() or testing.torch_uses_gpu(),
reason="This test doesn't support GPU",
)
def test_load_model_concurrently(self):
import multiprocessing as mp
model = keras.Sequential([keras.Input([1]), keras.layers.Dense(2)])
filepath = f"{self.get_temp_dir()}/model.keras"
saving_lib.save_model(model, filepath)
# Load the model concurrently.
results = []
with mp.Pool(4) as pool:
for i in range(4):
results.append(pool.apply_async(_load_model_fn, (filepath,)))
pool.close()
pool.join()
[r.get() for r in results] # No error occurs here
def test_load_model_containing_reused_layer(self):
# https://github.com/keras-team/keras/issues/20307
inputs = keras.Input((4,))
reused_layer = keras.layers.Dense(4)
x = reused_layer(inputs)
x = keras.layers.Dense(4)(x)
outputs = reused_layer(x)
model = keras.Model(inputs, outputs)
self.assertLen(model.layers, 3) # Input + 2 Dense layers
self._test_inference_after_instantiation(model)
@parameterized.named_parameters(
("efficientnet_b0_512", "efficientnet_b0", 1), # Only 1 sharded file.
("efficientnet_b0_10", "efficientnet_b0", 0.01),
)
def test_weights_sharding(self, model_name, max_shard_size):
from keras.src.applications import efficientnet
if backend.image_data_format() == "channels_last":
shape = (224, 224, 3)
else:
shape = (3, 224, 224)
if model_name == "efficientnet_b0":
model_fn = efficientnet.EfficientNetB0
temp_filepath = Path(
os.path.join(self.get_temp_dir(), "mymodel.weights.json")
)
model = model_fn(weights=None, input_shape=shape)
ref_input = np.random.random((1, *shape)).astype("float32")
ref_output = model.predict(ref_input)
# Save the sharded files.
saving_lib.save_weights_only(
model, temp_filepath, max_shard_size=max_shard_size
)
self.assertIn("mymodel.weights.json", os.listdir(temp_filepath.parent))
if max_shard_size == 1:
# 1 sharded file + 1 config file = 2.
self.assertLen(os.listdir(temp_filepath.parent), 2)
elif max_shard_size == 0.01:
# 3 sharded file + 1 config file = 4.
self.assertLen(os.listdir(temp_filepath.parent), 4)
with open(temp_filepath, "r") as f:
sharding_config = json.load(f)
self.assertIn("metadata", sharding_config)
self.assertIn("weight_map", sharding_config)
# Instantiate new model and load the sharded files.
model = model_fn(weights=None, input_shape=shape)
saving_lib.load_weights_only(model, temp_filepath)
self.assertAllClose(model.predict(ref_input), ref_output, atol=1e-6)
| SavingTest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/executors/aws_lambda/lambda_executor.py | {
"start": 2121,
"end": 23997
} | class ____(BaseExecutor):
"""
An Airflow Executor that submits tasks to AWS Lambda asynchronously.
When execute_async() is called, the executor invokes a specified AWS Lambda function (asynchronously)
with a payload that includes the task command and a unique task key.
The Lambda function writes its result directly to an SQS queue, which is then polled by this executor
to update task state in Airflow.
"""
if TYPE_CHECKING and AIRFLOW_V_3_0_PLUS:
# In the v3 path, we store workloads, not commands as strings.
# TODO: TaskSDK: move this type change into BaseExecutor
queued_tasks: dict[TaskInstanceKey, workloads.All] # type: ignore[assignment]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pending_tasks: deque = deque()
self.running_tasks: dict[str, TaskInstanceKey] = {}
self.lambda_function_name = conf.get(CONFIG_GROUP_NAME, AllLambdaConfigKeys.FUNCTION_NAME)
self.sqs_queue_url = conf.get(CONFIG_GROUP_NAME, AllLambdaConfigKeys.QUEUE_URL)
self.dlq_url = conf.get(CONFIG_GROUP_NAME, AllLambdaConfigKeys.DLQ_URL)
self.qualifier = conf.get(CONFIG_GROUP_NAME, AllLambdaConfigKeys.QUALIFIER, fallback=None)
# Maximum number of retries to invoke Lambda.
self.max_invoke_attempts = conf.get(
CONFIG_GROUP_NAME,
AllLambdaConfigKeys.MAX_INVOKE_ATTEMPTS,
)
self.attempts_since_last_successful_connection = 0
self.IS_BOTO_CONNECTION_HEALTHY = False
self.load_connections(check_connection=False)
def start(self):
"""Call this when the Executor is run for the first time by the scheduler."""
check_health = conf.getboolean(CONFIG_GROUP_NAME, AllLambdaConfigKeys.CHECK_HEALTH_ON_STARTUP)
if not check_health:
return
self.log.info("Starting Lambda Executor and determining health...")
try:
self.check_health()
except AirflowException:
self.log.error("Stopping the Airflow Scheduler from starting until the issue is resolved.")
raise
def check_health(self):
"""
Check the health of the Lambda and SQS connections.
For lambda: Use get_function to test if the lambda connection works and the function can be
described.
For SQS: Use get_queue_attributes is used as a close analog to describe to test if the SQS
connection is working.
"""
self.IS_BOTO_CONNECTION_HEALTHY = False
def _check_queue(queue_url):
sqs_get_queue_attrs_response = self.sqs_client.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["ApproximateNumberOfMessages"]
)
approx_num_msgs = sqs_get_queue_attrs_response.get("Attributes").get(
"ApproximateNumberOfMessages"
)
self.log.info(
"SQS connection is healthy and queue %s is present with %s messages.",
queue_url,
approx_num_msgs,
)
self.log.info("Checking Lambda and SQS connections")
try:
# Check Lambda health
lambda_get_response = self.lambda_client.get_function(FunctionName=self.lambda_function_name)
if self.lambda_function_name not in lambda_get_response["Configuration"]["FunctionName"]:
raise AirflowException("Lambda function %s not found.", self.lambda_function_name)
self.log.info(
"Lambda connection is healthy and function %s is present.", self.lambda_function_name
)
# Check SQS results queue
_check_queue(self.sqs_queue_url)
# Check SQS dead letter queue
_check_queue(self.dlq_url)
# If we reach this point, both connections are healthy and all resources are present
self.IS_BOTO_CONNECTION_HEALTHY = True
except Exception:
self.log.exception("Lambda Executor health check failed")
raise AirflowException(
"The Lambda executor will not be able to run Airflow tasks until the issue is addressed."
)
def load_connections(self, check_connection: bool = True):
"""
Retrieve the AWS connection via Hooks to leverage the Airflow connection system.
:param check_connection: If True, check the health of the connection after loading it.
"""
self.log.info("Loading Connections")
aws_conn_id = conf.get(CONFIG_GROUP_NAME, AllLambdaConfigKeys.AWS_CONN_ID)
region_name = conf.get(CONFIG_GROUP_NAME, AllLambdaConfigKeys.REGION_NAME, fallback=None)
self.sqs_client = SqsHook(aws_conn_id=aws_conn_id, region_name=region_name).conn
self.lambda_client = LambdaHook(aws_conn_id=aws_conn_id, region_name=region_name).conn
self.attempts_since_last_successful_connection += 1
self.last_connection_reload = timezone.utcnow()
if check_connection:
self.check_health()
self.attempts_since_last_successful_connection = 0
def sync(self):
"""
Sync the executor with the current state of tasks.
Check in on currently running tasks and attempt to run any new tasks that have been queued.
"""
if not self.IS_BOTO_CONNECTION_HEALTHY:
exponential_backoff_retry(
self.last_connection_reload,
self.attempts_since_last_successful_connection,
self.load_connections,
)
if not self.IS_BOTO_CONNECTION_HEALTHY:
return
try:
self.sync_running_tasks()
self.attempt_task_runs()
except (ClientError, NoCredentialsError) as error:
error_code = error.response["Error"]["Code"]
if error_code in INVALID_CREDENTIALS_EXCEPTIONS:
self.IS_BOTO_CONNECTION_HEALTHY = False
self.log.warning(
"AWS credentials are either missing or expired: %s.\nRetrying connection", error
)
except Exception:
self.log.exception("An error occurred while syncing tasks")
def queue_workload(self, workload: workloads.All, session: Session | None) -> None:
from airflow.executors import workloads
if not isinstance(workload, workloads.ExecuteTask):
raise RuntimeError(f"{type(self)} cannot handle workloads of type {type(workload)}")
ti = workload.ti
self.queued_tasks[ti.key] = workload
def _process_workloads(self, workloads: Sequence[workloads.All]) -> None:
from airflow.executors.workloads import ExecuteTask
for w in workloads:
if not isinstance(w, ExecuteTask):
raise RuntimeError(f"{type(self)} cannot handle workloads of type {type(w)}")
command = [w]
key = w.ti.key
queue = w.ti.queue
executor_config = w.ti.executor_config or {}
del self.queued_tasks[key]
self.execute_async(key=key, command=command, queue=queue, executor_config=executor_config) # type: ignore[arg-type]
self.running.add(key)
def execute_async(self, key: TaskInstanceKey, command: CommandType, queue=None, executor_config=None):
"""
Save the task to be executed in the next sync by inserting the commands into a queue.
:param key: A unique task key (typically a tuple identifying the task instance).
:param command: The shell command string to execute.
:param executor_config: (Unused) to keep the same signature as the base.
:param queue: (Unused) to keep the same signature as the base.
"""
if len(command) == 1:
from airflow.executors.workloads import ExecuteTask
if isinstance(command[0], ExecuteTask):
workload = command[0]
ser_input = workload.model_dump_json()
command = [
"python",
"-m",
"airflow.sdk.execution_time.execute_workload",
"--json-string",
ser_input,
]
else:
raise RuntimeError(
f"LambdaExecutor doesn't know how to handle workload of type: {type(command[0])}"
)
self.pending_tasks.append(
LambdaQueuedTask(
key, command, queue if queue else "", executor_config or {}, 1, timezone.utcnow()
)
)
def attempt_task_runs(self):
"""
Attempt to run tasks that are queued in the pending_tasks.
Each task is submitted to AWS Lambda with a payload containing the task key and command.
The task key is used to track the task's state in Airflow.
"""
queue_len = len(self.pending_tasks)
for _ in range(queue_len):
task_to_run = self.pending_tasks.popleft()
task_key = task_to_run.key
cmd = task_to_run.command
attempt_number = task_to_run.attempt_number
failure_reasons = []
ser_task_key = json.dumps(task_key._asdict())
payload = {
"task_key": ser_task_key,
"command": cmd,
"executor_config": task_to_run.executor_config,
}
if timezone.utcnow() < task_to_run.next_attempt_time:
self.pending_tasks.append(task_to_run)
continue
self.log.info("Submitting task %s to Lambda function %s", task_key, self.lambda_function_name)
try:
invoke_kwargs = {
"FunctionName": self.lambda_function_name,
"InvocationType": "Event",
"Payload": json.dumps(payload),
}
if self.qualifier:
invoke_kwargs["Qualifier"] = self.qualifier
response = self.lambda_client.invoke(**invoke_kwargs)
except NoCredentialsError:
self.pending_tasks.append(task_to_run)
raise
except ClientError as e:
error_code = e.response["Error"]["Code"]
if error_code in INVALID_CREDENTIALS_EXCEPTIONS:
self.pending_tasks.append(task_to_run)
raise
failure_reasons.append(str(e))
except Exception as e:
# Failed to even get a response back from the Boto3 API or something else went
# wrong. For any possible failure we want to add the exception reasons to the
# failure list so that it is logged to the user and most importantly the task is
# added back to the pending list to be retried later.
failure_reasons.append(str(e))
if failure_reasons:
# Make sure the number of attempts does not exceed max invoke attempts
if int(attempt_number) < int(self.max_invoke_attempts):
task_to_run.attempt_number += 1
task_to_run.next_attempt_time = timezone.utcnow() + calculate_next_attempt_delay(
attempt_number
)
self.pending_tasks.append(task_to_run)
else:
reasons_str = ", ".join(failure_reasons)
self.log.error(
"Lambda invoke %s has failed a maximum of %s times. Marking as failed. Reasons: %s",
task_key,
attempt_number,
reasons_str,
)
self.log_task_event(
event="lambda invoke failure",
ti_key=task_key,
extra=(
f"Task could not be queued after {attempt_number} attempts. "
f"Marking as failed. Reasons: {reasons_str}"
),
)
self.fail(task_key)
else:
status_code = response.get("StatusCode")
self.log.info("Invoked Lambda for task %s with status %s", task_key, status_code)
self.running_tasks[ser_task_key] = task_key
# Add the serialized task key as the info, this will be assigned on the ti as the external_executor_id
self.running_state(task_key, ser_task_key)
def sync_running_tasks(self):
"""
Poll the SQS queue for messages indicating task completion.
Each message is expected to contain a JSON payload with 'task_key' and 'return_code'.
Based on the return code, update the task state accordingly.
"""
if not len(self.running_tasks):
self.log.debug("No running tasks to process.")
return
self.process_queue(self.sqs_queue_url)
if self.dlq_url and self.running_tasks:
self.process_queue(self.dlq_url)
def process_queue(self, queue_url: str):
"""
Poll the SQS queue for messages indicating task completion.
Each message is expected to contain a JSON payload with 'task_key' and 'return_code'.
Based on the return code, update the task state accordingly.
"""
response = self.sqs_client.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=10,
)
# Pagination? Maybe we don't need it. But we don't always delete messages after viewing them so we
# could possibly accumulate a lot of messages in the queue and get stuck if we don't read bigger
# chunks and paginate.
messages = response.get("Messages", [])
# The keys that we validate in the messages below will be different depending on whether or not
# the message is from the dead letter queue or the main results queue.
message_keys = ("return_code", "task_key")
if messages and queue_url == self.dlq_url:
self.log.warning("%d messages received from the dead letter queue", len(messages))
message_keys = ("command", "task_key")
for message in messages:
delete_message = False
receipt_handle = message["ReceiptHandle"]
try:
body = json.loads(message["Body"])
except json.JSONDecodeError:
self.log.warning(
"Received a message from the queue that could not be parsed as JSON: %s",
message["Body"],
)
delete_message = True
# If the message is not already marked for deletion, check if it has the required keys.
if not delete_message and not all(key in body for key in message_keys):
self.log.warning(
"Message is not formatted correctly, %s and/or %s are missing: %s", *message_keys, body
)
delete_message = True
if delete_message:
self.log.warning("Deleting the message to avoid processing it again.")
self.sqs_client.delete_message(QueueUrl=queue_url, ReceiptHandle=receipt_handle)
continue
return_code = body.get("return_code")
ser_task_key = body.get("task_key")
# Fetch the real task key from the running_tasks dict, using the serialized task key.
try:
task_key = self.running_tasks[ser_task_key]
except KeyError:
self.log.debug(
"Received task %s from the queue which is not found in running tasks, it is likely "
"from another Lambda Executor sharing this queue or might be a stale message that needs "
"deleting manually. Marking the message as visible again.",
ser_task_key,
)
# Mark task as visible again in SQS so that another executor can pick it up.
self.sqs_client.change_message_visibility(
QueueUrl=queue_url,
ReceiptHandle=receipt_handle,
VisibilityTimeout=0,
)
continue
if task_key:
if return_code == 0:
self.success(task_key)
self.log.info(
"Successful Lambda invocation for task %s received from SQS queue.", task_key
)
else:
self.fail(task_key)
if queue_url == self.dlq_url and return_code is None:
# DLQ failure: AWS Lambda service could not complete the invocation after retries.
# This indicates a Lambda-level failure (timeout, memory limit, crash, etc.)
# where the function was unable to successfully execute to return a result.
self.log.error(
"DLQ message received: Lambda invocation for task: %s was unable to successfully execute. This likely indicates a Lambda-level failure (timeout, memory limit, crash, etc.).",
task_key,
)
else:
# In this case the Lambda likely started but failed at run time since we got a non-zero
# return code. We could consider retrying these tasks within the executor, because this _likely_
# means the Airflow task did not run to completion, however we can't be sure (maybe the
# lambda runtime code has a bug and is returning a non-zero when it actually passed?). So
# perhaps not retrying is the safest option.
self.log.debug(
"Lambda invocation for task: %s completed but the underlying Airflow task has returned a non-zero exit code %s",
task_key,
return_code,
)
# Remove the task from the tracking mapping.
self.running_tasks.pop(ser_task_key)
# Delete the message from the queue.
self.sqs_client.delete_message(QueueUrl=queue_url, ReceiptHandle=receipt_handle)
def try_adopt_task_instances(self, tis: Sequence[TaskInstance]) -> Sequence[TaskInstance]:
"""
Adopt task instances which have an external_executor_id (the serialized task key).
Anything that is not adopted will be cleared by the scheduler and becomes eligible for re-scheduling.
:param tis: The task instances to adopt.
"""
with Stats.timer("lambda_executor.adopt_task_instances.duration"):
adopted_tis: list[TaskInstance] = []
if serialized_task_keys := [
(ti, ti.external_executor_id) for ti in tis if ti.external_executor_id
]:
for ti, ser_task_key in serialized_task_keys:
try:
task_key = TaskInstanceKey.from_dict(json.loads(ser_task_key))
except Exception:
# If that task fails to deserialize, we should just skip it.
self.log.exception(
"Task failed to be adopted because the key could not be deserialized"
)
continue
self.running_tasks[ser_task_key] = task_key
adopted_tis.append(ti)
if adopted_tis:
tasks = [f"{task} in state {task.state}" for task in adopted_tis]
task_instance_str = "\n\t".join(tasks)
self.log.info(
"Adopted the following %d tasks from a dead executor:\n\t%s",
len(adopted_tis),
task_instance_str,
)
not_adopted_tis = [ti for ti in tis if ti not in adopted_tis]
return not_adopted_tis
def end(self, heartbeat_interval=10):
"""
End execution. Poll until all outstanding tasks are marked as completed.
This is a blocking call and async Lambda tasks can not be cancelled, so this will wait until
all tasks are either completed or the timeout is reached.
:param heartbeat_interval: The interval in seconds to wait between checks for task completion.
"""
self.log.info("Received signal to end, waiting for outstanding tasks to finish.")
time_to_wait = int(conf.get(CONFIG_GROUP_NAME, AllLambdaConfigKeys.END_WAIT_TIMEOUT))
start_time = timezone.utcnow()
while True:
if time_to_wait:
current_time = timezone.utcnow()
elapsed_time = (current_time - start_time).total_seconds()
if elapsed_time > time_to_wait:
self.log.warning(
"Timed out waiting for tasks to finish. Some tasks may not be handled gracefully"
" as the executor is force ending due to timeout."
)
break
self.sync()
if not self.running_tasks:
self.log.info("All tasks completed; executor ending.")
break
self.log.info("Waiting for %d task(s) to complete.", len(self.running_tasks))
time.sleep(heartbeat_interval)
def terminate(self):
"""Get called when the daemon receives a SIGTERM."""
self.log.warning("Terminating Lambda executor. In-flight tasks cannot be stopped.")
| AwsLambdaExecutor |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_replace.py | {
"start": 558,
"end": 54222
} | class ____:
def test_replace_inplace(self, datetime_frame, float_string_frame):
datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan
datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan
tsframe = datetime_frame.copy()
result = tsframe.replace(np.nan, 0, inplace=True)
assert result is tsframe
tm.assert_frame_equal(tsframe, datetime_frame.fillna(0))
# mixed type
mf = float_string_frame
mf.iloc[5:20, mf.columns.get_loc("foo")] = np.nan
mf.iloc[-10:, mf.columns.get_loc("A")] = np.nan
result = float_string_frame.replace(np.nan, 0)
expected = float_string_frame.copy()
expected["foo"] = expected["foo"].astype(object)
expected = expected.fillna(value=0)
tm.assert_frame_equal(result, expected)
tsframe = datetime_frame.copy()
result = tsframe.replace([np.nan], [0], inplace=True)
assert result is tsframe
tm.assert_frame_equal(tsframe, datetime_frame.fillna(0))
@pytest.mark.parametrize(
"to_replace,values,expected",
[
# lists of regexes and values
# list of [re1, re2, ..., reN] -> [v1, v2, ..., vN]
(
[r"\s*\.\s*", r"e|f|g"],
[np.nan, "crap"],
{
"a": ["a", "b", np.nan, np.nan],
"b": ["crap"] * 3 + ["h"],
"c": ["h", "crap", "l", "o"],
},
),
# list of [re1, re2, ..., reN] -> [re1, re2, .., reN]
(
[r"\s*(\.)\s*", r"(e|f|g)"],
[r"\1\1", r"\1_crap"],
{
"a": ["a", "b", "..", ".."],
"b": ["e_crap", "f_crap", "g_crap", "h"],
"c": ["h", "e_crap", "l", "o"],
},
),
# list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN
# or vN)]
(
[r"\s*(\.)\s*", r"e"],
[r"\1\1", r"crap"],
{
"a": ["a", "b", "..", ".."],
"b": ["crap", "f", "g", "h"],
"c": ["h", "crap", "l", "o"],
},
),
],
)
@pytest.mark.parametrize("inplace", [True, False])
@pytest.mark.parametrize("use_value_regex_args", [True, False])
def test_regex_replace_list_obj(
self, to_replace, values, expected, inplace, use_value_regex_args
):
df = DataFrame({"a": list("ab.."), "b": list("efgh"), "c": list("helo")})
if use_value_regex_args:
result = df.replace(value=values, regex=to_replace, inplace=inplace)
else:
result = df.replace(to_replace, values, regex=True, inplace=inplace)
if inplace:
assert result is df
expected = DataFrame(expected)
tm.assert_frame_equal(result, expected)
def test_regex_replace_list_mixed(self, mix_ab):
# mixed frame to make sure this doesn't break things
dfmix = DataFrame(mix_ab)
# lists of regexes and values
# list of [re1, re2, ..., reN] -> [v1, v2, ..., vN]
to_replace_res = [r"\s*\.\s*", r"a"]
values = [np.nan, "crap"]
mix2 = {"a": list(range(4)), "b": list("ab.."), "c": list("halo")}
dfmix2 = DataFrame(mix2)
res = dfmix2.replace(to_replace_res, values, regex=True)
expec = DataFrame(
{
"a": mix2["a"],
"b": ["crap", "b", np.nan, np.nan],
"c": ["h", "crap", "l", "o"],
}
)
tm.assert_frame_equal(res, expec)
# list of [re1, re2, ..., reN] -> [re1, re2, .., reN]
to_replace_res = [r"\s*(\.)\s*", r"(a|b)"]
values = [r"\1\1", r"\1_crap"]
res = dfmix.replace(to_replace_res, values, regex=True)
expec = DataFrame({"a": mix_ab["a"], "b": ["a_crap", "b_crap", "..", ".."]})
tm.assert_frame_equal(res, expec)
# list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN
# or vN)]
to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"]
values = [r"\1\1", r"crap", r"\1_crap"]
res = dfmix.replace(to_replace_res, values, regex=True)
expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]})
tm.assert_frame_equal(res, expec)
to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"]
values = [r"\1\1", r"crap", r"\1_crap"]
res = dfmix.replace(regex=to_replace_res, value=values)
expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]})
tm.assert_frame_equal(res, expec)
def test_regex_replace_list_mixed_inplace(self, mix_ab):
dfmix = DataFrame(mix_ab)
# the same inplace
# lists of regexes and values
# list of [re1, re2, ..., reN] -> [v1, v2, ..., vN]
to_replace_res = [r"\s*\.\s*", r"a"]
values = [np.nan, "crap"]
res = dfmix.copy()
result = res.replace(to_replace_res, values, inplace=True, regex=True)
assert result is res
expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b", np.nan, np.nan]})
tm.assert_frame_equal(res, expec)
# list of [re1, re2, ..., reN] -> [re1, re2, .., reN]
to_replace_res = [r"\s*(\.)\s*", r"(a|b)"]
values = [r"\1\1", r"\1_crap"]
res = dfmix.copy()
result = res.replace(to_replace_res, values, inplace=True, regex=True)
assert result is res
expec = DataFrame({"a": mix_ab["a"], "b": ["a_crap", "b_crap", "..", ".."]})
tm.assert_frame_equal(res, expec)
# list of [re1, re2, ..., reN] -> [(re1 or v1), (re2 or v2), ..., (reN
# or vN)]
to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"]
values = [r"\1\1", r"crap", r"\1_crap"]
res = dfmix.copy()
result = res.replace(to_replace_res, values, inplace=True, regex=True)
assert result is res
expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]})
tm.assert_frame_equal(res, expec)
to_replace_res = [r"\s*(\.)\s*", r"a", r"(b)"]
values = [r"\1\1", r"crap", r"\1_crap"]
res = dfmix.copy()
result = res.replace(regex=to_replace_res, value=values, inplace=True)
assert result is res
expec = DataFrame({"a": mix_ab["a"], "b": ["crap", "b_crap", "..", ".."]})
tm.assert_frame_equal(res, expec)
def test_regex_replace_dict_mixed(self, mix_abc):
dfmix = DataFrame(mix_abc)
# dicts
# single dict {re1: v1}, search the whole frame
# need test for this...
# list of dicts {re1: v1, re2: v2, ..., re3: v3}, search the whole
# frame
res = dfmix.replace({"b": r"\s*\.\s*"}, {"b": np.nan}, regex=True)
res2 = dfmix.copy()
result = res2.replace(
{"b": r"\s*\.\s*"}, {"b": np.nan}, inplace=True, regex=True
)
assert result is res2
expec = DataFrame(
{"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]}
)
tm.assert_frame_equal(res, expec)
tm.assert_frame_equal(res2, expec)
# list of dicts {re1: re11, re2: re12, ..., reN: re1N}, search the
# whole frame
res = dfmix.replace({"b": r"\s*(\.)\s*"}, {"b": r"\1ty"}, regex=True)
res2 = dfmix.copy()
result = res2.replace(
{"b": r"\s*(\.)\s*"}, {"b": r"\1ty"}, inplace=True, regex=True
)
assert result is res2
expec = DataFrame(
{"a": mix_abc["a"], "b": ["a", "b", ".ty", ".ty"], "c": mix_abc["c"]}
)
tm.assert_frame_equal(res, expec)
tm.assert_frame_equal(res2, expec)
res = dfmix.replace(regex={"b": r"\s*(\.)\s*"}, value={"b": r"\1ty"})
res2 = dfmix.copy()
result = res2.replace(
regex={"b": r"\s*(\.)\s*"}, value={"b": r"\1ty"}, inplace=True
)
assert result is res2
expec = DataFrame(
{"a": mix_abc["a"], "b": ["a", "b", ".ty", ".ty"], "c": mix_abc["c"]}
)
tm.assert_frame_equal(res, expec)
tm.assert_frame_equal(res2, expec)
# scalar -> dict
# to_replace regex, {value: value}
expec = DataFrame(
{"a": mix_abc["a"], "b": [np.nan, "b", ".", "."], "c": mix_abc["c"]}
)
res = dfmix.replace("a", {"b": np.nan}, regex=True)
res2 = dfmix.copy()
result = res2.replace("a", {"b": np.nan}, regex=True, inplace=True)
assert result is res2
tm.assert_frame_equal(res, expec)
tm.assert_frame_equal(res2, expec)
res = dfmix.replace("a", {"b": np.nan}, regex=True)
res2 = dfmix.copy()
result = res2.replace(regex="a", value={"b": np.nan}, inplace=True)
assert result is res2
expec = DataFrame(
{"a": mix_abc["a"], "b": [np.nan, "b", ".", "."], "c": mix_abc["c"]}
)
tm.assert_frame_equal(res, expec)
tm.assert_frame_equal(res2, expec)
def test_regex_replace_dict_nested(self, mix_abc):
# nested dicts will not work until this is implemented for Series
dfmix = DataFrame(mix_abc)
res = dfmix.replace({"b": {r"\s*\.\s*": np.nan}}, regex=True)
res2 = dfmix.copy()
res4 = dfmix.copy()
result = res2.replace({"b": {r"\s*\.\s*": np.nan}}, inplace=True, regex=True)
assert result is res2
res3 = dfmix.replace(regex={"b": {r"\s*\.\s*": np.nan}})
result = res4.replace(regex={"b": {r"\s*\.\s*": np.nan}}, inplace=True)
assert result is res4
expec = DataFrame(
{"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]}
)
tm.assert_frame_equal(res, expec)
tm.assert_frame_equal(res2, expec)
tm.assert_frame_equal(res3, expec)
tm.assert_frame_equal(res4, expec)
def test_regex_replace_dict_nested_non_first_character(
self, any_string_dtype, using_infer_string
):
# GH 25259
dtype = any_string_dtype
df = DataFrame({"first": ["abc", "bca", "cab"]}, dtype=dtype)
result = df.replace({"a": "."}, regex=True)
expected = DataFrame({"first": [".bc", "bc.", "c.b"]}, dtype=dtype)
tm.assert_frame_equal(result, expected)
def test_regex_replace_dict_nested_gh4115(self):
df = DataFrame(
{"Type": Series(["Q", "T", "Q", "Q", "T"], dtype=object), "tmp": 2}
)
expected = DataFrame({"Type": Series([0, 1, 0, 0, 1], dtype=object), "tmp": 2})
result = df.replace({"Type": {"Q": 0, "T": 1}})
tm.assert_frame_equal(result, expected)
def test_regex_replace_list_to_scalar(self, mix_abc):
df = DataFrame(mix_abc)
expec = DataFrame(
{
"a": mix_abc["a"],
"b": Series([np.nan] * 4, dtype="str"),
"c": [np.nan, np.nan, np.nan, "d"],
}
)
res = df.replace([r"\s*\.\s*", "a|b"], np.nan, regex=True)
res2 = df.copy()
res3 = df.copy()
result = res2.replace([r"\s*\.\s*", "a|b"], np.nan, regex=True, inplace=True)
assert result is res2
result = res3.replace(regex=[r"\s*\.\s*", "a|b"], value=np.nan, inplace=True)
assert result is res3
tm.assert_frame_equal(res, expec)
tm.assert_frame_equal(res2, expec)
tm.assert_frame_equal(res3, expec)
def test_regex_replace_str_to_numeric(self, mix_abc):
# what happens when you try to replace a numeric value with a regex?
df = DataFrame(mix_abc)
res = df.replace(r"\s*\.\s*", 0, regex=True)
res2 = df.copy()
result = res2.replace(r"\s*\.\s*", 0, inplace=True, regex=True)
assert result is res2
res3 = df.copy()
result = res3.replace(regex=r"\s*\.\s*", value=0, inplace=True)
assert result is res3
expec = DataFrame({"a": mix_abc["a"], "b": ["a", "b", 0, 0], "c": mix_abc["c"]})
expec["c"] = expec["c"].astype(object)
tm.assert_frame_equal(res, expec)
tm.assert_frame_equal(res2, expec)
tm.assert_frame_equal(res3, expec)
def test_regex_replace_regex_list_to_numeric(self, mix_abc):
df = DataFrame(mix_abc)
res = df.replace([r"\s*\.\s*", "b"], 0, regex=True)
res2 = df.copy()
result = res2.replace([r"\s*\.\s*", "b"], 0, regex=True, inplace=True)
assert result is res2
res3 = df.copy()
result = res3.replace(regex=[r"\s*\.\s*", "b"], value=0, inplace=True)
assert result is res3
expec = DataFrame(
{"a": mix_abc["a"], "b": ["a", 0, 0, 0], "c": ["a", 0, np.nan, "d"]}
)
tm.assert_frame_equal(res, expec)
tm.assert_frame_equal(res2, expec)
tm.assert_frame_equal(res3, expec)
def test_regex_replace_series_of_regexes(self, mix_abc):
df = DataFrame(mix_abc)
s1 = Series({"b": r"\s*\.\s*"})
s2 = Series({"b": np.nan})
res = df.replace(s1, s2, regex=True)
res2 = df.copy()
result = res2.replace(s1, s2, inplace=True, regex=True)
assert result is res2
res3 = df.copy()
result = res3.replace(regex=s1, value=s2, inplace=True)
assert result is res3
expec = DataFrame(
{"a": mix_abc["a"], "b": ["a", "b", np.nan, np.nan], "c": mix_abc["c"]}
)
tm.assert_frame_equal(res, expec)
tm.assert_frame_equal(res2, expec)
tm.assert_frame_equal(res3, expec)
def test_regex_replace_numeric_to_object_conversion(self, mix_abc):
df = DataFrame(mix_abc)
expec = DataFrame({"a": ["a", 1, 2, 3], "b": mix_abc["b"], "c": mix_abc["c"]})
res = df.replace(0, "a")
tm.assert_frame_equal(res, expec)
assert res.a.dtype == np.object_
@pytest.mark.parametrize(
"to_replace", [{"": np.nan, ",": ""}, {",": "", "": np.nan}]
)
def test_joint_simple_replace_and_regex_replace(self, to_replace):
# GH-39338
df = DataFrame(
{
"col1": ["1,000", "a", "3"],
"col2": ["a", "", "b"],
"col3": ["a", "b", "c"],
}
)
result = df.replace(regex=to_replace)
expected = DataFrame(
{
"col1": ["1000", "a", "3"],
"col2": ["a", np.nan, "b"],
"col3": ["a", "b", "c"],
}
)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("metachar", ["[]", "()", r"\d", r"\w", r"\s"])
def test_replace_regex_metachar(self, metachar):
df = DataFrame({"a": [metachar, "else"]})
result = df.replace({"a": {metachar: "paren"}})
expected = DataFrame({"a": ["paren", "else"]})
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"data,to_replace,expected",
[
(["xax", "xbx"], {"a": "c", "b": "d"}, ["xcx", "xdx"]),
(["d", "", ""], {r"^\s*$": pd.NA}, ["d", pd.NA, pd.NA]),
],
)
def test_regex_replace_string_types(
self,
data,
to_replace,
expected,
frame_or_series,
any_string_dtype,
using_infer_string,
request,
):
# GH-41333, GH-35977
dtype = any_string_dtype
obj = frame_or_series(data, dtype=dtype)
result = obj.replace(to_replace, regex=True)
expected = frame_or_series(expected, dtype=dtype)
tm.assert_equal(result, expected)
def test_replace(self, datetime_frame):
datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan
datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan
zero_filled = datetime_frame.replace(np.nan, -1e8)
tm.assert_frame_equal(zero_filled, datetime_frame.fillna(-1e8))
tm.assert_frame_equal(zero_filled.replace(-1e8, np.nan), datetime_frame)
datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan
datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan
datetime_frame.loc[datetime_frame.index[:5], "B"] = -1e8
# empty
df = DataFrame(index=["a", "b"])
tm.assert_frame_equal(df, df.replace(5, 7))
# GH 11698
# test for mixed data types.
df = DataFrame(
[("-", pd.to_datetime("20150101")), ("a", pd.to_datetime("20150102"))]
)
df1 = df.replace("-", np.nan)
expected_df = DataFrame(
[(np.nan, pd.to_datetime("20150101")), ("a", pd.to_datetime("20150102"))]
)
tm.assert_frame_equal(df1, expected_df)
def test_replace_list(self):
obj = {"a": list("ab.."), "b": list("efgh"), "c": list("helo")}
dfobj = DataFrame(obj)
# lists of regexes and values
# list of [v1, v2, ..., vN] -> [v1, v2, ..., vN]
to_replace_res = [r".", r"e"]
values = [np.nan, "crap"]
res = dfobj.replace(to_replace_res, values)
expec = DataFrame(
{
"a": ["a", "b", np.nan, np.nan],
"b": ["crap", "f", "g", "h"],
"c": ["h", "crap", "l", "o"],
}
)
tm.assert_frame_equal(res, expec)
# list of [v1, v2, ..., vN] -> [v1, v2, .., vN]
to_replace_res = [r".", r"f"]
values = [r"..", r"crap"]
res = dfobj.replace(to_replace_res, values)
expec = DataFrame(
{
"a": ["a", "b", "..", ".."],
"b": ["e", "crap", "g", "h"],
"c": ["h", "e", "l", "o"],
}
)
tm.assert_frame_equal(res, expec)
def test_replace_with_empty_list(self, frame_or_series):
# GH 21977
ser = Series([["a", "b"], [], np.nan, [1]])
obj = DataFrame({"col": ser})
obj = tm.get_obj(obj, frame_or_series)
expected = obj
result = obj.replace([], np.nan)
tm.assert_equal(result, expected)
# GH 19266
msg = (
"NumPy boolean array indexing assignment cannot assign {size} "
"input values to the 1 output values where the mask is true"
)
with pytest.raises(ValueError, match=msg.format(size=0)):
obj.replace({np.nan: []})
with pytest.raises(ValueError, match=msg.format(size=2)):
obj.replace({np.nan: ["dummy", "alt"]})
def test_replace_series_dict(self):
# from GH 3064
df = DataFrame({"zero": {"a": 0.0, "b": 1}, "one": {"a": 2.0, "b": 0}})
result = df.replace(0, {"zero": 0.5, "one": 1.0})
expected = DataFrame({"zero": {"a": 0.5, "b": 1}, "one": {"a": 2.0, "b": 1.0}})
tm.assert_frame_equal(result, expected)
result = df.replace(0, df.mean())
tm.assert_frame_equal(result, expected)
# series to series/dict
df = DataFrame({"zero": {"a": 0.0, "b": 1}, "one": {"a": 2.0, "b": 0}})
s = Series({"zero": 0.0, "one": 2.0})
result = df.replace(s, {"zero": 0.5, "one": 1.0})
expected = DataFrame({"zero": {"a": 0.5, "b": 1}, "one": {"a": 1.0, "b": 0.0}})
tm.assert_frame_equal(result, expected)
result = df.replace(s, df.mean())
tm.assert_frame_equal(result, expected)
def test_replace_convert(self, any_string_dtype):
# gh 3907 (pandas >= 3.0 no longer converts dtypes)
df = DataFrame(
[["foo", "bar", "bah"], ["bar", "foo", "bah"]], dtype=any_string_dtype
)
m = {"foo": 1, "bar": 2, "bah": 3}
rep = df.replace(m)
assert (rep.dtypes == object).all()
def test_replace_mixed(self, float_string_frame):
mf = float_string_frame
mf.iloc[5:20, mf.columns.get_loc("foo")] = np.nan
mf.iloc[-10:, mf.columns.get_loc("A")] = np.nan
result = float_string_frame.replace(np.nan, -18)
expected = float_string_frame.copy()
expected["foo"] = expected["foo"].astype(object)
expected = expected.fillna(value=-18)
tm.assert_frame_equal(result, expected)
expected2 = float_string_frame.copy()
expected2["foo"] = expected2["foo"].astype(object)
tm.assert_frame_equal(result.replace(-18, np.nan), expected2)
result = float_string_frame.replace(np.nan, -1e8)
expected = float_string_frame.copy()
expected["foo"] = expected["foo"].astype(object)
expected = expected.fillna(value=-1e8)
tm.assert_frame_equal(result, expected)
expected2 = float_string_frame.copy()
expected2["foo"] = expected2["foo"].astype(object)
tm.assert_frame_equal(result.replace(-1e8, np.nan), expected2)
def test_replace_mixed_int_block_upcasting(self):
# int block upcasting
df = DataFrame(
{
"A": Series([1.0, 2.0], dtype="float64"),
"B": Series([0, 1], dtype="int64"),
}
)
expected = DataFrame(
{
"A": Series([1.0, 2.0], dtype="float64"),
"B": Series([0.5, 1], dtype="float64"),
}
)
result = df.replace(0, 0.5)
tm.assert_frame_equal(result, expected)
result = df.replace(0, 0.5, inplace=True)
assert result is df
tm.assert_frame_equal(df, expected)
def test_replace_mixed_int_block_splitting(self):
# int block splitting
df = DataFrame(
{
"A": Series([1.0, 2.0], dtype="float64"),
"B": Series([0, 1], dtype="int64"),
"C": Series([1, 2], dtype="int64"),
}
)
expected = DataFrame(
{
"A": Series([1.0, 2.0], dtype="float64"),
"B": Series([0.5, 1], dtype="float64"),
"C": Series([1, 2], dtype="int64"),
}
)
result = df.replace(0, 0.5)
tm.assert_frame_equal(result, expected)
def test_replace_mixed2(self):
# to object block upcasting
df = DataFrame(
{
"A": Series([1.0, 2.0], dtype="float64"),
"B": Series([0, 1], dtype="int64"),
}
)
expected = DataFrame(
{
"A": Series([1, "foo"], dtype="object"),
"B": Series([0, 1], dtype="int64"),
}
)
result = df.replace(2, "foo")
tm.assert_frame_equal(result, expected)
expected = DataFrame(
{
"A": Series(["foo", "bar"], dtype="object"),
"B": Series([0, "foo"], dtype="object"),
}
)
result = df.replace([1, 2], ["foo", "bar"])
tm.assert_frame_equal(result, expected)
def test_replace_mixed3(self):
# test case from
df = DataFrame(
{"A": Series([3, 0], dtype="int64"), "B": Series([0, 3], dtype="int64")}
)
result = df.replace(3, df.mean().to_dict())
expected = df.copy().astype("float64")
m = df.mean()
expected.iloc[0, 0] = m.iloc[0]
expected.iloc[1, 1] = m.iloc[1]
tm.assert_frame_equal(result, expected)
def test_replace_nullable_int_with_string_doesnt_cast(self):
# GH#25438 don't cast df['a'] to float64
df = DataFrame({"a": [1, 2, 3, pd.NA], "b": ["some", "strings", "here", "he"]})
df["a"] = df["a"].astype("Int64")
res = df.replace("", np.nan)
tm.assert_series_equal(res["a"], df["a"])
@pytest.mark.parametrize("dtype", ["boolean", "Int64", "Float64"])
def test_replace_with_nullable_column(self, dtype):
# GH-44499
nullable_ser = Series([1, 0, 1], dtype=dtype)
df = DataFrame({"A": ["A", "B", "x"], "B": nullable_ser})
result = df.replace("x", "X")
expected = DataFrame({"A": ["A", "B", "X"], "B": nullable_ser})
tm.assert_frame_equal(result, expected)
def test_replace_simple_nested_dict(self):
df = DataFrame({"col": range(1, 5)})
expected = DataFrame({"col": ["a", 2, 3, "b"]})
result = df.replace({"col": {1: "a", 4: "b"}})
tm.assert_frame_equal(expected, result)
# in this case, should be the same as the not nested version
result = df.replace({1: "a", 4: "b"})
tm.assert_frame_equal(expected, result)
def test_replace_simple_nested_dict_with_nonexistent_value(self):
df = DataFrame({"col": range(1, 5)})
expected = DataFrame({"col": ["a", 2, 3, "b"]})
result = df.replace({-1: "-", 1: "a", 4: "b"})
tm.assert_frame_equal(expected, result)
result = df.replace({"col": {-1: "-", 1: "a", 4: "b"}})
tm.assert_frame_equal(expected, result)
def test_replace_NA_with_None(self):
# gh-45601
df = DataFrame({"value": [42, pd.NA]}, dtype="Int64")
result = df.replace({pd.NA: None})
expected = DataFrame({"value": [42, None]}, dtype=object)
tm.assert_frame_equal(result, expected)
def test_replace_NAT_with_None(self):
# gh-45836
df = DataFrame([pd.NaT, pd.NaT])
result = df.replace({pd.NaT: None, np.nan: None})
expected = DataFrame([None, None])
tm.assert_frame_equal(result, expected)
def test_replace_with_None_keeps_categorical(self):
# gh-46634
cat_series = Series(["b", "b", "b", "d"], dtype="category")
df = DataFrame(
{
"id": Series([5, 4, 3, 2], dtype="float64"),
"col": cat_series,
}
)
result = df.replace({3: None})
expected = DataFrame(
{
"id": Series([5.0, 4.0, None, 2.0], dtype="object"),
"col": cat_series,
}
)
tm.assert_frame_equal(result, expected)
def test_replace_all_NA(self):
# GH#60688
df = DataFrame({"ticker": ["#1234#"], "name": [None]})
result = df.replace({col: {r"^#": "$"} for col in df.columns}, regex=True)
expected = DataFrame({"ticker": ["$1234#"], "name": [None]})
tm.assert_frame_equal(result, expected)
def test_replace_value_is_none(self, datetime_frame):
orig_value = datetime_frame.iloc[0, 0]
orig2 = datetime_frame.iloc[1, 0]
datetime_frame.iloc[0, 0] = np.nan
datetime_frame.iloc[1, 0] = 1
result = datetime_frame.replace(to_replace={np.nan: 0})
expected = datetime_frame.T.replace(to_replace={np.nan: 0}).T
tm.assert_frame_equal(result, expected)
result = datetime_frame.replace(to_replace={np.nan: 0, 1: -1e8})
tsframe = datetime_frame.copy()
tsframe.iloc[0, 0] = 0
tsframe.iloc[1, 0] = -1e8
expected = tsframe
tm.assert_frame_equal(expected, result)
datetime_frame.iloc[0, 0] = orig_value
datetime_frame.iloc[1, 0] = orig2
def test_replace_for_new_dtypes(self, datetime_frame):
# dtypes
tsframe = datetime_frame.copy().astype(np.float32)
tsframe.loc[tsframe.index[:5], "A"] = np.nan
tsframe.loc[tsframe.index[-5:], "A"] = np.nan
zero_filled = tsframe.replace(np.nan, -1e8)
tm.assert_frame_equal(zero_filled, tsframe.fillna(-1e8))
tm.assert_frame_equal(zero_filled.replace(-1e8, np.nan), tsframe)
tsframe.loc[tsframe.index[:5], "A"] = np.nan
tsframe.loc[tsframe.index[-5:], "A"] = np.nan
tsframe.loc[tsframe.index[:5], "B"] = np.nan
@pytest.mark.parametrize(
"frame, to_replace, value, expected",
[
(DataFrame({"ints": [1, 2, 3]}), 1, 0, DataFrame({"ints": [0, 2, 3]})),
(
DataFrame({"ints": [1, 2, 3]}, dtype=np.int32),
1,
0,
DataFrame({"ints": [0, 2, 3]}, dtype=np.int32),
),
(
DataFrame({"ints": [1, 2, 3]}, dtype=np.int16),
1,
0,
DataFrame({"ints": [0, 2, 3]}, dtype=np.int16),
),
(
DataFrame({"bools": [True, False, True]}),
False,
True,
DataFrame({"bools": [True, True, True]}),
),
(
DataFrame({"complex": [1j, 2j, 3j]}),
1j,
0,
DataFrame({"complex": [0j, 2j, 3j]}),
),
(
DataFrame(
{
"datetime64": Index(
[
datetime(2018, 5, 28),
datetime(2018, 7, 28),
datetime(2018, 5, 28),
]
)
}
),
datetime(2018, 5, 28),
datetime(2018, 7, 28),
DataFrame({"datetime64": Index([datetime(2018, 7, 28)] * 3)}),
),
# GH 20380
(
DataFrame({"dt": [datetime(3017, 12, 20)], "str": ["foo"]}),
"foo",
"bar",
DataFrame({"dt": [datetime(3017, 12, 20)], "str": ["bar"]}),
),
(
DataFrame(
{
"A": date_range(
"20130101", periods=3, tz="US/Eastern", unit="ns"
),
"B": [0, np.nan, 2],
}
),
Timestamp("20130102", tz="US/Eastern"),
Timestamp("20130104", tz="US/Eastern"),
DataFrame(
{
"A": pd.DatetimeIndex(
[
Timestamp("20130101", tz="US/Eastern"),
Timestamp("20130104", tz="US/Eastern"),
Timestamp("20130103", tz="US/Eastern"),
]
).as_unit("ns"),
"B": [0, np.nan, 2],
}
),
),
# GH 35376
(
DataFrame([[1, 1.0], [2, 2.0]]),
1.0,
5,
DataFrame([[5, 5.0], [2, 2.0]]),
),
(
DataFrame([[1, 1.0], [2, 2.0]]),
1,
5,
DataFrame([[5, 5.0], [2, 2.0]]),
),
(
DataFrame([[1, 1.0], [2, 2.0]]),
1.0,
5.0,
DataFrame([[5, 5.0], [2, 2.0]]),
),
(
DataFrame([[1, 1.0], [2, 2.0]]),
1,
5.0,
DataFrame([[5, 5.0], [2, 2.0]]),
),
],
)
def test_replace_dtypes(self, frame, to_replace, value, expected):
result = frame.replace(to_replace, value)
tm.assert_frame_equal(result, expected)
def test_replace_input_formats_listlike(self):
# both dicts
to_rep = {"A": np.nan, "B": 0, "C": ""}
values = {"A": 0, "B": -1, "C": "missing"}
df = DataFrame(
{"A": [np.nan, 0, np.inf], "B": [0, 2, 5], "C": ["", "asdf", "fd"]}
)
filled = df.replace(to_rep, values)
expected = {k: v.replace(to_rep[k], values[k]) for k, v in df.items()}
tm.assert_frame_equal(filled, DataFrame(expected))
result = df.replace([0, 2, 5], [5, 2, 0])
expected = DataFrame(
{"A": [np.nan, 5, np.inf], "B": [5, 2, 0], "C": ["", "asdf", "fd"]}
)
tm.assert_frame_equal(result, expected)
# scalar to dict
values = {"A": 0, "B": -1, "C": "missing"}
df = DataFrame(
{"A": [np.nan, 0, np.nan], "B": [0, 2, 5], "C": ["", "asdf", "fd"]}
)
filled = df.replace(np.nan, values)
expected = {k: v.replace(np.nan, values[k]) for k, v in df.items()}
tm.assert_frame_equal(filled, DataFrame(expected))
# list to list
to_rep = [np.nan, 0, ""]
values = [-2, -1, "missing"]
result = df.replace(to_rep, values)
expected = df.copy()
for rep, value in zip(to_rep, values):
result = expected.replace(rep, value, inplace=True)
assert result is expected
tm.assert_frame_equal(result, expected)
msg = r"Replacement lists must match in length\. Expecting 3 got 2"
with pytest.raises(ValueError, match=msg):
df.replace(to_rep, values[1:])
def test_replace_input_formats_scalar(self):
df = DataFrame(
{"A": [np.nan, 0, np.inf], "B": [0, 2, 5], "C": ["", "asdf", "fd"]}
)
# dict to scalar
to_rep = {"A": np.nan, "B": 0, "C": ""}
filled = df.replace(to_rep, 0)
expected = {k: v.replace(to_rep[k], 0) for k, v in df.items()}
tm.assert_frame_equal(filled, DataFrame(expected))
msg = "value argument must be scalar, dict, or Series"
with pytest.raises(TypeError, match=msg):
df.replace(to_rep, [np.nan, 0, ""])
# list to scalar
to_rep = [np.nan, 0, ""]
result = df.replace(to_rep, -1)
expected = df.copy()
for rep in to_rep:
result = expected.replace(rep, -1, inplace=True)
assert result is expected
tm.assert_frame_equal(result, expected)
def test_replace_limit(self):
# TODO
pass
def test_replace_dict_no_regex(self, any_string_dtype):
answer = Series(
{
0: "Strongly Agree",
1: "Agree",
2: "Neutral",
3: "Disagree",
4: "Strongly Disagree",
},
dtype=any_string_dtype,
)
weights = {
"Agree": 4,
"Disagree": 2,
"Neutral": 3,
"Strongly Agree": 5,
"Strongly Disagree": 1,
}
expected = Series({0: 5, 1: 4, 2: 3, 3: 2, 4: 1}, dtype=object)
result = answer.replace(weights)
tm.assert_series_equal(result, expected)
def test_replace_series_no_regex(self, any_string_dtype):
answer = Series(
{
0: "Strongly Agree",
1: "Agree",
2: "Neutral",
3: "Disagree",
4: "Strongly Disagree",
},
dtype=any_string_dtype,
)
weights = Series(
{
"Agree": 4,
"Disagree": 2,
"Neutral": 3,
"Strongly Agree": 5,
"Strongly Disagree": 1,
}
)
expected = Series({0: 5, 1: 4, 2: 3, 3: 2, 4: 1}, dtype=object)
result = answer.replace(weights)
tm.assert_series_equal(result, expected)
def test_replace_dict_tuple_list_ordering_remains_the_same(self):
df = DataFrame({"A": [np.nan, 1]})
res1 = df.replace(to_replace={np.nan: 0, 1: -1e8})
res2 = df.replace(to_replace=(1, np.nan), value=[-1e8, 0])
res3 = df.replace(to_replace=[1, np.nan], value=[-1e8, 0])
expected = DataFrame({"A": [0, -1e8]})
tm.assert_frame_equal(res1, res2)
tm.assert_frame_equal(res2, res3)
tm.assert_frame_equal(res3, expected)
def test_replace_doesnt_replace_without_regex(self):
df = DataFrame(
{
"fol": [1, 2, 2, 3],
"T_opp": ["0", "vr", "0", "0"],
"T_Dir": ["0", "0", "0", "bt"],
"T_Enh": ["vo", "0", "0", "0"],
}
)
res = df.replace({r"\D": 1})
tm.assert_frame_equal(df, res)
def test_replace_bool_with_string(self):
df = DataFrame({"a": [True, False], "b": list("ab")})
result = df.replace(True, "a")
expected = DataFrame({"a": ["a", False], "b": df.b})
tm.assert_frame_equal(result, expected)
def test_replace_pure_bool_with_string_no_op(self):
df = DataFrame(np.random.default_rng(2).random((2, 2)) > 0.5)
result = df.replace("asdf", "fdsa")
tm.assert_frame_equal(df, result)
def test_replace_bool_with_bool(self):
df = DataFrame(np.random.default_rng(2).random((2, 2)) > 0.5)
result = df.replace(False, True)
expected = DataFrame(np.ones((2, 2), dtype=bool))
tm.assert_frame_equal(result, expected)
def test_replace_with_dict_with_bool_keys(self):
df = DataFrame({0: [True, False], 1: [False, True]})
result = df.replace({"asdf": "asdb", True: "yes"})
expected = DataFrame({0: ["yes", False], 1: [False, "yes"]})
tm.assert_frame_equal(result, expected)
def test_replace_dict_strings_vs_ints(self):
# GH#34789
df = DataFrame({"Y0": [1, 2], "Y1": [3, 4]})
result = df.replace({"replace_string": "test"})
tm.assert_frame_equal(result, df)
result = df["Y0"].replace({"replace_string": "test"})
tm.assert_series_equal(result, df["Y0"])
def test_replace_truthy(self):
df = DataFrame({"a": [True, True]})
r = df.replace([np.inf, -np.inf], np.nan)
e = df
tm.assert_frame_equal(r, e)
def test_nested_dict_overlapping_keys_replace_int(self):
# GH 27660 keep behaviour consistent for simple dictionary and
# nested dictionary replacement
df = DataFrame({"a": list(range(1, 5))})
result = df.replace({"a": dict(zip(range(1, 5), range(2, 6)))})
expected = df.replace(dict(zip(range(1, 5), range(2, 6))))
tm.assert_frame_equal(result, expected)
def test_nested_dict_overlapping_keys_replace_str(self):
# GH 27660
a = np.arange(1, 5)
astr = a.astype(str)
bstr = np.arange(2, 6).astype(str)
df = DataFrame({"a": astr})
result = df.replace(dict(zip(astr, bstr)))
expected = df.replace({"a": dict(zip(astr, bstr))})
tm.assert_frame_equal(result, expected)
def test_replace_swapping_bug(self):
df = DataFrame({"a": [True, False, True]})
res = df.replace({"a": {True: "Y", False: "N"}})
expect = DataFrame({"a": ["Y", "N", "Y"]}, dtype=object)
tm.assert_frame_equal(res, expect)
df = DataFrame({"a": [0, 1, 0]})
res = df.replace({"a": {0: "Y", 1: "N"}})
expect = DataFrame({"a": ["Y", "N", "Y"]}, dtype=object)
tm.assert_frame_equal(res, expect)
def test_replace_datetimetz(self):
# GH 11326
# behaving poorly when presented with a datetime64[ns, tz]
df = DataFrame(
{
"A": date_range("20130101", periods=3, tz="US/Eastern", unit="ns"),
"B": [0, np.nan, 2],
}
)
result = df.replace(np.nan, 1)
expected = DataFrame(
{
"A": date_range("20130101", periods=3, tz="US/Eastern", unit="ns"),
"B": Series([0, 1, 2], dtype="float64"),
}
)
tm.assert_frame_equal(result, expected)
result = df.fillna(1)
tm.assert_frame_equal(result, expected)
result = df.replace(0, np.nan)
expected = DataFrame(
{
"A": date_range("20130101", periods=3, tz="US/Eastern", unit="ns"),
"B": [np.nan, np.nan, 2],
}
)
tm.assert_frame_equal(result, expected)
result = df.replace(
Timestamp("20130102", tz="US/Eastern"),
Timestamp("20130104", tz="US/Eastern"),
)
expected = DataFrame(
{
"A": [
Timestamp("20130101", tz="US/Eastern"),
Timestamp("20130104", tz="US/Eastern"),
Timestamp("20130103", tz="US/Eastern"),
],
"B": [0, np.nan, 2],
}
)
expected["A"] = expected["A"].dt.as_unit("ns")
tm.assert_frame_equal(result, expected)
result = df.copy()
result.iloc[1, 0] = np.nan
result = result.replace({"A": pd.NaT}, Timestamp("20130104", tz="US/Eastern"))
tm.assert_frame_equal(result, expected)
# pre-2.0 this would coerce to object with mismatched tzs
result = df.copy()
result.iloc[1, 0] = np.nan
result = result.replace({"A": pd.NaT}, Timestamp("20130104", tz="US/Pacific"))
expected = DataFrame(
{
"A": [
Timestamp("20130101", tz="US/Eastern"),
Timestamp("20130104", tz="US/Pacific").tz_convert("US/Eastern"),
Timestamp("20130103", tz="US/Eastern"),
],
"B": [0, np.nan, 2],
}
)
expected["A"] = expected["A"].dt.as_unit("ns")
tm.assert_frame_equal(result, expected)
result = df.copy()
result.iloc[1, 0] = np.nan
result = result.replace({"A": np.nan}, Timestamp("20130104"))
expected = DataFrame(
{
"A": [
Timestamp("20130101", tz="US/Eastern"),
Timestamp("20130104"),
Timestamp("20130103", tz="US/Eastern"),
],
"B": [0, np.nan, 2],
}
)
tm.assert_frame_equal(result, expected)
def test_replace_with_empty_dictlike(self, mix_abc):
# GH 15289
df = DataFrame(mix_abc)
tm.assert_frame_equal(df, df.replace({}))
tm.assert_frame_equal(df, df.replace(Series([], dtype=object)))
tm.assert_frame_equal(df, df.replace({"b": {}}))
tm.assert_frame_equal(df, df.replace(Series({"b": {}})))
@pytest.mark.parametrize(
"df, to_replace, exp",
[
(
{"col1": [1, 2, 3], "col2": [4, 5, 6]},
{4: 5, 5: 6, 6: 7},
{"col1": [1, 2, 3], "col2": [5, 6, 7]},
),
(
{"col1": [1, 2, 3], "col2": ["4", "5", "6"]},
{"4": "5", "5": "6", "6": "7"},
{"col1": [1, 2, 3], "col2": ["5", "6", "7"]},
),
],
)
def test_replace_commutative(self, df, to_replace, exp):
# GH 16051
# DataFrame.replace() overwrites when values are non-numeric
# also added to data frame whilst issue was for series
df = DataFrame(df)
expected = DataFrame(exp)
result = df.replace(to_replace)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"replacer",
[
Timestamp("20170827"),
np.int8(1),
np.int16(1),
np.float32(1),
np.float64(1),
],
)
def test_replace_replacer_dtype(self, replacer):
# GH26632
df = DataFrame(["a"], dtype=object)
result = df.replace({"a": replacer, "b": replacer})
expected = DataFrame([replacer], dtype=object)
tm.assert_frame_equal(result, expected)
def test_replace_after_convert_dtypes(self):
# GH31517
df = DataFrame({"grp": [1, 2, 3, 4, 5]}, dtype="Int64")
result = df.replace(1, 10)
expected = DataFrame({"grp": [10, 2, 3, 4, 5]}, dtype="Int64")
tm.assert_frame_equal(result, expected)
def test_replace_invalid_to_replace(self):
# GH 18634
# API: replace() should raise an exception if invalid argument is given
df = DataFrame({"one": ["a", "b ", "c"], "two": ["d ", "e ", "f "]})
msg = (
r"Expecting 'to_replace' to be either a scalar, array-like, "
r"dict or None, got invalid type.*"
)
with pytest.raises(TypeError, match=msg):
df.replace(lambda x: x.strip())
@pytest.mark.parametrize("dtype", ["float", "float64", "int64", "Int64", "boolean"])
@pytest.mark.parametrize("value", [np.nan, pd.NA])
def test_replace_no_replacement_dtypes(self, dtype, value):
# https://github.com/pandas-dev/pandas/issues/32988
df = DataFrame(np.eye(2), dtype=dtype)
result = df.replace(to_replace=[None, -np.inf, np.inf], value=value)
tm.assert_frame_equal(result, df)
@pytest.mark.parametrize("replacement", [np.nan, 5])
def test_replace_with_duplicate_columns(self, replacement):
# GH 24798
result = DataFrame({"A": [1, 2, 3], "A1": [4, 5, 6], "B": [7, 8, 9]})
result.columns = list("AAB")
expected = DataFrame(
{"A": [1, 2, 3], "A1": [4, 5, 6], "B": [replacement, 8, 9]}
)
expected.columns = list("AAB")
result["B"] = result["B"].replace(7, replacement)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("value", [pd.Period("2020-01"), pd.Interval(0, 5)])
def test_replace_ea_ignore_float(self, frame_or_series, value):
# GH#34871
obj = DataFrame({"Per": [value] * 3})
obj = tm.get_obj(obj, frame_or_series)
expected = obj.copy()
result = obj.replace(1.0, 0.0)
tm.assert_equal(expected, result)
@pytest.mark.parametrize(
"replace_dict, final_data",
[({"a": 1, "b": 1}, [[2, 2], [2, 2]]), ({"a": 1, "b": 2}, [[2, 1], [2, 2]])],
)
def test_categorical_replace_with_dict(self, replace_dict, final_data):
# GH 26988
df = DataFrame([[1, 1], [2, 2]], columns=["a", "b"], dtype="category")
final_data = np.array(final_data)
a = pd.Categorical(final_data[:, 0], categories=[1, 2])
b = pd.Categorical(final_data[:, 1], categories=[1, 2])
expected = DataFrame({"a": a, "b": b})
result = df.replace(replace_dict, 2)
tm.assert_frame_equal(result, expected)
msg = r"DataFrame.iloc\[:, 0\] \(column name=\"a\"\) are " "different"
with pytest.raises(AssertionError, match=msg):
# ensure non-inplace call does not affect original
tm.assert_frame_equal(df, expected)
result = df.replace(replace_dict, 2, inplace=True)
assert result is df
tm.assert_frame_equal(df, expected)
def test_replace_value_category_type(self):
"""
Test for #23305: to ensure category dtypes are maintained
after replace with direct values
"""
# create input data
input_dict = {
"col1": [1, 2, 3, 4],
"col2": ["a", "b", "c", "d"],
"col3": [1.5, 2.5, 3.5, 4.5],
"col4": ["cat1", "cat2", "cat3", "cat4"],
"col5": ["obj1", "obj2", "obj3", "obj4"],
}
# explicitly cast columns as category and order them
input_df = DataFrame(data=input_dict).astype(
{"col2": "category", "col4": "category"}
)
input_df["col2"] = input_df["col2"].cat.reorder_categories(
["a", "b", "c", "d"], ordered=True
)
input_df["col4"] = input_df["col4"].cat.reorder_categories(
["cat1", "cat2", "cat3", "cat4"], ordered=True
)
# create expected dataframe
expected_dict = {
"col1": [1, 2, 3, 4],
"col2": ["a", "b", "c", "z"],
"col3": [1.5, 2.5, 3.5, 4.5],
"col4": ["cat1", "catX", "cat3", "cat4"],
"col5": ["obj9", "obj2", "obj3", "obj4"],
}
# explicitly cast columns as category and order them
expected = DataFrame(data=expected_dict).astype(
{"col2": "category", "col4": "category"}
)
expected["col2"] = expected["col2"].cat.reorder_categories(
["a", "b", "c", "z"], ordered=True
)
expected["col4"] = expected["col4"].cat.reorder_categories(
["cat1", "catX", "cat3", "cat4"], ordered=True
)
# replace values in input dataframe
input_df = input_df.apply(
lambda x: x.astype("category").cat.rename_categories({"d": "z"})
)
input_df = input_df.apply(
lambda x: x.astype("category").cat.rename_categories({"obj1": "obj9"})
)
result = input_df.apply(
lambda x: x.astype("category").cat.rename_categories({"cat2": "catX"})
)
result = result.astype({"col1": "int64", "col3": "float64", "col5": "str"})
tm.assert_frame_equal(result, expected)
def test_replace_dict_category_type(self):
"""
Test to ensure category dtypes are maintained
after replace with dict values
"""
# GH#35268, GH#44940
# create input dataframe
input_dict = {"col1": ["a"], "col2": ["obj1"], "col3": ["cat1"]}
# explicitly cast columns as category
input_df = DataFrame(data=input_dict).astype(
{"col1": "category", "col2": "category", "col3": "category"}
)
# create expected dataframe
expected_dict = {"col1": ["z"], "col2": ["obj9"], "col3": ["catX"]}
# explicitly cast columns as category
expected = DataFrame(data=expected_dict).astype(
{"col1": "category", "col2": "category", "col3": "category"}
)
# replace values in input dataframe using a dict
result = input_df.apply(
lambda x: x.cat.rename_categories(
{"a": "z", "obj1": "obj9", "cat1": "catX"}
)
)
tm.assert_frame_equal(result, expected)
def test_replace_with_compiled_regex(self):
# https://github.com/pandas-dev/pandas/issues/35680
df = DataFrame(["a", "b", "c"])
regex = re.compile("^a$")
result = df.replace({regex: "z"}, regex=True)
expected = DataFrame(["z", "b", "c"])
tm.assert_frame_equal(result, expected)
def test_replace_intervals(self):
# https://github.com/pandas-dev/pandas/issues/35931
df = DataFrame({"a": [pd.Interval(0, 1), pd.Interval(0, 1)]})
result = df.replace({"a": {pd.Interval(0, 1): "x"}})
expected = DataFrame({"a": ["x", "x"]}, dtype=object)
tm.assert_frame_equal(result, expected)
def test_replace_unicode(self):
# GH: 16784
columns_values_map = {"positive": {"正面": 1, "中立": 1, "负面": 0}}
df1 = DataFrame({"positive": np.ones(3)})
result = df1.replace(columns_values_map)
expected = DataFrame({"positive": np.ones(3)})
tm.assert_frame_equal(result, expected)
def test_replace_bytes(self, frame_or_series):
# GH#38900
obj = frame_or_series(["o"]).astype("|S")
expected = obj.copy()
obj = obj.replace({None: np.nan})
tm.assert_equal(obj, expected)
@pytest.mark.parametrize(
"data, to_replace, value, expected",
[
([1], [1.0], [0], [0]),
([1], [1], [0], [0]),
([1.0], [1.0], [0], [0.0]),
([1.0], [1], [0], [0.0]),
],
)
@pytest.mark.parametrize("box", [list, tuple, np.array])
def test_replace_list_with_mixed_type(
self, data, to_replace, value, expected, box, frame_or_series
):
# GH#40371
obj = frame_or_series(data)
expected = frame_or_series(expected)
result = obj.replace(box(to_replace), value)
tm.assert_equal(result, expected)
@pytest.mark.parametrize("val", [2, np.nan, 2.0])
def test_replace_value_none_dtype_numeric(self, val):
# GH#48231
df = DataFrame({"a": [1, val]})
result = df.replace(val, None)
expected = DataFrame({"a": [1, None]}, dtype=object)
tm.assert_frame_equal(result, expected)
df = DataFrame({"a": [1, val]})
result = df.replace({val: None})
tm.assert_frame_equal(result, expected)
def test_replace_with_nil_na(self):
# GH 32075
ser = DataFrame({"a": ["nil", pd.NA]})
expected = DataFrame({"a": ["anything else", pd.NA]}, index=[0, 1])
result = ser.replace("nil", "anything else")
tm.assert_frame_equal(expected, result)
@pytest.mark.parametrize(
"dtype",
[
"Float64",
pytest.param("float64[pyarrow]", marks=td.skip_if_no("pyarrow")),
],
)
def test_replace_na_to_nan_nullable_floats(self, dtype, using_nan_is_na):
# GH#55127
df = DataFrame({0: [1, np.nan, 1], 1: Series([0, pd.NA, 1], dtype=dtype)})
result = df.replace(pd.NA, np.nan)
if using_nan_is_na:
expected = result
else:
expected = DataFrame(
{0: [1, np.nan, 1], 1: Series([0, np.nan, 1], dtype=dtype)}
)
assert np.isnan(expected.loc[1, 1])
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"dtype",
[
"Int64",
pytest.param("int64[pyarrow]", marks=td.skip_if_no("pyarrow")),
],
)
def test_replace_nan_nullable_ints(self, dtype, using_nan_is_na):
# GH#51237 with nan_is_na=False, replacing NaN should be a no-op here
ser = Series([1, 2, None], dtype=dtype)
result = ser.replace(np.nan, -1)
if using_nan_is_na:
# np.nan is equivalent to pd.NA here
expected = Series([1, 2, -1], dtype=dtype)
else:
expected = ser
tm.assert_series_equal(result, expected)
| TestDataFrameReplace |
python | django-guardian__django-guardian | guardian/templatetags/guardian_tags.py | {
"start": 411,
"end": 3423
} | class ____(template.Node):
def __init__(self, for_whom, obj, context_var, checker=None):
self.for_whom = template.Variable(for_whom)
self.obj = template.Variable(obj)
self.context_var = context_var
self.checker = template.Variable(checker) if checker else None
def render(self, context):
for_whom = self.for_whom.resolve(context)
if isinstance(for_whom, get_user_model()):
self.user = for_whom
self.group = None
elif isinstance(for_whom, AnonymousUser):
self.user = get_user_model().get_anonymous()
self.group = None
elif isinstance(for_whom, Group):
self.user = None
self.group = for_whom
else:
raise NotUserNorGroup("User or Group instance required (got %s)" % for_whom.__class__)
obj = self.obj.resolve(context)
if not obj:
return ""
check = self.checker.resolve(context) if self.checker else ObjectPermissionChecker(for_whom)
perms = check.get_perms(obj)
context[self.context_var] = perms
return ""
@register.tag
def get_obj_perms(parser, token):
"""Get a list of permissions for a given user/group and object.
Parses `get_obj_perms` tag which should be in format:
```
{% get_obj_perms user/group for obj as "context_var" %}
```
Returns:
a list of permissions (as `codename` strings)
for a given `user`/`group` and `obj` (Model instance).
Note:
Make sure that you set and use those permissions in same template
block (`{% block %}`).
Example:
Assuming `flatpage` and `perm` objects are available in the *context* object:
```
{% get_obj_perms request.user for flatpage as "flatpage_perms" %}
{% if "delete_flatpage" in flatpage_perms %}
<a href="/pages/delete?target={{ flatpage.url }}">Remove page</a>
{% endif %}
```
Note:
Please remember that superusers would always get full list of permissions
for a given object.
Note: Added in version 1.2
As of v1.2, passing `None` as `obj` for this template tag won't rise
obfuscated exception and would return empty permissions set instead.
"""
bits = token.split_contents()
format = '{% get_obj_perms user/group for obj as "context_var" perm_checker %}'
if not (6 <= len(bits) <= 7) or bits[2] != "for" or bits[4] != "as":
raise template.TemplateSyntaxError("get_obj_perms tag should be in format: %s" % format)
for_whom = bits[1]
obj = bits[3]
context_var = bits[5]
if context_var[0] != context_var[-1] or context_var[0] not in ('"', "'"):
raise template.TemplateSyntaxError("get_obj_perms tag's context_var argument should be in quotes")
context_var = context_var[1:-1]
checker = bits[6] if len(bits) == 7 else None
return ObjectPermissionsNode(for_whom, obj, context_var, checker)
| ObjectPermissionsNode |
python | kamyu104__LeetCode-Solutions | Python/count-valid-paths-in-a-tree.py | {
"start": 69,
"end": 2188
} | class ____(object):
def countPaths(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
def linear_sieve_of_eratosthenes(n): # Time: O(n), Space: O(n)
primes = []
spf = [-1]*(n+1) # the smallest prime factor
for i in xrange(2, n+1):
if spf[i] == -1:
spf[i] = i
primes.append(i)
for p in primes:
if i*p > n or p > spf[i]:
break
spf[i*p] = p
return spf
def is_prime(u):
return spf[u] == u
def iter_dfs():
result = 0
stk = [(1, (0, -1, [0]*2))]
while stk:
step, args = stk.pop()
if step == 1:
u, p, ret = args
ret[:] = [1-is_prime(u+1), is_prime(u+1)]
stk.append((2, (u, p, ret, 0)))
elif step == 2:
u, p, ret, i = args
if i == len(adj[u]):
continue
v = adj[u][i]
stk.append((2, (u, p, ret, i+1)))
if v == p:
continue
new_ret = [0]*2
stk.append((3, (u, p, new_ret, ret, i)))
stk.append((1, (v, u, new_ret)))
elif step == 3:
u, p, new_ret, ret, i = args
result += ret[0]*new_ret[1]+ret[1]*new_ret[0]
if is_prime(u+1):
ret[1] += new_ret[0]
else:
ret[0] += new_ret[0]
ret[1] += new_ret[1]
return result
spf = linear_sieve_of_eratosthenes(n)
adj = [[] for _ in xrange(n)]
for u, v in edges:
u, v = u-1, v-1
adj[u].append(v)
adj[v].append(u)
return iter_dfs()
# Time: O(n)
# Space: O(n)
# number theory, tree dp, dfs
| Solution |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/dataclass_transforms_decorator_w_mixins.py | {
"start": 670,
"end": 994
} | class ____(RelationshipsModel):
im_going_to_be_mapped = True
level: Mapped[int] = mapped_column(Integer)
# note init=True is implicit on Relationships
# (this is the type checker, not us)
rs = Relationships(entity_id1=1, entity_id2=2, level=1)
assert_type(rs.entity_id1, int)
assert_type(rs.level, int)
| Relationships |
python | Pylons__pyramid | tests/test_httpexceptions.py | {
"start": 14717,
"end": 15536
} | class ____(unittest.TestCase):
def _doit(self, content_type):
from pyramid.httpexceptions import status_map
L = []
self.assertTrue(status_map)
for v in status_map.values():
environ = _makeEnviron()
start_response = DummyStartResponse()
exc = v()
exc.content_type = content_type
result = list(exc(environ, start_response))[0]
if exc.empty_body:
self.assertEqual(result, b'')
else:
self.assertTrue(bytes_(exc.status) in result)
L.append(result)
self.assertEqual(len(L), len(status_map))
def test_it_plain(self):
self._doit('text/plain')
def test_it_html(self):
self._doit('text/html')
| TestRenderAllExceptionsWithoutArguments |
python | matplotlib__matplotlib | lib/matplotlib/sphinxext/figmpl_directive.py | {
"start": 805,
"end": 864
} | class ____(nodes.General, nodes.Element):
pass
| figmplnode |
python | simonw__datasette | datasette/events.py | {
"start": 1582,
"end": 2063
} | class ____(Event):
"""
Event name: ``create-table``
A new table has been created in the database.
:ivar database: The name of the database where the table was created.
:type database: str
:ivar table: The name of the table that was created
:type table: str
:ivar schema: The SQL schema definition for the new table.
:type schema: str
"""
name = "create-table"
database: str
table: str
schema: str
@dataclass
| CreateTableEvent |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_api_key_details.py | {
"start": 378,
"end": 727
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-api-key-details"
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
self.api_key = ApiKey.objects.create(
organization_id=self.organization.id, scope_list=DEFAULT_SCOPES
)
@control_silo_test
| OrganizationApiKeyDetailsBase |
python | django__django | tests/schema/models.py | {
"start": 2034,
"end": 2281
} | class ____(models.Model):
author = models.ForeignKey(Author, models.CASCADE, db_constraint=False)
title = models.CharField(max_length=100, db_index=True)
pub_date = models.DateTimeField()
class Meta:
apps = new_apps
| BookWeak |
python | Pylons__pyramid | tests/test_traversal.py | {
"start": 45565,
"end": 45978
} | class ____:
__parent__ = None
def __init__(self, next=None, name=None):
self.next = next
self.__name__ = name
def __getitem__(self, name):
if self.next is None:
raise KeyError(name)
return self.next
def __repr__(self):
return '<DummyContext with name {} at id {}>'.format(
self.__name__,
id(self),
)
| DummyContext |
python | walkccc__LeetCode | solutions/3325. Count Substrings With K-Frequency Characters I/3325.py | {
"start": 0,
"end": 314
} | class ____:
def numberOfSubstrings(self, s: str, k: int) -> int:
n = len(s)
ans = n * (n + 1) // 2
count = collections.Counter()
l = 0
for r, c in enumerate(s):
count[c] += 1
while count[c] == k:
count[s[l]] -= 1
l += 1
ans -= r - l + 1
return ans
| Solution |
python | catalyst-team__catalyst | examples/detection/models/yolo_x.py | {
"start": 16022,
"end": 17542
} | class ____(nn.Module):
def __init__(self, reduction="none", loss_type="iou"):
super(IOUloss, self).__init__()
self.reduction = reduction
self.loss_type = loss_type
def forward(self, pred, target):
assert pred.shape[0] == target.shape[0]
pred = pred.view(-1, 4)
target = target.view(-1, 4)
tl = torch.max(
(pred[:, :2] - pred[:, 2:] / 2), (target[:, :2] - target[:, 2:] / 2)
)
br = torch.min(
(pred[:, :2] + pred[:, 2:] / 2), (target[:, :2] + target[:, 2:] / 2)
)
area_p = torch.prod(pred[:, 2:], 1)
area_g = torch.prod(target[:, 2:], 1)
en = (tl < br).type(tl.type()).prod(dim=1)
area_i = torch.prod(br - tl, 1) * en
iou = (area_i) / (area_p + area_g - area_i + 1e-16)
if self.loss_type == "iou":
loss = 1 - iou ** 2
elif self.loss_type == "giou":
c_tl = torch.min(
(pred[:, :2] - pred[:, 2:] / 2), (target[:, :2] - target[:, 2:] / 2)
)
c_br = torch.max(
(pred[:, :2] + pred[:, 2:] / 2), (target[:, :2] + target[:, 2:] / 2)
)
area_c = torch.prod(c_br - c_tl, 1)
giou = iou - (area_c - area_i) / area_c.clamp(1e-16)
loss = 1 - giou.clamp(min=-1.0, max=1.0)
if self.reduction == "mean":
loss = loss.mean()
elif self.reduction == "sum":
loss = loss.sum()
return loss
| IOUloss |
python | zarr-developers__zarr-python | src/zarr/codecs/vlen_utf8.py | {
"start": 2279,
"end": 3798
} | class ____(ArrayBytesCodec):
@classmethod
def from_dict(cls, data: dict[str, JSON]) -> Self:
_, configuration_parsed = parse_named_configuration(
data, "vlen-bytes", require_configuration=False
)
configuration_parsed = configuration_parsed or {}
return cls(**configuration_parsed)
def to_dict(self) -> dict[str, JSON]:
return {"name": "vlen-bytes", "configuration": {}}
def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self:
return self
async def _decode_single(
self,
chunk_bytes: Buffer,
chunk_spec: ArraySpec,
) -> NDBuffer:
assert isinstance(chunk_bytes, Buffer)
raw_bytes = chunk_bytes.as_array_like()
decoded = _vlen_bytes_codec.decode(raw_bytes)
assert decoded.dtype == np.object_
decoded.shape = chunk_spec.shape
return chunk_spec.prototype.nd_buffer.from_numpy_array(decoded)
async def _encode_single(
self,
chunk_array: NDBuffer,
chunk_spec: ArraySpec,
) -> Buffer | None:
assert isinstance(chunk_array, NDBuffer)
return chunk_spec.prototype.buffer.from_bytes(
_vlen_bytes_codec.encode(chunk_array.as_numpy_array())
)
def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int:
# what is input_byte_length for an object dtype?
raise NotImplementedError("compute_encoded_size is not implemented for VLen codecs")
| VLenBytesCodec |
python | spack__spack | lib/spack/spack/cmd/create.py | {
"start": 6241,
"end": 6726
} | class ____(PackageTemplate):
"""Provides appropriate overrides for CMake-based packages"""
base_class_name = "CMakePackage"
package_class_import = "from spack_repo.builtin.build_systems.cmake import CMakePackage"
body_def = """\
def cmake_args(self):
# FIXME: Add arguments other than
# FIXME: CMAKE_INSTALL_PREFIX and CMAKE_BUILD_TYPE
# FIXME: If not needed delete this function
args = []
return args"""
| CMakePackageTemplate |
python | PrefectHQ__prefect | src/integrations/prefect-azure/tests/conftest.py | {
"start": 4074,
"end": 4818
} | class ____:
def query_items(self, *args, **kwargs):
return [{"name": "Someone", "age": 23}]
def read_item(self, *args, **kwargs):
return {"name": "Someone", "age": 23}
def create_item(self, *args, **kwargs):
return {"name": "Other", "age": 3}
@pytest.fixture
def cosmos_db_credentials():
cosmos_db_credentials = MagicMock()
cosmos_db_credentials.get_container_client.side_effect = (
lambda container, database: CosmosDbClientMethodsMock()
)
return cosmos_db_credentials
@pytest.fixture
def ml_credentials():
ml_credentials = MagicMock()
ml_credentials.get_workspace.side_effect = lambda: MagicMock(datastores=["a", "b"])
return ml_credentials
| CosmosDbClientMethodsMock |
python | ansible__ansible | lib/ansible/module_utils/facts/hardware/sunos.py | {
"start": 10444,
"end": 10589
} | class ____(HardwareCollector):
_fact_class = SunOSHardware
_platform = 'SunOS'
required_facts = set(['platform'])
| SunOSHardwareCollector |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_preprocess_data.py | {
"start": 10592,
"end": 11327
} | class ____:
plotters = [Axes.scatter, Axes.bar, Axes.plot]
@pytest.mark.parametrize('plotter', plotters)
@check_figures_equal()
def test_dict_unpack(self, plotter, fig_test, fig_ref):
x = [1, 2, 3]
y = [4, 5, 6]
ddict = dict(zip(x, y))
plotter(fig_test.subplots(),
ddict.keys(), ddict.values())
plotter(fig_ref.subplots(), x, y)
@pytest.mark.parametrize('plotter', plotters)
@check_figures_equal()
def test_data_kwarg(self, plotter, fig_test, fig_ref):
x = [1, 2, 3]
y = [4, 5, 6]
plotter(fig_test.subplots(), 'xval', 'yval',
data={'xval': x, 'yval': y})
plotter(fig_ref.subplots(), x, y)
| TestPlotTypes |
python | celery__celery | t/unit/tasks/test_result.py | {
"start": 1571,
"end": 1809
} | class ____:
def add_pending_result(self, *args, **kwargs):
return True
def wait_for_pending(self, *args, **kwargs):
return True
def remove_pending_result(self, *args, **kwargs):
return True
| _MockBackend |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_executors.py | {
"start": 961,
"end": 1133
} | class ____(TestCase):
@given(integers())
def test_something(self, i):
pass
def execute_example(self, f):
f()
return f()
| TestTryReallyHard |
python | walkccc__LeetCode | solutions/2124. Check if All A's Appears Before All B's/2124.py | {
"start": 0,
"end": 82
} | class ____:
def checkString(self, s: str) -> bool:
return 'ba' not in s
| Solution |
python | pytorch__pytorch | test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py | {
"start": 16709,
"end": 17261
} | class ____(_RendezvousStateHolder):
_state: _RendezvousState
_dirty: Optional[bool]
def __init__(self) -> None:
self._state = _RendezvousState()
self._dirty = None
@property
def state(self) -> _RendezvousState:
return self._state
@state.setter
def state(self, value) -> None:
self._state = value
def sync(self) -> Optional[bool]:
self._dirty, dirty = None, self._dirty
return dirty
def mark_dirty(self) -> None:
self._dirty = True
| FakeRendezvousStateHolder |
python | django__django | tests/serializers/models/base.py | {
"start": 3887,
"end": 3959
} | class ____(BaseModel):
class Meta:
proxy = True
| ProxyBaseModel |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 30866,
"end": 34449
} | class ____(NonStrictDataModel):
"""
:param content_types:
:type content_types: Sequence[StatCount]
:param labels:
:type labels: Sequence[StatCount]
:param frames:
:type frames: Sequence[StatCount]
"""
_schema = {
"properties": {
"content_types": {
"items": {
"$ref": "#/definitions/stat_count",
"description": (
"List of content type counts for the version (e.g.\n 'image/jpeg',"
" 'image/png', 'video/mp4')"
),
},
"type": ["array", "null"],
},
"frames": {
"items": {
"$ref": "#/definitions/stat_count",
"description": (
"List of frame counts, indicating the\n type of frames included in the "
"version (annotated/"
),
},
"type": ["array", "null"],
},
"labels": {
"items": {
"$ref": "#/definitions/stat_count",
"description": (
"List of labels' counts,\n indicating the categories included in the version"
),
},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(self, content_types=None, labels=None, frames=None, **kwargs):
super(Statistics, self).__init__(**kwargs)
self.content_types = content_types
self.labels = labels
self.frames = frames
@schema_property("content_types")
def content_types(self):
return self._property_content_types
@content_types.setter
def content_types(self, value):
if value is None:
self._property_content_types = None
return
self.assert_isinstance(value, "content_types", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [
StatCount.from_dict(v) if isinstance(v, dict) else v for v in value
]
else:
self.assert_isinstance(value, "content_types", StatCount, is_array=True)
self._property_content_types = value
@schema_property("labels")
def labels(self):
return self._property_labels
@labels.setter
def labels(self, value):
if value is None:
self._property_labels = None
return
self.assert_isinstance(value, "labels", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [
StatCount.from_dict(v) if isinstance(v, dict) else v for v in value
]
else:
self.assert_isinstance(value, "labels", StatCount, is_array=True)
self._property_labels = value
@schema_property("frames")
def frames(self):
return self._property_frames
@frames.setter
def frames(self, value):
if value is None:
self._property_frames = None
return
self.assert_isinstance(value, "frames", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [
StatCount.from_dict(v) if isinstance(v, dict) else v for v in value
]
else:
self.assert_isinstance(value, "frames", StatCount, is_array=True)
self._property_frames = value
| Statistics |
python | pytorch__pytorch | test/distributed/tensor/test_dtensor_dispatch_overhead.py | {
"start": 713,
"end": 2019
} | class ____(TorchDispatchMode):
def __init__(self, repeat_count=10):
# repeat each op call `repeat_count` times
self.repeat_count = repeat_count
# recorded time is scaled to micro seconds
self.time_list = []
self.op_to_time = {}
def __torch_dispatch__(self, func, types, args=(), kwargs=None):
self.time_list.clear()
@functools.wraps(func)
def repeated_func(*args, **kwargs):
result = None
for _ in range(self.repeat_count):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
elapsed_time = end_time - start_time
self.time_list.append(elapsed_time)
return result
res = repeated_func(*args, **(kwargs or {}))
Timing = namedtuple(
"Timing", ["dispatch_with_cache_miss", "dispatch_with_cache_hit"]
)
if func.__name__ not in self.op_to_time:
self.op_to_time[func.__name__] = []
self.op_to_time[func.__name__].append(
Timing(
round(self.time_list[0] * 1e6, 2),
round(statistics.median(self.time_list) * 1e6, 2),
)
)
return res
| TimeCaptureMode |
python | bokeh__bokeh | src/bokeh/models/comparisons.py | {
"start": 2154,
"end": 3566
} | class ____(Comparison):
''' A client-side comparison performed by evaluating a user-supplied
JavaScript function. This comparison can be useful for DataTable columns.
.. warning::
The explicit purpose of this Bokeh Model is to embed *raw JavaScript
code* for a browser to execute. If any part of the code is derived
from untrusted user inputs, then you must take appropriate care to
sanitize the user input prior to passing to Bokeh.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
args = Dict(String, AnyRef, help="""
A mapping of names to Python objects. In particular those can be bokeh's models.
These objects are made available to the callback's code snippet as the values of
named parameters to the callback. There is no need to manually include the data
source of the associated glyph renderer, as it is available within the scope of
the code via `this` keyword (e.g. `this.data` will give access to raw data).
""")
code = String(default="", help="""
A snippet of JavaScript code to execute in the browser. The code is made into
the body of a generator function and all of the named objects in ``args``
are available as parameters that the code can use. Must return -1, 0, or 1.
""")
| CustomJSCompare |
python | ray-project__ray | python/ray/data/tests/test_download_expression.py | {
"start": 1296,
"end": 9658
} | class ____:
"""Test actual download functionality with real and mocked data."""
def test_download_expression_with_local_files(self, tmp_path):
"""Test basic download expression functionality with local files."""
# Create sample files with different content types
sample_data = [
b"This is test file 1 content",
b"Different content for file 2",
b"File 3 has some binary data: \x00\x01\x02\x03",
]
file_paths = []
for i, data in enumerate(sample_data):
file_path = tmp_path / f"test_file_{i}.txt"
file_path.write_bytes(data)
file_paths.append(str(file_path))
# Create dataset with file URIs and metadata
table = pa.Table.from_arrays(
[
pa.array([f"local://{path}" for path in file_paths]),
pa.array([f"id_{i}" for i in range(len(file_paths))]),
pa.array([f"metadata_{i}" for i in range(len(file_paths))]),
pa.array(range(len(file_paths))),
],
names=["file_uri", "file_id", "metadata", "index"],
)
ds = ray.data.from_arrow(table)
# Add download column using expression
ds_with_downloads = ds.with_column("file_bytes", download("file_uri"))
# Verify results
results = ds_with_downloads.take_all()
assert len(results) == len(sample_data)
for i, result in enumerate(results):
# Download column should be added correctly
assert "file_bytes" in result
assert result["file_bytes"] == sample_data[i]
# All original columns should be preserved
assert result["file_id"] == f"id_{i}"
assert result["metadata"] == f"metadata_{i}"
assert result["index"] == i
assert result["file_uri"] == f"local://{file_paths[i]}"
def test_download_expression_empty_dataset(self):
"""Test download expression with empty dataset."""
# Create empty dataset with correct schema
table = pa.Table.from_arrays(
[
pa.array([], type=pa.string()),
],
names=["uri"],
)
ds = ray.data.from_arrow(table)
ds_with_downloads = ds.with_column("bytes", download("uri"))
results = ds_with_downloads.take_all()
assert len(results) == 0
def test_download_expression_with_different_file_types(self, tmp_path):
"""Test download expression with various file types including actual images."""
# Create a small 8x8 RGB image
small_image = Image.new("RGB", (8, 8), color=(255, 0, 0)) # Red 8x8 image
image_buffer = io.BytesIO()
small_image.save(image_buffer, format="PNG")
image_bytes = image_buffer.getvalue()
# Create files with different types of content
test_files = [
("text_file.txt", b"Simple text content"),
("binary_file.dat", b"\x00\x01\x02\x03\x04\x05"),
("json_file.json", b'{"key": "value", "number": 123}'),
("small_image.png", image_bytes), # Actual PNG image (primary use case)
("empty_file.txt", b""), # Empty file edge case
]
file_paths = []
expected_data = []
for filename, content in test_files:
file_path = tmp_path / filename
file_path.write_bytes(content)
file_paths.append(str(file_path))
expected_data.append(content)
# Create dataset
table = pa.Table.from_arrays(
[
pa.array([f"local://{path}" for path in file_paths]),
pa.array(
[f.split(".")[0] for f, _ in test_files]
), # filename without extension
],
names=["file_uri", "file_type"],
)
ds = ray.data.from_arrow(table)
ds_with_downloads = ds.with_column("content", download("file_uri"))
results = ds_with_downloads.take_all()
assert len(results) == len(test_files)
for i, result in enumerate(results):
assert result["content"] == expected_data[i]
assert result["file_type"] == test_files[i][0].split(".")[0]
# Special verification for image file - ensure it can be loaded as an image
if test_files[i][0].endswith(".png"):
downloaded_image = Image.open(io.BytesIO(result["content"]))
assert downloaded_image.size == (8, 8)
assert downloaded_image.mode == "RGB"
def test_chained_download_expressions(self, tmp_path):
"""Test chained download expressions functionality."""
# Create sample files with different content
sample_data = [
b"Content for file 1",
b"Content for file 2",
b"Content for file 3",
]
file_paths = []
for i, data in enumerate(sample_data):
file_path = tmp_path / f"test_file_{i}.txt"
file_path.write_bytes(data)
file_paths.append(str(file_path))
# Create dataset with file URIs
table = pa.Table.from_arrays(
[
pa.array([f"local://{path}" for path in file_paths]),
pa.array([f"id_{i}" for i in range(len(file_paths))]),
],
names=["file_uri", "file_id"],
)
ds = ray.data.from_arrow(table)
# Chain multiple download expressions from the same URI column
ds_with_chained_downloads = (
ds.with_column("file_bytes_1", download("file_uri"))
.with_column("file_bytes_2", download("file_uri"))
.with_column("file_bytes_3", download("file_uri"))
)
# Verify results
results = ds_with_chained_downloads.take_all()
assert len(results) == len(sample_data)
for i, result in enumerate(results):
# All download columns should have the same content
assert "file_bytes_1" in result
assert "file_bytes_2" in result
assert "file_bytes_3" in result
assert result["file_bytes_1"] == sample_data[i]
assert result["file_bytes_2"] == sample_data[i]
assert result["file_bytes_3"] == sample_data[i]
# Original columns should be preserved
assert result["file_id"] == f"id_{i}"
assert result["file_uri"] == f"local://{file_paths[i]}"
def test_download_expression_with_pandas_blocks(self, tmp_path):
"""Test download with pandas blocks to ensure arrow conversion works.
This tests the code path in PartitionActor.__call__ where non-arrow
blocks are converted to arrow format before processing.
"""
ctx = ray.data.context.DataContext.get_current()
old_enable_pandas_block = ctx.enable_pandas_block
ctx.enable_pandas_block = True
try:
# Create test files
sample_data = [
b"Pandas block test content 1",
b"Pandas block test content 2",
]
file_paths = []
for i, data in enumerate(sample_data):
file_path = tmp_path / f"pandas_test_{i}.txt"
file_path.write_bytes(data)
file_paths.append(str(file_path))
# Create dataset with pandas blocks (not arrow)
df = pd.DataFrame(
{
"file_uri": [f"local://{path}" for path in file_paths],
"file_id": [f"id_{i}" for i in range(len(file_paths))],
}
)
ds = ray.data.from_pandas(df)
# Apply download - this should trigger arrow conversion in PartitionActor
ds_with_downloads = ds.with_column("content", download("file_uri"))
# Verify results
results = ds_with_downloads.take_all()
assert len(results) == len(sample_data)
for i, result in enumerate(results):
assert result["content"] == sample_data[i]
assert result["file_id"] == f"id_{i}"
assert result["file_uri"] == f"local://{file_paths[i]}"
finally:
ctx.enable_pandas_block = old_enable_pandas_block
| TestDownloadExpressionFunctionality |
python | sympy__sympy | sympy/testing/runtests.py | {
"start": 59736,
"end": 67264
} | class ____(DocTestFinder):
"""
A class used to extract the DocTests that are relevant to a given
object, from its docstring and the docstrings of its contained
objects. Doctests can currently be extracted from the following
object types: modules, functions, classes, methods, staticmethods,
classmethods, and properties.
Modified from doctest's version to look harder for code that
appears comes from a different module. For example, the @vectorize
decorator makes it look like functions come from multidimensional.py
even though their code exists elsewhere.
"""
def _find(self, tests, obj, name, module, source_lines, globs, seen):
"""
Find tests for the given object and any contained objects, and
add them to ``tests``.
"""
if self._verbose:
print('Finding tests in %s' % name)
# If we've already processed this object, then ignore it.
if id(obj) in seen:
return
seen[id(obj)] = 1
# Make sure we don't run doctests for classes outside of sympy, such
# as in numpy or scipy.
if inspect.isclass(obj):
if obj.__module__.split('.')[0] != 'sympy':
return
# Find a test for this object, and add it to the list of tests.
test = self._get_test(obj, name, module, globs, source_lines)
if test is not None:
tests.append(test)
if not self._recurse:
return
# Look for tests in a module's contained objects.
if inspect.ismodule(obj):
for rawname, val in obj.__dict__.items():
# Recurse to functions & classes.
if inspect.isfunction(val) or inspect.isclass(val):
# Make sure we don't run doctests functions or classes
# from different modules
if val.__module__ != module.__name__:
continue
assert self._from_module(module, val), \
"%s is not in module %s (rawname %s)" % (val, module, rawname)
try:
valname = '%s.%s' % (name, rawname)
self._find(tests, val, valname, module,
source_lines, globs, seen)
except KeyboardInterrupt:
raise
# Look for tests in a module's __test__ dictionary.
for valname, val in getattr(obj, '__test__', {}).items():
if not isinstance(valname, str):
raise ValueError("SymPyDocTestFinder.find: __test__ keys "
"must be strings: %r" %
(type(valname),))
if not (inspect.isfunction(val) or inspect.isclass(val) or
inspect.ismethod(val) or inspect.ismodule(val) or
isinstance(val, str)):
raise ValueError("SymPyDocTestFinder.find: __test__ values "
"must be strings, functions, methods, "
"classes, or modules: %r" %
(type(val),))
valname = '%s.__test__.%s' % (name, valname)
self._find(tests, val, valname, module, source_lines,
globs, seen)
# Look for tests in a class's contained objects.
if inspect.isclass(obj):
for valname, val in obj.__dict__.items():
# Special handling for staticmethod/classmethod.
if isinstance(val, staticmethod):
val = getattr(obj, valname)
if isinstance(val, classmethod):
val = getattr(obj, valname).__func__
# Recurse to methods, properties, and nested classes.
if ((inspect.isfunction(unwrap(val)) or
inspect.isclass(val) or
isinstance(val, property)) and
self._from_module(module, val)):
# Make sure we don't run doctests functions or classes
# from different modules
if isinstance(val, property):
if hasattr(val.fget, '__module__'):
if val.fget.__module__ != module.__name__:
continue
else:
if val.__module__ != module.__name__:
continue
assert self._from_module(module, val), \
"%s is not in module %s (valname %s)" % (
val, module, valname)
valname = '%s.%s' % (name, valname)
self._find(tests, val, valname, module, source_lines,
globs, seen)
def _get_test(self, obj, name, module, globs, source_lines):
"""
Return a DocTest for the given object, if it defines a docstring;
otherwise, return None.
"""
lineno = None
# Extract the object's docstring. If it does not have one,
# then return None (no test for this object).
if isinstance(obj, str):
# obj is a string in the case for objects in the polys package.
# Note that source_lines is a binary string (compiled polys
# modules), which can't be handled by _find_lineno so determine
# the line number here.
docstring = obj
matches = re.findall(r"line \d+", name)
assert len(matches) == 1, \
"string '%s' does not contain lineno " % name
# NOTE: this is not the exact linenumber but its better than no
# lineno ;)
lineno = int(matches[0][5:])
else:
docstring = getattr(obj, '__doc__', '')
if docstring is None:
docstring = ''
if not isinstance(docstring, str):
docstring = str(docstring)
# Don't bother if the docstring is empty.
if self._exclude_empty and not docstring:
return None
# check that properties have a docstring because _find_lineno
# assumes it
if isinstance(obj, property):
if obj.fget.__doc__ is None:
return None
# Find the docstring's location in the file.
if lineno is None:
obj = unwrap(obj)
# handling of properties is not implemented in _find_lineno so do
# it here
if hasattr(obj, 'func_closure') and obj.func_closure is not None:
tobj = obj.func_closure[0].cell_contents
elif isinstance(obj, property):
tobj = obj.fget
else:
tobj = obj
lineno = self._find_lineno(tobj, source_lines)
if lineno is None:
return None
# Return a DocTest for this object.
if module is None:
filename = None
else:
filename = getattr(module, '__file__', module.__name__)
if filename[-4:] in (".pyc", ".pyo"):
filename = filename[:-1]
globs['_doctest_depends_on'] = getattr(obj, '_doctest_depends_on', {})
return self._parser.get_doctest(docstring, globs, name,
filename, lineno)
| SymPyDocTestFinder |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol1.py | {
"start": 569,
"end": 790
} | class ____:
def send(self, data: float) -> int: ...
sender: Sender[float] = Sender_Impl()
new_sender: Sender[int]
# This should not generate an error because 'Sender' is contravariant.
new_sender = sender
| Sender_Impl |
python | pytest-dev__pytest-xdist | testing/test_looponfail.py | {
"start": 2957,
"end": 6695
} | class ____:
def test_nofailures(self, pytester: pytest.Pytester) -> None:
item = pytester.getitem("def test_func(): pass\n")
control = RemoteControl(item.config)
control.setup()
_topdir, failures = control.runsession()[:2]
assert not failures
def test_failures_somewhere(self, pytester: pytest.Pytester) -> None:
item = pytester.getitem("def test_func():\n assert 0\n")
control = RemoteControl(item.config)
control.setup()
failures = control.runsession()[0]
assert failures
control.setup()
item.path.write_text("def test_func():\n assert 1\n")
removepyc(item.path)
_topdir, failures = control.runsession()[:2]
assert not failures
def test_failure_change(self, pytester: pytest.Pytester) -> None:
modcol = pytester.getitem(
textwrap.dedent(
"""
def test_func():
assert 0
"""
)
)
control = RemoteControl(modcol.config)
control.loop_once()
assert control.failures
modcol_path = modcol.path
modcol_path.write_text(
textwrap.dedent(
"""
def test_func():
assert 1
def test_new():
assert 0
"""
)
)
removepyc(modcol_path)
control.loop_once()
assert not control.failures
control.loop_once()
assert control.failures
assert str(control.failures).find("test_new") != -1
def test_failure_subdir_no_init(
self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch
) -> None:
modcol = pytester.getitem(
textwrap.dedent(
"""
def test_func():
assert 0
"""
)
)
parent = modcol.path.parent.parent
monkeypatch.chdir(parent)
modcol.config.args = [
str(Path(x).relative_to(parent)) for x in modcol.config.args
]
control = RemoteControl(modcol.config)
control.loop_once()
assert control.failures
control.loop_once()
assert control.failures
def test_ignore_sys_path_hook_entry(
self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch
) -> None:
# Modifying sys.path as seen by the worker process is a bit tricky,
# because any changes made in the current process do not carry over.
# However, we can leverage the `sitecustomize` behavior to run arbitrary
# code when the subprocess interpreter is starting up. We just need to
# install our module in the search path, which we can accomplish by
# adding a temporary directory to PYTHONPATH.
tmpdir = tempfile.TemporaryDirectory()
with open(pathlib.Path(tmpdir.name) / "sitecustomize.py", "w") as custom:
print(
textwrap.dedent(
"""
import sys
sys.path.append('dummy.__path_hook__')
"""
),
file=custom,
)
monkeypatch.setenv("PYTHONPATH", tmpdir.name, prepend=":")
item = pytester.getitem(
textwrap.dedent(
"""
def test_func():
import sys
assert "dummy.__path_hook__" in sys.path
"""
)
)
control = RemoteControl(item.config)
control.setup()
_topdir, failures = control.runsession()[:2]
assert not failures
| TestRemoteControl |
python | getsentry__sentry | tests/sentry/integrations/slack/webhooks/commands/test_post.py | {
"start": 260,
"end": 889
} | class ____(SlackCommandsTest):
def test_invalid_signature(self) -> None:
# The `get_error_response` method doesn't add a signature to the request.
self.get_error_response(status_code=status.HTTP_401_UNAUTHORIZED)
def test_missing_team(self) -> None:
self.get_slack_response({"text": ""}, status_code=status.HTTP_400_BAD_REQUEST)
def test_idp_does_not_exist(self) -> None:
"""Test that get_identity fails if we cannot find a matching idp."""
data = self.send_slack_message("", team_id="slack:2")
assert DISCONNECTED_MESSAGE in get_response_text(data)
| SlackCommandsPostTest |
python | Netflix__metaflow | metaflow/exception.py | {
"start": 3596,
"end": 4059
} | class ____(MetaflowException):
headline = "Unknown decorator attribute"
def __init__(self, deconame, attr, defaults):
msg = (
"Decorator '{deco}' does not support the attribute '{attr}'. "
"These attributes are supported: {defaults}.".format(
deco=deconame, attr=attr, defaults=", ".join(defaults)
)
)
super(InvalidDecoratorAttribute, self).__init__(msg)
| InvalidDecoratorAttribute |
python | paramiko__paramiko | tests/auth.py | {
"start": 762,
"end": 4802
} | class ____:
"""
Most of these tests are explicit about the auth method they call.
This is because not too many other tests do so (they rely on the implicit
auth trigger of various connect() kwargs).
"""
def bad_auth_type(self):
"""
verify that we get the right exception when an unsupported auth
type is requested.
"""
# Server won't allow password auth for this user, so should fail
# and return just publickey allowed types
with server(
connect=dict(username="unknown", password="error"),
catch_error=True,
) as (_, _, err):
assert isinstance(err, BadAuthenticationType)
assert err.allowed_types == ["publickey"]
def bad_password(self):
"""
verify that a bad password gets the right exception, and that a retry
with the right password works.
"""
# NOTE: Transport.connect doesn't do any auth upfront if no userauth
# related kwargs given.
with server(defer=True) as (tc, ts):
# Auth once, badly
with raises(AuthenticationException):
tc.auth_password(username="slowdive", password="error")
# And again, correctly
tc.auth_password(username="slowdive", password="pygmalion")
def multipart_auth(self):
"""
verify that multipart auth works.
"""
with server(defer=True) as (tc, ts):
assert tc.auth_password(
username="paranoid", password="paranoid"
) == ["publickey"]
key = Ed25519Key.from_private_key_file(_support("ed25519.key"))
assert tc.auth_publickey(username="paranoid", key=key) == []
def interactive_auth(self):
"""
verify keyboard-interactive auth works.
"""
def handler(title, instructions, prompts):
self.got_title = title
self.got_instructions = instructions
self.got_prompts = prompts
return ["cat"]
with server(defer=True) as (tc, ts):
assert tc.auth_interactive("commie", handler) == []
assert self.got_title == "password"
assert self.got_prompts == [("Password", False)]
def interactive_fallback(self):
"""
verify that a password auth attempt will fallback to "interactive"
if password auth isn't supported but interactive is.
"""
with server(defer=True) as (tc, ts):
# This username results in an allowed_auth of just kbd-int,
# and has a configured interactive->response on the server.
assert tc.auth_password("commie", "cat") == []
def utf8(self):
"""
verify that utf-8 encoding happens in authentication.
"""
with server(defer=True) as (tc, ts):
assert tc.auth_password("utf8", unicodey) == []
def non_utf8(self):
"""
verify that non-utf-8 encoded passwords can be used for broken
servers.
"""
with server(defer=True) as (tc, ts):
assert tc.auth_password("non-utf8", "\xff") == []
def auth_exception_when_disconnected(self):
"""
verify that we catch a server disconnecting during auth, and report
it as an auth failure.
"""
with server(defer=True, skip_verify=True) as (tc, ts), raises(
AuthenticationException
):
tc.auth_password("bad-server", "hello")
def non_responsive_triggers_auth_exception(self):
"""
verify that authentication times out if server takes to long to
respond (or never responds).
"""
with server(defer=True, skip_verify=True) as (tc, ts), raises(
AuthenticationException
) as info:
tc.auth_timeout = 1 # 1 second, to speed up test
tc.auth_password("unresponsive-server", "hello")
assert "Authentication timeout" in str(info.value)
| AuthHandler_ |
python | gevent__gevent | src/gevent/tests/test__fileobject.py | {
"start": 1319,
"end": 10626
} | class ____(CleanupMixin,
greentest.TestCase):
# serves as a base for the concurrent tests too
WORKS_WITH_REGULAR_FILES = True
def setUp(self):
super().setUp()
# Try our best to run any pending __del__ methods. When we run
# multiple tests in sequence, because file descriptor numbers get
# reused, a test could open new FDs with the same numbers as some
# object (FileObjectPosix/GreenFileDescriptorIO) still waiting for
# __del__ to get called to close the FD. If GC runs and
# __del__ gets called while that second test is running, we
# get unexpected errors.
# This shows up on PyPy 3.11.
gc.collect()
def _getTargetClass(self):
return fileobject.FileObjectBlock
def _makeOne(self, *args, **kwargs):
return self._getTargetClass()(*args, **kwargs)
def _test_del(self, **kwargs):
r, w = self._pipe()
self._do_test_del((r, w), **kwargs)
def _do_test_del(self, pipe, **kwargs):
read_fd, write_fd = pipe
writer = self._makeOne(write_fd, 'wb', **kwargs)
writer.write(b'x')
try:
writer.flush()
except IOError:
# Sometimes seen on Windows/AppVeyor
print("Failed flushing fileobject", repr(writer), file=sys.stderr)
import traceback
traceback.print_exc()
import warnings
with warnings.catch_warnings():
warnings.simplefilter('ignore', ResourceWarning)
# Deliberately getting ResourceWarning with FileObject(Thread) under Py3
del writer
# PyPy, run RawIO.__del__ to close FD.
gc.collect()
if kwargs.get("close", True):
with self.assertRaises((OSError, IOError)):
# expected, because FileObject already closed it
os.close(write_fd)
else:
os.close(write_fd)
with self._makeOne(read_fd, 'rb') as fobj:
self.assertEqual(fobj.read(), b'x')
def test_del(self):
# Close should be true by default
self._test_del()
def test_del_close(self):
self._test_del(close=True)
@skipUnlessWorksWithRegularFiles
def test_seek(self):
fileno, path = self._mkstemp('.gevent.test__fileobject.test_seek')
s = b'a' * 1024
os.write(fileno, b'B' * 15)
os.write(fileno, s)
os.close(fileno)
with open(path, 'rb') as f:
f.seek(15)
native_data = f.read(1024)
with open(path, 'rb') as f_raw:
f = self._makeOne(f_raw, 'rb', close=False)
# On Python 3, all objects should have seekable.
# On Python 2, only our custom objects do.
self.assertTrue(f.seekable())
f.seek(15)
self.assertEqual(15, f.tell())
# Note that a duplicate close() of the underlying
# file descriptor can look like an OSError from this line
# as we exit the with block
fileobj_data = f.read(1024)
self.assertEqual(native_data, s)
self.assertEqual(native_data, fileobj_data)
def __check_native_matches(self, byte_data, open_mode,
meth='read', open_path=True,
**open_kwargs):
fileno, path = self._mkstemp('.gevent_test_' + open_mode)
os.write(fileno, byte_data)
os.close(fileno)
with io.open(path, open_mode, **open_kwargs) as f:
native_data = getattr(f, meth)()
if open_path:
with self._makeOne(path, open_mode, **open_kwargs) as f:
gevent_data = getattr(f, meth)()
else:
# Note that we don't use ``io.open()`` for the raw file,
# on Python 2. We want 'r' to mean what the usual call to open() means.
opener = io.open
with opener(path, open_mode, **open_kwargs) as raw:
with self._makeOne(raw) as f:
gevent_data = getattr(f, meth)()
self.assertEqual(native_data, gevent_data)
return gevent_data
@skipUnlessWorksWithRegularFiles
def test_str_default_to_native(self):
# With no 'b' or 't' given, read and write native str.
gevent_data = self.__check_native_matches(b'abcdefg', 'r')
self.assertIsInstance(gevent_data, str)
@skipUnlessWorksWithRegularFiles
def test_text_encoding(self):
gevent_data = self.__check_native_matches(
u'\N{SNOWMAN}'.encode('utf-8'),
'r+',
buffering=5, encoding='utf-8'
)
self.assertIsInstance(gevent_data, str)
@skipUnlessWorksWithRegularFiles
def test_does_not_leak_on_exception(self):
# If an exception occurs during opening,
# everything still gets cleaned up.
pass
@skipUnlessWorksWithRegularFiles
def test_rbU_produces_bytes_readline(self):
if sys.version_info > (3, 11):
self.skipTest("U file mode was removed in 3.11")
# Including U in rb still produces bytes.
# Note that the universal newline behaviour is
# essentially ignored in explicit bytes mode.
gevent_data = self.__check_native_matches(
b'line1\nline2\r\nline3\rlastline\n\n',
'rbU',
meth='readlines',
)
self.assertIsInstance(gevent_data[0], bytes)
self.assertEqual(len(gevent_data), 4)
@skipUnlessWorksWithRegularFiles
def test_rU_produces_native(self):
if sys.version_info > (3, 11):
self.skipTest("U file mode was removed in 3.11")
gevent_data = self.__check_native_matches(
b'line1\nline2\r\nline3\rlastline\n\n',
'rU',
meth='readlines',
)
self.assertIsInstance(gevent_data[0], str)
@skipUnlessWorksWithRegularFiles
def test_r_readline_produces_native(self):
gevent_data = self.__check_native_matches(
b'line1\n',
'r',
meth='readline',
)
self.assertIsInstance(gevent_data, str)
@skipUnlessWorksWithRegularFiles
def test_r_readline_on_fobject_produces_native(self):
gevent_data = self.__check_native_matches(
b'line1\n',
'r',
meth='readline',
open_path=False,
)
self.assertIsInstance(gevent_data, str)
def test_close_pipe(self):
# Issue #190, 203
r, w = os.pipe()
x = self._makeOne(r)
y = self._makeOne(w, 'w')
x.close()
y.close()
@skipUnlessWorksWithRegularFiles
@greentest.ignores_leakcheck
def test_name_after_close(self):
fileno, path = self._mkstemp('.gevent_test_named_path_after_close')
# Passing the fileno; the name is the same as the fileno, and
# doesn't change when closed.
f = self._makeOne(fileno)
nf = os.fdopen(fileno)
# On Python 2, os.fdopen() produces a name of <fdopen>;
# we follow the Python 3 semantics everywhere.
nf_name = '<fdopen>' if greentest.PY2 else fileno
self.assertEqual(f.name, fileno)
self.assertEqual(nf.name, nf_name)
# A file-like object that has no name; we'll close the
# `f` after this because we reuse the fileno, which
# gets passed to fcntl and so must still be valid
class Nameless(object):
def fileno(self):
return fileno
close = flush = isatty = closed = writable = lambda self: False
seekable = readable = lambda self: True
nameless = self._makeOne(Nameless(), 'rb')
with self.assertRaises(AttributeError):
getattr(nameless, 'name')
nameless.close()
with self.assertRaises(AttributeError):
getattr(nameless, 'name')
f.close()
try:
nf.close()
except OSError:
# OSError: Py3, IOError: Py2
pass
self.assertEqual(f.name, fileno)
self.assertEqual(nf.name, nf_name)
def check(arg):
f = self._makeOne(arg)
self.assertEqual(f.name, path)
f.close()
# Doesn't change after closed.
self.assertEqual(f.name, path)
# Passing the string
check(path)
# Passing an opened native object
with open(path) as nf:
check(nf)
# An io object
with io.open(path) as nf:
check(nf)
@skipUnlessWorksWithRegularFiles
def test_readinto_serial(self):
fileno, path = self._mkstemp('.gevent_test_readinto')
os.write(fileno, b'hello world')
os.close(fileno)
buf = bytearray(32)
mbuf = memoryview(buf)
def assertReadInto(byte_count, expected_data):
bytes_read = f.readinto(mbuf[:byte_count])
self.assertEqual(bytes_read, len(expected_data))
self.assertEqual(buf[:bytes_read], expected_data)
with self._makeOne(path, 'rb') as f:
assertReadInto(2, b'he')
assertReadInto(1, b'l')
assertReadInto(32, b'lo world')
assertReadInto(32, b'')
| TestFileObjectBlock |
python | pallets__jinja | tests/test_debug.py | {
"start": 348,
"end": 3704
} | class ____:
def assert_traceback_matches(self, callback, expected_tb):
with pytest.raises(Exception) as exc_info:
callback()
tb = format_exception(exc_info.type, exc_info.value, exc_info.tb)
m = re.search(expected_tb.strip(), "".join(tb))
assert m is not None, (
f"Traceback did not match:\n\n{''.join(tb)}\nexpected:\n{expected_tb}"
)
def test_runtime_error(self, fs_env):
def test():
tmpl.render(fail=lambda: 1 / 0)
tmpl = fs_env.get_template("broken.html")
self.assert_traceback_matches(
test,
r"""
File ".*?broken.html", line 2, in (top-level template code|<module>)
\{\{ fail\(\) \}\}(
\^{12})?
File ".*debug?.pyc?", line \d+, in <lambda>
tmpl\.render\(fail=lambda: 1 / 0\)(
~~\^~~)?
ZeroDivisionError: (int(eger)? )?division (or modulo )?by zero
""",
)
def test_syntax_error(self, fs_env):
# The trailing .*? is for PyPy 2 and 3, which don't seem to
# clear the exception's original traceback, leaving the syntax
# error in the middle of other compiler frames.
self.assert_traceback_matches(
lambda: fs_env.get_template("syntaxerror.html"),
"""(?sm)
File ".*?syntaxerror.html", line 4, in (template|<module>)
\\{% endif %\\}.*?
(jinja2\\.exceptions\\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja \
was looking for the following tags: 'endfor' or 'else'. The innermost block that needs \
to be closed is 'for'.
""",
)
def test_regular_syntax_error(self, fs_env):
def test():
raise TemplateSyntaxError("wtf", 42)
self.assert_traceback_matches(
test,
r"""
File ".*debug.pyc?", line \d+, in test
raise TemplateSyntaxError\("wtf", 42\)(
\^{36})?
(jinja2\.exceptions\.)?TemplateSyntaxError: wtf
line 42""",
)
def test_pickleable_syntax_error(self, fs_env):
original = TemplateSyntaxError("bad template", 42, "test", "test.txt")
unpickled = pickle.loads(pickle.dumps(original))
assert str(original) == str(unpickled)
assert original.name == unpickled.name
def test_include_syntax_error_source(self, filesystem_loader):
e = Environment(
loader=ChoiceLoader(
[
filesystem_loader,
DictLoader({"inc": "a\n{% include 'syntaxerror.html' %}\nb"}),
]
)
)
t = e.get_template("inc")
with pytest.raises(TemplateSyntaxError) as exc_info:
t.render()
assert exc_info.value.source is not None
def test_local_extraction(self):
from jinja2.debug import get_template_locals
from jinja2.runtime import missing
locals = get_template_locals(
{
"l_0_foo": 42,
"l_1_foo": 23,
"l_2_foo": 13,
"l_0_bar": 99,
"l_1_bar": missing,
"l_0_baz": missing,
}
)
assert locals == {"foo": 13, "bar": 99}
def test_get_corresponding_lineno_traceback(self, fs_env):
tmpl = fs_env.get_template("test.html")
assert tmpl.get_corresponding_lineno(1) == 1
| TestDebug |
python | huggingface__transformers | src/transformers/models/seed_oss/modeling_seed_oss.py | {
"start": 7121,
"end": 10352
} | class ____(nn.Module):
def __init__(self, config: SeedOssConfig, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = config.head_dim
self.num_key_value_heads = config.num_key_value_heads
self.num_attention_heads = config.num_attention_heads
self.num_key_value_groups = self.num_attention_heads // self.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.attention_dropout = config.attention_dropout
self.is_causal = True
self.q_proj = nn.Linear(
config.hidden_size, self.num_attention_heads * self.head_dim, bias=config.attention_bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(
self.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_out_bias
)
self.residual_dropout = config.residual_dropout
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: Optional[torch.Tensor],
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_values is not None:
# sin and cos are specific to RoPE models; cache_position needed for the static cache
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
attn_output = nn.functional.dropout(attn_output, p=self.residual_dropout, training=self.training)
return attn_output, attn_weights
| SeedOssAttention |
python | spack__spack | lib/spack/spack/enums.py | {
"start": 615,
"end": 770
} | class ____(enum.Enum):
"""Enum to specify the behavior of a propagated dependency"""
NONE = enum.auto()
PREFERENCE = enum.auto()
| PropagationPolicy |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 157025,
"end": 162585
} | class ____:
def test_rvgeneric_std(self):
# Regression test for #1191
assert_array_almost_equal(stats.t.std([5, 6]), [1.29099445, 1.22474487])
def test_moments_t(self):
# regression test for #8786
assert_equal(stats.t.stats(df=1, moments='mvsk'),
(np.inf, np.nan, np.nan, np.nan))
assert_equal(stats.t.stats(df=1.01, moments='mvsk'),
(0.0, np.inf, np.nan, np.nan))
assert_equal(stats.t.stats(df=2, moments='mvsk'),
(0.0, np.inf, np.nan, np.nan))
assert_equal(stats.t.stats(df=2.01, moments='mvsk'),
(0.0, 2.01/(2.01-2.0), np.nan, np.inf))
assert_equal(stats.t.stats(df=3, moments='sk'), (np.nan, np.inf))
assert_equal(stats.t.stats(df=3.01, moments='sk'), (0.0, np.inf))
assert_equal(stats.t.stats(df=4, moments='sk'), (0.0, np.inf))
assert_allclose(stats.t.stats(df=4.01, moments='sk'), (0.0, 6.0/(4.01 - 4.0)),
rtol=1e-14)
def test_t_entropy(self):
df = [1, 2, 25, 100]
# Expected values were computed with mpmath.
expected = [2.5310242469692907, 1.9602792291600821,
1.459327578078393, 1.4289633653182439]
assert_allclose(stats.t.entropy(df), expected, rtol=1e-13)
@pytest.mark.parametrize("v, ref",
[(100, 1.4289633653182439),
(1e+100, 1.4189385332046727)])
def test_t_extreme_entropy(self, v, ref):
# Reference values were calculated with mpmath:
# from mpmath import mp
# mp.dps = 500
#
# def t_entropy(v):
# v = mp.mpf(v)
# C = (v + mp.one) / 2
# A = C * (mp.digamma(C) - mp.digamma(v / 2))
# B = 0.5 * mp.log(v) + mp.log(mp.beta(v / 2, mp.one / 2))
# h = A + B
# return float(h)
assert_allclose(stats.t.entropy(v), ref, rtol=1e-14)
@pytest.mark.parametrize("methname", ["pdf", "logpdf", "cdf",
"ppf", "sf", "isf"])
@pytest.mark.parametrize("df_infmask", [[0, 0], [1, 1], [0, 1],
[[0, 1, 0], [1, 1, 1]],
[[1, 0], [0, 1]],
[[0], [1]]])
def test_t_inf_df(self, methname, df_infmask):
df_infmask = np.asarray(df_infmask, dtype=bool)
rng = np.random.default_rng(5442451539)
df = rng.uniform(0, 10, size=df_infmask.shape)
x = rng.standard_normal(df_infmask.shape)
df[df_infmask] = np.inf
t_dist = stats.t(df=df, loc=3, scale=1)
t_dist_ref = stats.t(df=df[~df_infmask], loc=3, scale=1)
norm_dist = stats.norm(loc=3, scale=1)
t_meth = getattr(t_dist, methname)
t_meth_ref = getattr(t_dist_ref, methname)
norm_meth = getattr(norm_dist, methname)
res = t_meth(x)
assert_allclose(res[df_infmask], norm_meth(x[df_infmask]), rtol=5e-15)
assert_equal(res[~df_infmask], t_meth_ref(x[~df_infmask]))
@pytest.mark.parametrize("df_infmask", [[0, 0], [1, 1], [0, 1],
[[0, 1, 0], [1, 1, 1]],
[[1, 0], [0, 1]],
[[0], [1]]])
def test_t_inf_df_stats_entropy(self, df_infmask):
df_infmask = np.asarray(df_infmask, dtype=bool)
rng = np.random.default_rng(5442451539)
df = rng.uniform(0, 10, size=df_infmask.shape)
df[df_infmask] = np.inf
res = stats.t.stats(df=df, loc=3, scale=1, moments='mvsk')
res_ex_inf = stats.norm.stats(loc=3, scale=1, moments='mvsk')
res_ex_noinf = stats.t.stats(df=df[~df_infmask], loc=3, scale=1,
moments='mvsk')
for i in range(4):
assert_equal(res[i][df_infmask], res_ex_inf[i])
assert_equal(res[i][~df_infmask], res_ex_noinf[i])
res = stats.t.entropy(df=df, loc=3, scale=1)
res_ex_inf = stats.norm.entropy(loc=3, scale=1)
res_ex_noinf = stats.t.entropy(df=df[~df_infmask], loc=3, scale=1)
assert_equal(res[df_infmask], res_ex_inf)
assert_equal(res[~df_infmask], res_ex_noinf)
def test_logpdf_pdf(self):
# reference values were computed via the reference distribution, e.g.
# mp.dps = 500; StudentT(df=df).logpdf(x), StudentT(df=df).pdf(x)
x = [1, 1e3, 10, 1]
df = [1e100, 1e50, 1e20, 1]
logpdf_ref = [-1.4189385332046727, -500000.9189385332,
-50.918938533204674, -1.8378770664093456]
pdf_ref = [0.24197072451914334, 0,
7.69459862670642e-23, 0.15915494309189535]
assert_allclose(stats.t.logpdf(x, df), logpdf_ref, rtol=1e-14)
assert_allclose(stats.t.pdf(x, df), pdf_ref, rtol=1e-14)
# Reference values were computed with mpmath, and double-checked with
# Wolfram Alpha.
@pytest.mark.parametrize('x, df, ref',
[(-75.0, 15, -46.76036184546812),
(0, 15, -0.6931471805599453),
(75.0, 15, -4.9230344937641665e-21)])
def test_logcdf_logsf(self, x, df, ref):
logcdf = stats.t.logcdf(x, df)
assert_allclose(logcdf, ref, rtol=5e-15)
# The reference value is logcdf(x, df) == logsf(-x, df).
logsf = stats.t.logsf(-x, df)
assert_allclose(logsf, ref, rtol=5e-15)
| TestStudentT |
python | astropy__astropy | astropy/units/tests/test_logarithmic.py | {
"start": 34808,
"end": 36704
} | class ____:
@pytest.mark.parametrize(
"method",
(
"mean",
"min",
"max",
"round",
"trace",
"std",
"var",
"diff",
"ediff1d",
),
)
@log_quantity_parametrization
def test_always_ok(self, method, mag):
res = getattr(mag, method)()
assert np.all(res.value == getattr(mag._function_view, method)().value)
if method in ("std", "diff", "ediff1d"):
assert res.unit == u.mag()
elif method == "var":
assert res.unit == u.mag**2
else:
assert res.unit == mag.unit
@pytest.mark.skipif(not NUMPY_LT_2_0, reason="ptp method removed in numpy 2.0")
@log_quantity_parametrization
def test_always_ok_ptp(self, mag):
res = mag.ptp()
assert np.all(res.value == mag._function_view.ptp().value)
assert res.unit == u.mag()
@log_quantity_parametrization
def test_clip(self, mag):
assert np.all(
mag.clip(2.0 * mag.unit, 4.0 * mag.unit).value == mag.value.clip(2.0, 4.0)
)
@pytest.mark.parametrize("method", ("sum", "cumsum"))
def test_ok_if_dimensionless(self, method):
res = getattr(m1, method)()
assert np.all(res.value == getattr(m1, method)().value)
assert res.unit == m1.unit
@pytest.mark.parametrize("method", ("sum", "cumsum"))
def test_not_ok_if_not_dimensionless(self, method):
with pytest.raises(TypeError):
getattr(mJy, method)()
def test_dot(self):
assert np.all(m1.dot(m1).value == m1.value.dot(m1.value))
@pytest.mark.parametrize("method", ("prod", "cumprod"))
@log_quantity_parametrization
def test_never_ok(self, method, mag):
with pytest.raises(TypeError):
getattr(mag, method)()
| TestLogQuantityMethods |
python | openai__openai-python | src/openai/types/beta/threads/image_url_content_block_param.py | {
"start": 269,
"end": 447
} | class ____(TypedDict, total=False):
image_url: Required[ImageURLParam]
type: Required[Literal["image_url"]]
"""The type of the content part."""
| ImageURLContentBlockParam |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_bitcoin_address_positive_balance.py | {
"start": 1054,
"end": 2098
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_bitcoin_address_positive_balance"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.apply(lambda x: has_btc_address_positive_balance(x))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
| ColumnValuesBitcoinAddressPositiveBalance |
python | Lightning-AI__lightning | src/lightning/pytorch/loops/evaluation_loop.py | {
"start": 2207,
"end": 2305
} | class ____:
NONE = "none"
RESTARTED_MID_EVALUATION = "restarted_mid_evaluation"
| RestartStage |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/execution_api/datamodels/asset.py | {
"start": 1275,
"end": 1916
} | class ____(StrictBaseModel):
"""
Profile of an asset-like object.
Asset will have name, uri defined, with type set to 'Asset'.
AssetNameRef will have name defined, type set to 'AssetNameRef'.
AssetUriRef will have uri defined, type set to 'AssetUriRef'.
AssetAlias will have name defined, type set to 'AssetAlias'.
Note that 'type' here is distinct from 'asset_type' the user declares on an
Asset (or subclass). This field is for distinguishing between different
asset-related types (Asset, AssetRef, or AssetAlias).
"""
name: str | None = None
uri: str | None = None
type: str
| AssetProfile |
python | cython__cython | Cython/Compiler/ParseTreeTransforms.py | {
"start": 118389,
"end": 121930
} | class ____(CythonTransform):
def visit_ModuleNode(self, node):
node.scope.infer_types()
node.body = node.body.analyse_expressions(node.scope)
self.positions = [{node.pos}]
self.visitchildren(node)
self._build_positions(node)
return node
def visit_FuncDefNode(self, node):
node.local_scope.infer_types()
node.body = node.body.analyse_expressions(node.local_scope)
self.positions[-1].add(node.pos)
if node.is_wrapper:
# Share positions between function and Python wrapper.
local_positions = self.positions[-1]
else:
local_positions = {node.pos}
self.positions.append(local_positions)
self.visitchildren(node)
self._build_positions(node)
return node
def visit_ScopedExprNode(self, node):
if node.has_local_scope:
node.expr_scope.infer_types()
node = node.analyse_scoped_expressions(node.expr_scope)
self.visit_ExprNode(node)
return node
def visit_IndexNode(self, node):
"""
Replace index nodes used to specialize cdef functions with fused
argument types with the Attribute- or NameNode referring to the
function. We then need to copy over the specialization properties to
the attribute or name node.
Because the indexing might be a Python indexing operation on a fused
function, or (usually) a Cython indexing operation, we need to
re-analyse the types.
"""
self.visit_ExprNode(node)
if node.is_fused_index and not node.type.is_error:
node = node.base
return node
# Build the line table according to PEP-626.
# We mostly just do this here to avoid yet another transform traversal.
def visit_ExprNode(self, node):
self.positions[-1].add(node.pos)
self.visitchildren(node)
return node
def visit_StatNode(self, node):
self.positions[-1].add(node.pos)
self.visitchildren(node)
return node
def _build_positions(self, func_node):
"""
Build the PEP-626 line table and "bytecode-to-position" mapping used for CodeObjects.
"""
# Code can originate from different source files and string code fragments, even within a single function.
# Thus, it's not completely correct to just ignore the source files when sorting the line numbers,
# but it also doesn't hurt much for the moment. Eventually, we might need different CodeObjects
# even within a single function if it uses code from different sources / line number ranges.
positions: list = sorted(
self.positions.pop(),
key=itemgetter(1, 2), # (line, column)
# Build ranges backwards to know the end column before we see the start column in the same line.
reverse=True,
)
next_line = -1
next_column_in_line = 0
ranges = []
for _, line, start_column in positions:
ranges.append((line, line, start_column, next_column_in_line if line == next_line else start_column + 1))
next_line, next_column_in_line = line, start_column
ranges.reverse()
func_node.node_positions = ranges
positions.reverse()
i: cython.Py_ssize_t
func_node.local_scope.node_positions_to_offset = {
position: i
for i, position in enumerate(positions)
}
| AnalyseExpressionsTransform |
python | huggingface__transformers | src/transformers/models/luke/modeling_luke.py | {
"start": 9078,
"end": 10337
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Classification (or regression if config.num_labels==1) loss.
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
Classification (or regression if config.num_labels==1) scores (before SoftMax).
entity_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, entity_length, hidden_size)`. Entity hidden-states of the model at the output of each
layer plus the initial entity embedding outputs.
"""
loss: Optional[torch.FloatTensor] = None
logits: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
entity_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for outputs of token classification models.
"""
)
| LukeSequenceClassifierOutput |
python | davidhalter__jedi | jedi/inference/names.py | {
"start": 2742,
"end": 3275
} | class ____(AbstractNameDefinition):
"""
When you e.g. want to complete dicts keys, you probably want to complete
string literals, which is not really a name, but for Jedi we use this
concept of Name for completions as well.
"""
is_value_name = False
def __init__(self, inference_state, string):
self.inference_state = inference_state
self.string_name = string
self.parent_context = inference_state.builtins_module
def infer(self):
return NO_VALUES
| AbstractArbitraryName |
python | sqlalchemy__sqlalchemy | test/orm/test_session.py | {
"start": 20725,
"end": 44144
} | class ____(_fixtures.FixtureTest):
run_inserts = None
__prefer_requires__ = ("independent_connections",)
def test_info(self):
s = fixture_session()
eq_(s.info, {})
maker = sessionmaker(info={"global": True, "s1": 5})
s1 = maker()
s2 = maker(info={"s1": 6, "s2": True})
eq_(s1.info, {"global": True, "s1": 5})
eq_(s2.info, {"global": True, "s1": 6, "s2": True})
s2.info["global"] = False
s2.info["s1"] = 7
s3 = maker()
eq_(s3.info, {"global": True, "s1": 5})
maker2 = sessionmaker()
s4 = maker2(info={"s4": 8})
eq_(s4.info, {"s4": 8})
@testing.variation("session_type", ["plain", "sessionmaker"])
@testing.variation("merge", [True, False])
@testing.variation(
"method", ["scalar", "execute", "scalars", "get", "query"]
)
@testing.variation("add_statement_options", [True, False])
def test_execution_options(
self,
session_type: testing.Variation,
merge: testing.Variation,
method: testing.Variation,
add_statement_options: testing.Variation,
):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
session_execution_options = {
"populate_existing": True,
"autoflush": False,
"opt1": "z",
"opt5": "q",
}
expected_opts = session_execution_options
if add_statement_options:
statement_options = {"opt2": "w", "opt4": "y", "opt5": "w"}
expected_opts = {**expected_opts, **statement_options}
else:
statement_options = {}
if merge:
query_opts = {
"compiled_cache": {},
"opt1": "q",
"opt2": "p",
"opt3": "r",
"populate_existing": False,
}
expected_opts = {**expected_opts, **query_opts}
else:
query_opts = {}
if session_type.plain:
sess = Session(
testing.db, execution_options=session_execution_options
)
elif session_type.sessionmaker:
maker = sessionmaker(
testing.db, execution_options=session_execution_options
)
sess = maker()
else:
session_type.fail()
gather_options = {}
@event.listens_for(sess, "do_orm_execute")
def check(ctx: ORMExecuteState) -> None:
assert not gather_options
gather_options.update(ctx.execution_options)
if method.scalar:
statement = select(User).limit(1)
if add_statement_options:
statement = statement.execution_options(**statement_options)
sess.scalar(statement, execution_options=query_opts)
elif method.execute:
statement = select(User).limit(1)
if add_statement_options:
statement = statement.execution_options(**statement_options)
sess.execute(statement, execution_options=query_opts)
elif method.scalars:
statement = select(User).limit(1)
if add_statement_options:
statement = statement.execution_options(**statement_options)
sess.scalars(statement, execution_options=query_opts)
elif method.get:
if add_statement_options:
sess.get(
User,
1,
execution_options={**statement_options, **query_opts},
)
else:
sess.get(User, 1, execution_options=query_opts)
elif method.query:
q = sess.query(User).limit(1)
if add_statement_options:
q = q.execution_options(**statement_options)
q = q.execution_options(**query_opts)
q.all()
else:
method.fail()
sess.close()
for key, value in expected_opts.items():
eq_(gather_options[key], value)
def test_autocommit_kw_accepted_but_must_be_false(self):
Session(autocommit=False)
with expect_raises_message(
exc.ArgumentError, "autocommit=True is no longer supported"
):
Session(autocommit=True)
@testing.requires.independent_connections
@engines.close_open_connections
def test_autoflush(self):
User, users = self.classes.User, self.tables.users
bind = testing.db
self.mapper_registry.map_imperatively(User, users)
conn1 = bind.connect()
conn2 = bind.connect()
sess = Session(bind=conn1, autoflush=True)
u = User()
u.name = "ed"
sess.add(u)
u2 = sess.query(User).filter_by(name="ed").one()
assert u2 is u
eq_(conn1.exec_driver_sql("select count(1) from users").scalar(), 1)
eq_(conn2.exec_driver_sql("select count(1) from users").scalar(), 0)
sess.commit()
eq_(conn1.exec_driver_sql("select count(1) from users").scalar(), 1)
eq_(
bind.connect()
.exec_driver_sql("select count(1) from users")
.scalar(),
1,
)
sess.close()
def test_with_no_autoflush(self):
User, users = self.classes.User, self.tables.users
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
u = User()
u.name = "ed"
sess.add(u)
def go(obj):
assert u not in sess.query(User).all()
testing.run_as_contextmanager(sess.no_autoflush, go)
assert u in sess.new
assert u in sess.query(User).all()
assert u not in sess.new
def test_with_no_autoflush_after_exception(self):
sess = Session(autoflush=True)
assert_raises(
ZeroDivisionError,
testing.run_as_contextmanager,
sess.no_autoflush,
lambda obj: 1 / 0,
)
is_true(sess.autoflush)
def test_autoflush_exception_addition(self):
User, users = self.classes.User, self.tables.users
Address, addresses = self.classes.Address, self.tables.addresses
self.mapper_registry.map_imperatively(
User, users, properties={"addresses": relationship(Address)}
)
self.mapper_registry.map_imperatively(Address, addresses)
s = Session(testing.db)
u1 = User(name="first")
s.add(u1)
s.commit()
u1.addresses.append(Address(email=None))
# will raise for null email address
assert_raises_message(
exc.DBAPIError,
".*raised as a result of Query-invoked autoflush; consider using "
"a session.no_autoflush block.*",
s.query(User).first,
)
def test_deleted_flag(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
u1 = User(name="u1")
sess.add(u1)
sess.commit()
sess.delete(u1)
sess.flush()
assert u1 not in sess
assert_raises(exc.InvalidRequestError, sess.add, u1)
assert sess.in_transaction()
sess.rollback()
assert u1 in sess
sess.delete(u1)
sess.commit()
assert u1 not in sess
assert_raises(exc.InvalidRequestError, sess.add, u1)
make_transient(u1)
sess.add(u1)
sess.commit()
eq_(sess.query(User).count(), 1)
@testing.requires.sane_rowcount
def test_deleted_adds_to_imap_unconditionally(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
u1 = User(name="u1")
sess.add(u1)
sess.commit()
sess.delete(u1)
sess.flush()
# object is not in session
assert u1 not in sess
# but it *is* attached
assert u1._sa_instance_state.session_id == sess.hash_key
# mark as deleted again
sess.delete(u1)
# in the session again
assert u1 in sess
# commit proceeds w/ warning
with assertions.expect_warnings(
"DELETE statement on table 'users' "
r"expected to delete 1 row\(s\); 0 were matched."
):
sess.commit()
@testing.requires.independent_connections
@engines.close_open_connections
def test_autoflush_unbound(self):
User, users = self.classes.User, self.tables.users
self.mapper_registry.map_imperatively(User, users)
with fixture_session(autoflush=True) as sess:
u = User()
u.name = "ed"
sess.add(u)
u2 = sess.query(User).filter_by(name="ed").one()
is_(u2, u)
eq_(
sess.execute(
text("select count(1) from users"),
bind_arguments=dict(mapper=User),
).scalar(),
1,
)
eq_(
testing.db.connect()
.exec_driver_sql("select count(1) from users")
.scalar(),
0,
)
sess.commit()
eq_(
sess.execute(
text("select count(1) from users"),
bind_arguments=dict(mapper=User),
).scalar(),
1,
)
eq_(
testing.db.connect()
.exec_driver_sql("select count(1) from users")
.scalar(),
1,
)
@engines.close_open_connections
def test_autoflush_2(self):
User, users = self.classes.User, self.tables.users
self.mapper_registry.map_imperatively(User, users)
conn1 = testing.db.connect()
sess = Session(bind=conn1, autoflush=True)
u = User()
u.name = "ed"
sess.add(u)
sess.commit()
assert (
conn1.exec_driver_sql("select count(1) from users").scalar() == 1
)
assert (
testing.db.connect()
.exec_driver_sql("select count(1) from users")
.scalar()
== 1
)
sess.commit()
def test_active_flag_autobegin(self):
sess = Session(
bind=config.db,
)
assert sess.is_active
assert not sess.in_transaction()
sess.begin()
assert sess.is_active
sess.rollback()
assert sess.is_active
def test_active_flag_autobegin_future(self):
sess = Session(bind=config.db)
assert sess.is_active
assert not sess.in_transaction()
sess.begin()
assert sess.is_active
sess.rollback()
assert sess.is_active
def test_active_flag_partial_rollback(self):
sess = Session(
bind=config.db,
)
assert sess.is_active
assert not sess.in_transaction()
sess.begin()
assert sess.is_active
sess._autobegin_t()._begin()
sess.rollback()
assert sess.is_active
sess.rollback()
assert sess.is_active
@engines.close_open_connections
def test_add_delete(self):
User, Address, addresses, users = (
self.classes.User,
self.classes.Address,
self.tables.addresses,
self.tables.users,
)
s = fixture_session()
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(Address, cascade="all, delete")
},
)
self.mapper_registry.map_imperatively(Address, addresses)
user = User(name="u1")
assert_raises_message(
exc.InvalidRequestError, "is not persisted", s.delete, user
)
s.add(user)
s.commit()
user = s.query(User).one()
s.expunge(user)
assert user not in s
# modify outside of session, assert changes remain/get saved
user.name = "fred"
s.add(user)
assert user in s
assert user in s.dirty
s.commit()
assert s.query(User).count() == 1
user = s.query(User).one()
assert user.name == "fred"
# ensure its not dirty if no changes occur
s.expunge_all()
assert user not in s
s.add(user)
assert user in s
assert user not in s.dirty
s2 = fixture_session()
assert_raises_message(
exc.InvalidRequestError,
"is already attached to session",
s2.delete,
user,
)
u2 = s2.get(User, user.id)
s2.expunge(u2)
assert_raises_message(
exc.InvalidRequestError,
"another instance .* is already present",
s.delete,
u2,
)
s.expire(user)
s.expunge(user)
assert user not in s
s.delete(user)
assert user in s
s.flush()
assert user not in s
assert s.query(User).count() == 0
def test_already_attached(self):
User = self.classes.User
users = self.tables.users
self.mapper_registry.map_imperatively(User, users)
s1 = fixture_session()
s2 = fixture_session()
u1 = User(id=1, name="u1")
make_transient_to_detached(u1) # shorthand for actually persisting it
s1.add(u1)
assert_raises_message(
exc.InvalidRequestError,
"Object '<User.*?>' is already attached to session",
s2.add,
u1,
)
assert u1 not in s2
assert not s2.identity_map.keys()
def test_identity_conflict(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
with fixture_session() as s:
s.execute(users.delete())
u1 = User(name="ed")
s.add(u1)
s.flush()
s.expunge(u1)
u2 = s.query(User).first()
s.expunge(u2)
s.identity_map.add(sa.orm.attributes.instance_state(u1))
assert_raises_message(
exc.InvalidRequestError,
"Can't attach instance <User.*?>; another instance "
"with key .*? is already "
"present in this session.",
s.identity_map.add,
sa.orm.attributes.instance_state(u2),
)
def test_internal_identity_conflict_warning_weak(self):
# test for issue #4890
# see also test_naturalpks::ReversePKsTest::test_reverse
users, User = self.tables.users, self.classes.User
addresses, Address = self.tables.addresses, self.classes.Address
self.mapper_registry.map_imperatively(
User,
users,
properties={"addresses": relationship(Address, backref="user")},
)
self.mapper_registry.map_imperatively(Address, addresses)
session = fixture_session()
@event.listens_for(session, "after_flush")
def load_collections(session, flush_context):
for target in set(session.new).union(session.dirty):
if isinstance(target, User):
target.addresses
u1 = User(name="u1")
a1 = Address(email_address="e1", user=u1)
session.add_all([u1, a1])
session.flush()
session.expire_all()
# create new Address via backref, so that u1.addresses remains
# expired and a2 is in pending mutations
a2 = Address(email_address="e2", user=u1)
assert "addresses" not in inspect(u1).dict
assert a2 in inspect(u1)._pending_mutations["addresses"].added_items
# this is needed now that cascade_backrefs is turned off
session.add(a2)
with assertions.expect_warnings(
r"Identity map already had an identity "
r"for \(.*Address.*\), replacing"
):
session.flush()
def test_pickled_update(self):
users, User = self.tables.users, pickleable.User
self.mapper_registry.map_imperatively(User, users)
sess1 = fixture_session()
sess2 = fixture_session()
u1 = User(name="u1")
sess1.add(u1)
assert_raises_message(
exc.InvalidRequestError,
"already attached to session",
sess2.add,
u1,
)
u2 = pickle.loads(pickle.dumps(u1))
sess2.add(u2)
def test_duplicate_update(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
Session = sessionmaker()
sess = fixture_session()
u1 = User(name="u1")
sess.add(u1)
sess.flush()
assert u1.id is not None
sess.expunge(u1)
assert u1 not in sess
assert Session.object_session(u1) is None
u2 = sess.get(User, u1.id)
assert u2 is not None and u2 is not u1
assert u2 in sess
assert_raises_message(
exc.InvalidRequestError,
"Can't attach instance <User.*?>; another instance "
"with key .*? is already "
"present in this session.",
sess.add,
u1,
)
sess.expunge(u2)
assert u2 not in sess
assert Session.object_session(u2) is None
u1.name = "John"
u2.name = "Doe"
sess.add(u1)
assert u1 in sess
assert Session.object_session(u1) is sess
sess.flush()
sess.expunge_all()
u3 = sess.get(User, u1.id)
assert u3 is not u1 and u3 is not u2 and u3.name == u1.name
def test_no_double_save(self):
users = self.tables.users
sess = fixture_session()
class Foo:
def __init__(self):
sess.add(self)
class Bar(Foo):
def __init__(self):
sess.add(self)
Foo.__init__(self)
self.mapper_registry.map_imperatively(Foo, users)
self.mapper_registry.map_imperatively(Bar, users)
b = Bar()
assert b in sess
assert len(list(sess)) == 1
def test_identity_map_mutate(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
sess.add_all([User(name="u1"), User(name="u2"), User(name="u3")])
sess.commit()
# TODO: what are we testing here ? that iteritems() can
# withstand a change? should this be
# more directly attempting to manipulate the identity_map ?
u1, u2, u3 = sess.query(User).all()
for i, (key, value) in enumerate(iter(sess.identity_map.items())):
if i == 2:
del u3
gc_collect()
def _test_extra_dirty_state(self):
users, User = self.tables.users, self.classes.User
m = self.mapper_registry.map_imperatively(User, users)
s = fixture_session()
@event.listens_for(m, "after_update")
def e(mapper, conn, target):
sess = object_session(target)
for entry in list(sess.identity_map.values()):
entry.name = "5"
a1, a2 = User(name="1"), User(name="2")
s.add_all([a1, a2])
s.commit()
a1.name = "3"
return s, a1, a2
def test_extra_dirty_state_post_flush_warning(self):
s, a1, a2 = self._test_extra_dirty_state()
assert_warns_message(
exc.SAWarning,
"Attribute history events accumulated on 1 previously "
"clean instances",
s.commit,
)
def test_extra_dirty_state_post_flush_state(self):
s, a1, a2 = self._test_extra_dirty_state()
canary = []
@event.listens_for(s, "after_flush_postexec")
def e(sess, ctx):
canary.append(bool(sess.identity_map._modified))
@testing.emits_warning("Attribute")
def go():
s.commit()
go()
eq_(canary, [False])
def test_deleted_auto_expunged(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
sess.add(User(name="x"))
sess.commit()
u1 = sess.query(User).first()
sess.delete(u1)
assert not was_deleted(u1)
sess.flush()
assert was_deleted(u1)
assert u1 not in sess
assert object_session(u1) is sess
sess.commit()
assert object_session(u1) is None
def test_explicit_expunge_pending(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
u1 = User(name="x")
sess.add(u1)
sess.flush()
sess.expunge(u1)
assert u1 not in sess
assert object_session(u1) is None
sess.rollback()
assert u1 not in sess
assert object_session(u1) is None
def test_explicit_expunge_deleted(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
sess.add(User(name="x"))
sess.commit()
u1 = sess.query(User).first()
sess.delete(u1)
sess.flush()
assert was_deleted(u1)
assert u1 not in sess
assert object_session(u1) is sess
sess.expunge(u1)
assert was_deleted(u1)
assert u1 not in sess
assert object_session(u1) is None
sess.rollback()
assert was_deleted(u1)
assert u1 not in sess
assert object_session(u1) is None
@testing.combinations(True, False, "default", argnames="close_resets_only")
@testing.variation("method", ["close", "reset"])
def test_session_close_resets_only(self, close_resets_only, method):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
if close_resets_only is True:
kw = {"close_resets_only": True}
elif close_resets_only is False:
kw = {"close_resets_only": False}
else:
eq_(close_resets_only, "default")
kw = {}
s = fixture_session(**kw)
u1 = User()
s.add(u1)
assertions.in_(u1, s)
if method.reset:
s.reset()
elif method.close:
s.close()
else:
method.fail()
assertions.not_in(u1, s)
u2 = User()
if method.close and close_resets_only is False:
with expect_raises_message(
exc.InvalidRequestError,
"This Session has been permanently closed and is unable "
"to handle any more transaction requests.",
):
s.add(u2)
assertions.not_in(u2, s)
else:
s.add(u2)
assertions.in_(u2, s)
| SessionStateTest |
python | lazyprogrammer__machine_learning_examples | supervised_class2/rf_regression.py | {
"start": 1428,
"end": 4287
} | class ____:
def fit(self, df):
self.scalers = {}
for col in NUMERICAL_COLS:
scaler = StandardScaler()
scaler.fit(df[col].values.reshape(-1, 1))
self.scalers[col] = scaler
def transform(self, df):
N, _ = df.shape
D = len(NUMERICAL_COLS) + len(NO_TRANSFORM)
X = np.zeros((N, D))
i = 0
for col, scaler in iteritems(self.scalers):
X[:,i] = scaler.transform(df[col].values.reshape(-1, 1)).flatten()
i += 1
for col in NO_TRANSFORM:
X[:,i] = df[col]
i += 1
return X
def fit_transform(self, df):
self.fit(df)
return self.transform(df)
def get_data():
df = pd.read_csv('housing.data', header=None, delim_whitespace=True)
df.columns = [
'crim', # numerical
'zn', # numerical
'nonretail', # numerical
'river', # binary
'nox', # numerical
'rooms', # numerical
'age', # numerical
'dis', # numerical
'rad', # numerical
'tax', # numerical
'ptratio', # numerical
'b', # numerical
'lstat', # numerical
'medv', # numerical -- this is the target
]
# transform the data
transformer = DataTransformer()
# shuffle the data
N = len(df)
train_idx = np.random.choice(N, size=int(0.7*N), replace=False)
test_idx = [i for i in range(N) if i not in train_idx]
df_train = df.loc[train_idx]
df_test = df.loc[test_idx]
Xtrain = transformer.fit_transform(df_train)
Ytrain = np.log(df_train['medv'].values)
Xtest = transformer.transform(df_test)
Ytest = np.log(df_test['medv'].values)
return Xtrain, Ytrain, Xtest, Ytest
if __name__ == '__main__':
Xtrain, Ytrain, Xtest, Ytest = get_data()
model = RandomForestRegressor(n_estimators=100) # try 10, 20, 50, 100, 200
model.fit(Xtrain, Ytrain)
predictions = model.predict(Xtest)
# plot predictions vs targets
plt.scatter(Ytest, predictions)
plt.xlabel("target")
plt.ylabel("prediction")
ymin = np.round( min( min(Ytest), min(predictions) ) )
ymax = np.ceil( max( max(Ytest), max(predictions) ) )
print("ymin:", ymin, "ymax:", ymax)
r = range(int(ymin), int(ymax) + 1)
plt.plot(r, r)
plt.show()
plt.plot(Ytest, label='targets')
plt.plot(predictions, label='predictions')
plt.legend()
plt.show()
# do a quick baseline test
baseline = LinearRegression()
single_tree = DecisionTreeRegressor()
print("CV single tree:", cross_val_score(single_tree, Xtrain, Ytrain, cv=5).mean())
print("CV baseline:", cross_val_score(baseline, Xtrain, Ytrain, cv=5).mean())
print("CV forest:", cross_val_score(model, Xtrain, Ytrain, cv=5).mean())
# test score
single_tree.fit(Xtrain, Ytrain)
baseline.fit(Xtrain, Ytrain)
print("test score single tree:", single_tree.score(Xtest, Ytest))
print("test score baseline:", baseline.score(Xtest, Ytest))
print("test score forest:", model.score(Xtest, Ytest))
| DataTransformer |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/base_layer.py | {
"start": 128548,
"end": 129208
} | class ____(Layer):
"""Adds its inputs as a loss.
Attributes:
unconditional: Whether or not the loss should be conditioned on the inputs.
"""
def __init__(self, unconditional, **kwargs):
# Pass autocast=False, as there is no reason to cast loss to a different
# dtype.
kwargs['autocast'] = False
super(AddLoss, self).__init__(**kwargs)
self.unconditional = unconditional
def call(self, inputs):
self.add_loss(inputs, inputs=(not self.unconditional))
return inputs
def get_config(self):
config = super(AddLoss, self).get_config()
config.update({'unconditional': self.unconditional})
return config
| AddLoss |
python | huggingface__transformers | tests/models/cohere2_vision/test_image_processing_cohere2_vision.py | {
"start": 2864,
"end": 7895
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
fast_image_processing_class = Cohere2VisionImageProcessorFast if is_torchvision_available() else None
test_slow_image_processor = False
def setUp(self):
super().setUp()
self.image_processor_tester = Cohere2VisionImageProcessingTester(self)
@property
def image_processor_dict(self):
return self.image_processor_tester.prepare_image_processor_dict()
def test_image_processor_properties(self):
for image_processing_class in self.image_processor_list:
image_processor = image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(image_processor, "do_resize"))
self.assertTrue(hasattr(image_processor, "size"))
self.assertTrue(hasattr(image_processor, "do_normalize"))
self.assertTrue(hasattr(image_processor, "image_mean"))
self.assertTrue(hasattr(image_processor, "image_std"))
self.assertTrue(hasattr(image_processor, "do_convert_rgb"))
def test_call_pil(self):
for image_processing_class in self.image_processor_list:
# Initialize image_processing
image_processing = image_processing_class(**self.image_processor_dict)
# create random PIL images
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True)
for image in image_inputs:
self.assertIsInstance(image, Image.Image)
# Test not batched input
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
self.assertEqual(tuple(encoded_images.shape), (10, 3, 30, 30))
# Test batched
encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
self.assertEqual(tuple(encoded_images.shape), (70, 3, 30, 30))
def test_call_numpy(self):
for image_processing_class in self.image_processor_list:
# Initialize image_processing
image_processing = image_processing_class(**self.image_processor_dict)
# create random numpy tensors
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, numpify=True)
for image in image_inputs:
self.assertIsInstance(image, np.ndarray)
# Test not batched input
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
self.assertEqual(tuple(encoded_images.shape), (10, 3, 30, 30))
# Test batched
encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
self.assertEqual(tuple(encoded_images.shape), (70, 3, 30, 30))
def test_call_pytorch(self):
for image_processing_class in self.image_processor_list:
# Initialize image_processing
image_processing = image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True)
for image in image_inputs:
self.assertIsInstance(image, torch.Tensor)
# Test not batched input
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
self.assertEqual(tuple(encoded_images.shape), (10, 3, 30, 30))
# Test batched
encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
self.assertEqual(tuple(encoded_images.shape), (70, 3, 30, 30))
def test_call_numpy_4_channels(self):
for image_processing_class in self.image_processor_list:
# Test that can process images which have an arbitrary number of channels
# Initialize image_processing
image_processor = image_processing_class(**self.image_processor_dict)
# create random numpy tensors
self.image_processor_tester.num_channels = 4
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, numpify=True)
# Test not batched input
encoded_images = image_processor(
image_inputs[0],
return_tensors="pt",
input_data_format="channels_last",
image_mean=(0.0, 0.0, 0.0, 0.0),
image_std=(1.0, 1.0, 1.0, 1.0),
).pixel_values
self.assertEqual(tuple(encoded_images.shape), (10, 4, 30, 30))
# Test batched
encoded_images = image_processor(
image_inputs,
return_tensors="pt",
input_data_format="channels_last",
image_mean=(0.0, 0.0, 0.0, 0.0),
image_std=(1.0, 1.0, 1.0, 1.0),
).pixel_values
self.assertEqual(tuple(encoded_images.shape), (70, 4, 30, 30))
| Cohere2VisionProcessingTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.