language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | ray-project__ray | python/ray/llm/_internal/serve/core/engine/protocol.py | {
"start": 527,
"end": 6445
} | class ____(abc.ABC):
"""Base protocol class for all LLM engines."""
@abc.abstractmethod
def __init__(self, llm_config: LLMConfig):
"""Initialize the engine with the llm config"""
pass
@abc.abstractmethod
async def start(self):
"""Start the engine"""
pass
@abc.abstractmethod
async def resolve_lora(self, lora_model: DiskMultiplexConfig):
"""Mounts the LoRA model on the engine, given the local disk path."""
pass
@abc.abstractmethod
async def reset_prefix_cache(self) -> None:
"""Reset the prefix cache of the underlying engine"""
@abc.abstractmethod
async def chat(
self, request: "ChatCompletionRequest"
) -> AsyncGenerator[Union[str, "ChatCompletionResponse", "ErrorResponse"], None]:
"""Run a ChatCompletion with the engine.
To implement this method, you need to take a openAI compatible chat request, internally cast it to the target engine request type, and then call the engine's chat method.
This method is an async generator, so it yields chunks of response and when it is done, it returns None. We have the following convention:
- In case of streaming, yield a string representing data: <json_str>\n\n for each chunk. This should be already openAI compatible, so the higher level can just yield it to the client.
- In case of non-streaming, yield a single object of type ChatCompletionResponse.
- In case of error, yield a single object of type ErrorResponse.
Args:
request: The chat completion request.
Yields:
Union[str, ChatCompletionResponse, ErrorResponse]: A string representing a chunk of the response, a ChatCompletionResponse object, or an ErrorResponse object.
Returns:
None when the generator is done.
"""
pass
@abc.abstractmethod
async def completions(
self, request: "CompletionRequest"
) -> AsyncGenerator[Union[str, "CompletionResponse", "ErrorResponse"], None]:
"""Run a Completion with the engine.
Similar to chat, this method is an async generator, so it yields chunks
of response and when it is done, it returns None. We have the following
convention:
* In case of streaming, yield a string representing data:
<json_str>\n\n for each chunk. This should be already openAI compatible
with completion response format, so the higher level can just yield it
directly to the client.
* In case of non-streaming, yield a single object of type
CompletionResponse.
* In case of error, yield a single object of type ErrorResponse.
Args:
request: The completion request.
Yields:
Union[str, CompletionResponse, ErrorResponse]: A string
representing a chunk of the response, a CompletionResponse object,
or an ErrorResponse object.
Returns:
None when the generator is done.
"""
pass
@abc.abstractmethod
async def embeddings(
self, request: "EmbeddingRequest"
) -> AsyncGenerator[Union["EmbeddingResponse", "ErrorResponse"], None]:
"""Run an Embedding with the engine.
This method is different from chat and completion in that it does not
have streaming, but still it is an async generator that yields response
objects and when it is done, it returns None. We have the following
convention:
* yield a single object of type EmbeddingResponse.
* For errors, yield a single object of type ErrorResponse.
Args:
request: The embedding request.
Returns:
An async generator that yields EmbeddingResponse objects or ErrorResponse objects, and returns None when the generator is done.
"""
pass
@abc.abstractmethod
async def transcriptions(
self, request: "TranscriptionRequest"
) -> AsyncGenerator[Union[str, "TranscriptionResponse", "ErrorResponse"], None]:
"""Run a Transcription with the engine.
Similar to chat and completion, this method is an async generator,
so it yields chunks of response and when it is done, it returns None.
We have the following convention:
* In case of streaming, yield a string representing data:
<json_str>\n\n for each chunk. This should be already openAI compatible,
so the higher level can just yield it to the client.
* In case of non-streaming, yield a single object of type TranscriptionResponse.
* In case of error, yield a single object of type ErrorResponse.
Args:
request: The transcription request.
Yields:
Union[str, TranscriptionResponse, ErrorResponse]: A string
representing a chunk of the response, a TranscriptionResponse object,
or an ErrorResponse object.
Returns:
None when the generator is done.
"""
pass
async def check_health(self) -> None:
"""Check the health of the engine.
Does not return anything. Raise error when the engine is dead and needs
to be restarted.
"""
return
##############################################################
# Optional methods
# These methods will be implemented in the future to allow
# more granular life-cycle management of the engine.
# e.g. in usecases like RL training, we need to put the engine
# to sleep during training and wake up during rollouts.
##############################################################
async def sleep(self):
"""Puts the engine to sleep"""
pass
async def wakeup(self):
"""Wakes up the engine"""
pass
def shutdown(self):
"""Shuts down the engine"""
pass
| LLMEngine |
python | coleifer__peewee | tests/db_tests.py | {
"start": 819,
"end": 11659
} | class ____(DatabaseTestCase):
database = db_loader('sqlite3')
def test_pragmas(self):
self.database.cache_size = -2048
self.assertEqual(self.database.cache_size, -2048)
self.database.cache_size = -4096
self.assertEqual(self.database.cache_size, -4096)
self.database.foreign_keys = 'on'
self.assertEqual(self.database.foreign_keys, 1)
self.database.foreign_keys = 'off'
self.assertEqual(self.database.foreign_keys, 0)
def test_appid_user_version(self):
self.assertEqual(self.database.application_id, 0)
self.assertEqual(self.database.user_version, 0)
self.database.application_id = 1
self.database.user_version = 2
self.assertEqual(self.database.application_id, 1)
self.assertEqual(self.database.user_version, 2)
self.assertTrue(self.database.close())
self.assertTrue(self.database.connect())
self.assertEqual(self.database.application_id, 1)
self.assertEqual(self.database.user_version, 2)
def test_timeout_semantics(self):
self.assertEqual(self.database.timeout, 5)
self.assertEqual(self.database.pragma('busy_timeout'), 5000)
self.database.timeout = 2.5
self.assertEqual(self.database.timeout, 2.5)
self.assertEqual(self.database.pragma('busy_timeout'), 2500)
self.database.close()
self.database.connect()
self.assertEqual(self.database.timeout, 2.5)
self.assertEqual(self.database.pragma('busy_timeout'), 2500)
def test_pragmas_deferred(self):
pragmas = (('journal_mode', 'wal'),)
db = SqliteDatabase(None, pragmas=pragmas)
self.assertEqual(db._pragmas, pragmas)
# Test pragmas preserved after initializing.
db.init(':memory:')
self.assertEqual(db._pragmas, pragmas)
db = SqliteDatabase(None)
self.assertEqual(db._pragmas, ())
# Test pragmas are set and subsequently overwritten.
db.init(':memory:', pragmas=pragmas)
self.assertEqual(db._pragmas, pragmas)
db.init(':memory:', pragmas=())
self.assertEqual(db._pragmas, ())
# Test when specified twice, the previous value is overwritten.
db = SqliteDatabase(None, pragmas=pragmas)
db.init(':memory:', pragmas=(('cache_size', -8000),))
self.assertEqual(db._pragmas, (('cache_size', -8000),))
def test_pragmas_as_dict(self):
pragmas = {'journal_mode': 'wal'}
pragma_list = [('journal_mode', 'wal')]
db = SqliteDatabase(':memory:', pragmas=pragmas)
self.assertEqual(db._pragmas, pragma_list)
# Test deferred databases correctly handle pragma dicts.
db = SqliteDatabase(None, pragmas=pragmas)
self.assertEqual(db._pragmas, pragma_list)
db.init(':memory:')
self.assertEqual(db._pragmas, pragma_list)
db.init(':memory:', pragmas={})
self.assertEqual(db._pragmas, [])
def test_pragmas_permanent(self):
db = SqliteDatabase(':memory:')
db.execute_sql('pragma foreign_keys=0')
self.assertEqual(db.foreign_keys, 0)
db.pragma('foreign_keys', 1, True)
self.assertEqual(db.foreign_keys, 1)
db.close()
db.connect()
self.assertEqual(db.foreign_keys, 1)
def test_context_settings(self):
class TestDatabase(Database):
field_types = {'BIGINT': 'TEST_BIGINT', 'TEXT': 'TEST_TEXT'}
operations = {'LIKE': '~', 'NEW': '->>'}
param = '$'
test_db = TestDatabase(None)
state = test_db.get_sql_context().state
self.assertEqual(state.field_types['BIGINT'], 'TEST_BIGINT')
self.assertEqual(state.field_types['TEXT'], 'TEST_TEXT')
self.assertEqual(state.field_types['INT'], FIELD.INT)
self.assertEqual(state.field_types['VARCHAR'], FIELD.VARCHAR)
self.assertEqual(state.operations['LIKE'], '~')
self.assertEqual(state.operations['NEW'], '->>')
self.assertEqual(state.operations['ILIKE'], 'ILIKE')
self.assertEqual(state.param, '$')
self.assertEqual(state.quote, '""')
test_db2 = TestDatabase(None, field_types={'BIGINT': 'XXX_BIGINT',
'INT': 'XXX_INT'})
state = test_db2.get_sql_context().state
self.assertEqual(state.field_types['BIGINT'], 'XXX_BIGINT')
self.assertEqual(state.field_types['TEXT'], 'TEST_TEXT')
self.assertEqual(state.field_types['INT'], 'XXX_INT')
self.assertEqual(state.field_types['VARCHAR'], FIELD.VARCHAR)
def test_connection_state(self):
conn = self.database.connection()
self.assertFalse(self.database.is_closed())
self.database.close()
self.assertTrue(self.database.is_closed())
conn = self.database.connection()
self.assertFalse(self.database.is_closed())
def test_db_context_manager(self):
self.database.close()
self.assertTrue(self.database.is_closed())
with self.database:
self.assertFalse(self.database.is_closed())
self.assertTrue(self.database.is_closed())
self.database.connect()
self.assertFalse(self.database.is_closed())
# Enter context with an already-open db.
with self.database:
self.assertFalse(self.database.is_closed())
# Closed after exit.
self.assertTrue(self.database.is_closed())
def test_connection_initialization(self):
state = {'count': 0}
class TestDatabase(SqliteDatabase):
def _initialize_connection(self, conn):
state['count'] += 1
db = TestDatabase(':memory:')
self.assertEqual(state['count'], 0)
conn = db.connection()
self.assertEqual(state['count'], 1)
# Since already connected, nothing happens here.
conn = db.connection()
self.assertEqual(state['count'], 1)
def test_connect_semantics(self):
state = {'count': 0}
class TestDatabase(SqliteDatabase):
def _initialize_connection(self, conn):
state['count'] += 1
db = TestDatabase(':memory:')
db.connect()
self.assertEqual(state['count'], 1)
self.assertRaises(OperationalError, db.connect)
self.assertEqual(state['count'], 1)
self.assertFalse(db.connect(reuse_if_open=True))
self.assertEqual(state['count'], 1)
with db:
self.assertEqual(state['count'], 1)
self.assertFalse(db.is_closed())
self.assertTrue(db.is_closed())
with db:
self.assertEqual(state['count'], 2)
def test_execute_sql(self):
self.database.execute_sql('CREATE TABLE register (val INTEGER);')
self.database.execute_sql('INSERT INTO register (val) VALUES (?), (?)',
(1337, 31337))
cursor = self.database.execute_sql(
'SELECT val FROM register ORDER BY val')
self.assertEqual(cursor.fetchall(), [(1337,), (31337,)])
self.database.execute_sql('DROP TABLE register;')
def test_bind_helpers(self):
db = get_in_memory_db()
alt_db = get_in_memory_db()
class Base(Model):
class Meta:
database = db
class A(Base):
a = TextField()
class B(Base):
b = TextField()
db.create_tables([A, B])
# Temporarily bind A to alt_db.
with alt_db.bind_ctx([A]):
self.assertFalse(A.table_exists())
self.assertTrue(B.table_exists())
self.assertTrue(A.table_exists())
self.assertTrue(B.table_exists())
alt_db.bind([A])
self.assertFalse(A.table_exists())
self.assertTrue(B.table_exists())
db.close()
alt_db.close()
def test_bind_regression(self):
class Base(Model):
class Meta:
database = None
class A(Base): pass
class B(Base): pass
class AB(Base):
a = ForeignKeyField(A)
b = ForeignKeyField(B)
self.assertTrue(A._meta.database is None)
db = get_in_memory_db()
with db.bind_ctx([A, B]):
self.assertEqual(A._meta.database, db)
self.assertEqual(B._meta.database, db)
self.assertEqual(AB._meta.database, db)
self.assertTrue(A._meta.database is None)
self.assertTrue(B._meta.database is None)
self.assertTrue(AB._meta.database is None)
class C(Base):
a = ForeignKeyField(A)
with db.bind_ctx([C], bind_refs=False):
self.assertEqual(C._meta.database, db)
self.assertTrue(A._meta.database is None)
self.assertTrue(C._meta.database is None)
self.assertTrue(A._meta.database is None)
def test_batch_commit(self):
class PatchCommitDatabase(SqliteDatabase):
commits = 0
def begin(self): pass
def commit(self):
self.commits += 1
db = PatchCommitDatabase(':memory:')
def assertBatches(n_objs, batch_size, n_commits):
accum = []
source = range(n_objs)
db.commits = 0
for item in db.batch_commit(source, batch_size):
accum.append(item)
self.assertEqual(accum, list(range(n_objs)))
self.assertEqual(db.commits, n_commits)
assertBatches(12, 1, 12)
assertBatches(12, 2, 6)
assertBatches(12, 3, 4)
assertBatches(12, 4, 3)
assertBatches(12, 5, 3)
assertBatches(12, 6, 2)
assertBatches(12, 7, 2)
assertBatches(12, 11, 2)
assertBatches(12, 12, 1)
assertBatches(12, 13, 1)
def test_server_version(self):
class FakeDatabase(Database):
server_version = None
def _connect(self):
return 1
def _close(self, conn):
pass
def _set_server_version(self, conn):
self.server_version = (1, 33, 7)
db = FakeDatabase(':memory:')
self.assertTrue(db.server_version is None)
db.connect()
self.assertEqual(db.server_version, (1, 33, 7))
db.close()
self.assertEqual(db.server_version, (1, 33, 7))
db.server_version = (1, 2, 3)
db.connect()
self.assertEqual(db.server_version, (1, 2, 3))
db.close()
def test_explicit_connect(self):
db = get_in_memory_db(autoconnect=False)
self.assertRaises(InterfaceError, db.execute_sql, 'pragma cache_size')
with db:
db.execute_sql('pragma cache_size')
self.assertRaises(InterfaceError, db.cursor)
| TestDatabase |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataplex.py | {
"start": 35893,
"end": 37111
} | class ____:
@mock.patch(ASPECT_TYPE_STR)
@mock.patch(HOOK_STR)
def test_execute(self, hook_mock, aspect_type_mock):
op = DataplexCatalogCreateAspectTypeOperator(
task_id="create_task",
project_id=PROJECT_ID,
location=REGION,
aspect_type_id=ASPECT_TYPE_NAME,
aspect_type_configuration=BODY,
validate_request=None,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
aspect_type_mock.return_value.to_dict.return_value = None
hook_mock.return_value.wait_for_operation.return_value = None
op.execute(context=mock.MagicMock())
hook_mock.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
hook_mock.return_value.create_aspect_type.assert_called_once_with(
aspect_type_id=ASPECT_TYPE_NAME,
aspect_type_configuration=BODY,
location=REGION,
project_id=PROJECT_ID,
validate_only=None,
retry=DEFAULT,
timeout=None,
metadata=(),
)
| TestDataplexCatalogCreateAspectTypeOperator |
python | huggingface__transformers | src/transformers/models/yoso/modeling_yoso.py | {
"start": 34936,
"end": 39871
} | class ____(YosoPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.yoso = YosoModel(config)
self.pre_classifier = nn.Linear(config.hidden_size, config.hidden_size)
self.classifier = nn.Linear(config.hidden_size, 1)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, MultipleChoiceModelOutput]:
r"""
input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids)
position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
config.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids)
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, 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.
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
`input_ids` above)
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
inputs_embeds = (
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
if inputs_embeds is not None
else None
)
outputs = self.yoso(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
logits = self.classifier(pooled_output)
reshaped_logits = logits.view(-1, num_choices)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(reshaped_logits, labels)
if not return_dict:
output = (reshaped_logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return MultipleChoiceModelOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@auto_docstring
| YosoForMultipleChoice |
python | mahmoud__glom | glom/core.py | {
"start": 20342,
"end": 27027
} | class ____:
"""Path objects specify explicit paths when the default
``'a.b.c'``-style general access syntax won't work or isn't
desirable. Use this to wrap ints, datetimes, and other valid
keys, as well as strings with dots that shouldn't be expanded.
>>> target = {'a': {'b': 'c', 'd.e': 'f', 2: 3}}
>>> glom(target, Path('a', 2))
3
>>> glom(target, Path('a', 'd.e'))
'f'
Paths can be used to join together other Path objects, as
well as :data:`~glom.T` objects:
>>> Path(T['a'], T['b'])
T['a']['b']
>>> Path(Path('a', 'b'), Path('c', 'd'))
Path('a', 'b', 'c', 'd')
Paths also support indexing and slicing, with each access
returning a new Path object:
>>> path = Path('a', 'b', 1, 2)
>>> path[0]
Path('a')
>>> path[-2:]
Path(1, 2)
To build a Path object from a string, use :meth:`Path.from_text()`.
This is the default behavior when the top-level :func:`~glom.glom`
function gets a string spec.
"""
def __init__(self, *path_parts):
if not path_parts:
self.path_t = T
return
if isinstance(path_parts[0], TType):
path_t = path_parts[0]
offset = 1
else:
path_t = T
offset = 0
for part in path_parts[offset:]:
if isinstance(part, Path):
part = part.path_t
if isinstance(part, TType):
sub_parts = part.__ops__
if sub_parts[0] is not T:
raise ValueError('path segment must be path from T, not %r'
% sub_parts[0])
i = 1
while i < len(sub_parts):
path_t = _t_child(path_t, sub_parts[i], sub_parts[i + 1])
i += 2
else:
path_t = _t_child(path_t, 'P', part)
self.path_t = path_t
_CACHE = {True: {}, False: {}}
_MAX_CACHE = 10000
_STAR_WARNED = False
@classmethod
def from_text(cls, text):
"""Make a Path from .-delimited text:
>>> Path.from_text('a.b.c')
Path('a', 'b', 'c')
This is the default behavior when :func:`~glom.glom` gets a string spec.
"""
def create():
segs = text.split('.')
if PATH_STAR:
segs = [
_T_STAR if seg == '*' else
_T_STARSTAR if seg == '**' else seg
for seg in segs]
elif not cls._STAR_WARNED:
if '*' in segs or '**' in segs:
warnings.warn(
"'*' and '**' have changed behavior in glom version 23.1."
" Recommend switch to T['*'] or T['**'].")
cls._STAR_WARNED = True
return cls(*segs)
cache = cls._CACHE[PATH_STAR] # remove this when PATH_STAR is default
if text not in cache:
if len(cache) > cls._MAX_CACHE:
return create()
cache[text] = create()
return cache[text]
def glomit(self, target, scope):
# The entrypoint for the Path extension
return _t_eval(target, self.path_t, scope)
def __len__(self):
return (len(self.path_t.__ops__) - 1) // 2
def __eq__(self, other):
if type(other) is Path:
return self.path_t.__ops__ == other.path_t.__ops__
elif type(other) is TType:
return self.path_t.__ops__ == other.__ops__
return False
def __ne__(self, other):
return not self == other
def values(self):
"""
Returns a tuple of values referenced in this path.
>>> Path(T.a.b, 'c', T['d']).values()
('a', 'b', 'c', 'd')
"""
cur_t_path = self.path_t.__ops__
return cur_t_path[2::2]
def items(self):
"""
Returns a tuple of (operation, value) pairs.
>>> Path(T.a.b, 'c', T['d']).items()
(('.', 'a'), ('.', 'b'), ('P', 'c'), ('[', 'd'))
"""
cur_t_path = self.path_t.__ops__
return tuple(zip(cur_t_path[1::2], cur_t_path[2::2]))
def startswith(self, other):
if isinstance(other, basestring):
other = Path(other)
if isinstance(other, Path):
other = other.path_t
if not isinstance(other, TType):
raise TypeError('can only check if Path starts with string, Path or T')
o_path = other.__ops__
return self.path_t.__ops__[:len(o_path)] == o_path
def from_t(self):
'''return the same path but starting from T'''
t_path = self.path_t.__ops__
if t_path[0] is S:
new_t = TType()
new_t.__ops__ = (T,) + t_path[1:]
return Path(new_t)
return self
def __getitem__(self, i):
cur_t_path = self.path_t.__ops__
try:
step = i.step
start = i.start if i.start is not None else 0
stop = i.stop
start = (start * 2) + 1 if start >= 0 else (start * 2) + len(cur_t_path)
if stop is not None:
stop = (stop * 2) + 1 if stop >= 0 else (stop * 2) + len(cur_t_path)
except AttributeError:
step = 1
start = (i * 2) + 1 if i >= 0 else (i * 2) + len(cur_t_path)
if start < 0 or start > len(cur_t_path):
raise IndexError('Path index out of range')
stop = ((i + 1) * 2) + 1 if i >= 0 else ((i + 1) * 2) + len(cur_t_path)
new_t = TType()
new_path = cur_t_path[start:stop]
if step is not None and step != 1:
new_path = tuple(zip(new_path[::2], new_path[1::2]))[::step]
new_path = sum(new_path, ())
new_t.__ops__ = (cur_t_path[0],) + new_path
return Path(new_t)
def __repr__(self):
return _format_path(self.path_t.__ops__[1:])
def _format_path(t_path):
path_parts, cur_t_path = [], []
i = 0
while i < len(t_path):
op, arg = t_path[i], t_path[i + 1]
i += 2
if op == 'P':
if cur_t_path:
path_parts.append(cur_t_path)
cur_t_path = []
path_parts.append(arg)
else:
cur_t_path.append(op)
cur_t_path.append(arg)
if path_parts and cur_t_path:
path_parts.append(cur_t_path)
if path_parts or not cur_t_path:
return 'Path(%s)' % ', '.join([_format_t(part)
if type(part) is list else repr(part)
for part in path_parts])
return _format_t(cur_t_path)
| Path |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-visited-cells-in-a-grid.py | {
"start": 81,
"end": 970
} | class ____(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = range(n)
self.rank = [0]*n
self.right = range(n) # added
def find_set(self, x):
stk = []
while self.set[x] != x: # path compression
stk.append(x)
x = self.set[x]
while stk:
self.set[stk.pop()] = x
return x
def union_set(self, x, y):
x, y = self.find_set(x), self.find_set(y)
if x == y:
return False
if self.rank[x] > self.rank[y]: # union by rank
x, y = y, x
self.set[x] = self.set[y]
if self.rank[x] == self.rank[y]:
self.rank[y] += 1
self.right[y] = max(self.right[x], self.right[y]) # added
return True
def right_set(self, x): # added
return self.right[self.find_set(x)]
| UnionFind |
python | kamyu104__LeetCode-Solutions | Python/minimum-string-length-after-removing-substrings.py | {
"start": 37,
"end": 381
} | class ____(object):
def minLength(self, s):
"""
:type s: str
:rtype: int
"""
stk = []
for c in s:
if stk and ((stk[-1] == 'A' and c == 'B') or (stk[-1] == 'C' and c == 'D')):
stk.pop()
continue
stk.append(c)
return len(stk)
| Solution |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/extra/array_api.py | {
"start": 11221,
"end": 42306
} | class ____(st.SearchStrategy):
def __init__(
self, *, xp, api_version, elements_strategy, dtype, shape, fill, unique
):
super().__init__()
self.xp = xp
self.elements_strategy = elements_strategy
self.dtype = dtype
self.shape = shape
self.fill = fill
self.unique = unique
self.array_size = math.prod(shape)
self.builtin = find_castable_builtin_for_dtype(xp, api_version, dtype)
self.finfo = None if self.builtin is not float else xp.finfo(self.dtype)
def check_set_value(self, val, val_0d, strategy):
if val == val and self.builtin(val_0d) != val:
if self.builtin is float:
assert self.finfo is not None # for mypy
try:
is_subnormal = 0 < abs(val) < self.finfo.smallest_normal
except Exception:
# val may be a non-float that does not support the
# operations __lt__ and __abs__
is_subnormal = False
if is_subnormal:
raise InvalidArgument(
f"Generated subnormal float {val} from strategy "
f"{strategy} resulted in {val_0d!r}, probably "
f"as a result of array module {self.xp.__name__} "
"being built with flush-to-zero compiler options. "
"Consider passing allow_subnormal=False."
)
raise InvalidArgument(
f"Generated array element {val!r} from strategy {strategy} "
f"cannot be represented with dtype {self.dtype}. "
f"Array module {self.xp.__name__} instead "
f"represents the element as {val_0d}. "
"Consider using a more precise elements strategy, "
"for example passing the width argument to floats()."
)
def do_draw(self, data):
if 0 in self.shape:
return self.xp.zeros(self.shape, dtype=self.dtype)
if self.fill.is_empty:
# We have no fill value (either because the user explicitly
# disabled it or because the default behaviour was used and our
# elements strategy does not produce reusable values), so we must
# generate a fully dense array with a freshly drawn value for each
# entry.
elems = data.draw(
st.lists(
self.elements_strategy,
min_size=self.array_size,
max_size=self.array_size,
unique=self.unique,
)
)
try:
result = self.xp.asarray(elems, dtype=self.dtype)
except Exception as e:
if len(elems) <= 6:
f_elems = str(elems)
else:
f_elems = f"[{elems[0]}, {elems[1]}, ..., {elems[-2]}, {elems[-1]}]"
types = tuple(
sorted({type(e) for e in elems}, key=lambda t: t.__name__)
)
f_types = f"type {types[0]}" if len(types) == 1 else f"types {types}"
raise InvalidArgument(
f"Generated elements {f_elems} from strategy "
f"{self.elements_strategy} could not be converted "
f"to array of dtype {self.dtype}. "
f"Consider if elements of {f_types} "
f"are compatible with {self.dtype}."
) from e
for i in range(self.array_size):
self.check_set_value(elems[i], result[i], self.elements_strategy)
else:
# We draw arrays as "sparse with an offset". We assume not every
# element will be assigned and so first draw a single value from our
# fill strategy to create a full array. We then draw a collection of
# index assignments within the array and assign fresh values from
# our elements strategy to those indices.
fill_val = data.draw(self.fill)
result_obj = [fill_val for _ in range(self.array_size)]
fill_mask = [True for _ in range(self.array_size)]
elements = cu.many(
data,
min_size=0,
max_size=self.array_size,
# sqrt isn't chosen for any particularly principled reason. It
# just grows reasonably quickly but sublinearly, and for small
# arrays it represents a decent fraction of the array size.
average_size=min(
0.9 * self.array_size, # ensure small arrays sometimes use fill
max(10, math.sqrt(self.array_size)), # ...but *only* sometimes
),
)
assigned = set()
seen = set()
while elements.more():
i = data.draw_integer(0, self.array_size - 1)
if i in assigned:
elements.reject("chose an array index we've already used")
continue
val = data.draw(self.elements_strategy)
if self.unique:
if val in seen:
elements.reject("chose an element we've already used")
continue
seen.add(val)
result_obj[i] = val
assigned.add(i)
fill_mask[i] = False
try:
result = self.xp.asarray(result_obj, dtype=self.dtype)
except Exception as e:
f_expr = f"xp.asarray({result_obj}, dtype={self.dtype})"
raise InvalidArgument(f"Could not create array via {f_expr}") from e
for i, val in enumerate(result_obj):
val_0d = result[i]
if fill_mask[i] and self.unique:
if not self.xp.isnan(val_0d):
raise InvalidArgument(
f"Array module {self.xp.__name__} did not recognise fill "
f"value {fill_val!r} as NaN - instead got {val_0d!r}. "
"Cannot fill unique array with non-NaN values."
)
else:
self.check_set_value(val, val_0d, self.elements_strategy)
return self.xp.reshape(result, self.shape)
def _arrays(
xp: Any,
api_version: NominalVersion,
dtype: DataType | str | st.SearchStrategy[DataType] | st.SearchStrategy[str],
shape: int | Shape | st.SearchStrategy[Shape],
*,
elements: Mapping[str, Any] | st.SearchStrategy | None = None,
fill: st.SearchStrategy[Any] | None = None,
unique: bool = False,
) -> st.SearchStrategy:
"""Returns a strategy for :xp-ref:`arrays <array_object.html>`.
* ``dtype`` may be a :xp-ref:`valid dtype <data_types.html>` object or name,
or a strategy that generates such values.
* ``shape`` may be an integer >= 0, a tuple of such integers, or a strategy
that generates such values.
* ``elements`` is a strategy for values to put in the array. If ``None``
then a suitable value will be inferred based on the dtype, which may give
any legal value (including e.g. NaN for floats). If a mapping, it will be
passed as ``**kwargs`` to :func:`from_dtype()` when inferring based on the dtype.
* ``fill`` is a strategy that may be used to generate a single background
value for the array. If ``None``, a suitable default will be inferred
based on the other arguments. If set to
:func:`~hypothesis.strategies.nothing` then filling behaviour will be
disabled entirely and every element will be generated independently.
* ``unique`` specifies if the elements of the array should all be distinct
from one another; if fill is also set, the only valid values for fill to
return are NaN values.
Arrays of specified ``dtype`` and ``shape`` are generated for example
like this:
.. code-block:: pycon
>>> from numpy import array_api as xp
>>> xps.arrays(xp, xp.int8, (2, 3)).example()
Array([[-8, 6, 3],
[-6, 4, 6]], dtype=int8)
Specifying element boundaries by a :obj:`python:dict` of the kwargs to pass
to :func:`from_dtype` will ensure ``dtype`` bounds will be respected.
.. code-block:: pycon
>>> xps.arrays(xp, xp.int8, 3, elements={"min_value": 10}).example()
Array([125, 13, 79], dtype=int8)
.. code-block:: pycon
>>> xps.arrays(xp, xp.float32, 3, elements=floats(0, 1, width=32)).example()
Array([ 0.88974794, 0.77387938, 0.1977879 ], dtype=float32)
Array values are generated in two parts:
1. A single value is drawn from the fill strategy and is used to create a
filled array.
2. Some subset of the coordinates of the array are populated with a value
drawn from the elements strategy (or its inferred form).
You can set ``fill`` to :func:`~hypothesis.strategies.nothing` if you want
to disable this behaviour and draw a value for every element.
By default ``arrays`` will attempt to infer the correct fill behaviour: if
``unique`` is also ``True``, no filling will occur. Otherwise, if it looks
safe to reuse the values of elements across multiple coordinates (this will
be the case for any inferred strategy, and for most of the builtins, but is
not the case for mutable values or strategies built with flatmap, map,
composite, etc.) then it will use the elements strategy as the fill, else it
will default to having no fill.
Having a fill helps Hypothesis craft high quality examples, but its
main importance is when the array generated is large: Hypothesis is
primarily designed around testing small examples. If you have arrays with
hundreds or more elements, having a fill value is essential if you want
your tests to run in reasonable time.
"""
check_xp_attributes(
xp, ["finfo", "asarray", "zeros", "all", "isnan", "isfinite", "reshape"]
)
if isinstance(dtype, st.SearchStrategy):
return dtype.flatmap(
lambda d: _arrays(
xp, api_version, d, shape, elements=elements, fill=fill, unique=unique
)
)
elif isinstance(dtype, str):
dtype = dtype_from_name(xp, dtype)
if isinstance(shape, st.SearchStrategy):
return shape.flatmap(
lambda s: _arrays(
xp, api_version, dtype, s, elements=elements, fill=fill, unique=unique
)
)
elif isinstance(shape, int):
shape = (shape,)
elif not isinstance(shape, tuple):
raise InvalidArgument(f"shape={shape} is not a valid shape or strategy")
check_argument(
all(isinstance(x, int) and x >= 0 for x in shape),
f"{shape=}, but all dimensions must be non-negative integers.",
)
if elements is None:
elements = _from_dtype(xp, api_version, dtype)
elif isinstance(elements, Mapping):
elements = _from_dtype(xp, api_version, dtype, **elements)
check_strategy(elements, "elements")
if fill is None:
assert isinstance(elements, st.SearchStrategy) # for mypy
if unique or not elements.has_reusable_values:
fill = st.nothing()
else:
fill = elements
check_strategy(fill, "fill")
return ArrayStrategy(
xp=xp,
api_version=api_version,
elements_strategy=elements,
dtype=dtype,
shape=shape,
fill=fill,
unique=unique,
)
@check_function
def check_dtypes(xp: Any, dtypes: list[DataType], stubs: list[str]) -> None:
if len(dtypes) == 0:
assert len(stubs) > 0, "No dtypes passed but stubs is empty"
f_stubs = ", ".join(stubs)
raise InvalidArgument(
f"Array module {xp.__name__} does not have the following "
f"required dtypes in its namespace: {f_stubs}"
)
elif len(stubs) > 0:
warn_on_missing_dtypes(xp, stubs)
def _scalar_dtypes(xp: Any, api_version: NominalVersion) -> st.SearchStrategy[DataType]:
"""Return a strategy for all :xp-ref:`valid dtype <data_types.html>` objects."""
return st.one_of(_boolean_dtypes(xp), _numeric_dtypes(xp, api_version))
def _boolean_dtypes(xp: Any) -> st.SearchStrategy[DataType]:
"""Return a strategy for just the boolean dtype object."""
try:
return st.just(xp.bool)
except AttributeError:
raise InvalidArgument(
f"Array module {xp.__name__} does not have a bool dtype in its namespace"
) from None
def _real_dtypes(xp: Any) -> st.SearchStrategy[DataType]:
"""Return a strategy for all real-valued dtype objects."""
return st.one_of(
_integer_dtypes(xp),
_unsigned_integer_dtypes(xp),
_floating_dtypes(xp),
)
def _numeric_dtypes(
xp: Any, api_version: NominalVersion
) -> st.SearchStrategy[DataType]:
"""Return a strategy for all numeric dtype objects."""
strat: st.SearchStrategy[DataType] = _real_dtypes(xp)
if api_version > "2021.12":
strat |= _complex_dtypes(xp)
return strat
@check_function
def check_valid_sizes(
category: str, sizes: Sequence[int], valid_sizes: Sequence[int]
) -> None:
check_argument(len(sizes) > 0, "No sizes passed")
invalid_sizes = [s for s in sizes if s not in valid_sizes]
f_valid_sizes = ", ".join(str(s) for s in valid_sizes)
f_invalid_sizes = ", ".join(str(s) for s in invalid_sizes)
check_argument(
len(invalid_sizes) == 0,
f"The following sizes are not valid for {category} dtypes: "
f"{f_invalid_sizes} (valid sizes: {f_valid_sizes})",
)
def numeric_dtype_names(base_name: str, sizes: Sequence[int]) -> Iterator[str]:
for size in sizes:
yield f"{base_name}{size}"
IntSize: TypeAlias = Literal[8, 16, 32, 64]
FltSize: TypeAlias = Literal[32, 64]
CpxSize: TypeAlias = Literal[64, 128]
def _integer_dtypes(
xp: Any, *, sizes: IntSize | Sequence[IntSize] = (8, 16, 32, 64)
) -> st.SearchStrategy[DataType]:
"""Return a strategy for signed integer dtype objects.
``sizes`` contains the signed integer sizes in bits, defaulting to
``(8, 16, 32, 64)`` which covers all valid sizes.
"""
if isinstance(sizes, int):
sizes = (sizes,)
check_valid_sizes("int", sizes, (8, 16, 32, 64))
dtypes, stubs = partition_attributes_and_stubs(
xp, numeric_dtype_names("int", sizes)
)
check_dtypes(xp, dtypes, stubs)
return st.sampled_from(dtypes)
def _unsigned_integer_dtypes(
xp: Any, *, sizes: IntSize | Sequence[IntSize] = (8, 16, 32, 64)
) -> st.SearchStrategy[DataType]:
"""Return a strategy for unsigned integer dtype objects.
``sizes`` contains the unsigned integer sizes in bits, defaulting to
``(8, 16, 32, 64)`` which covers all valid sizes.
"""
if isinstance(sizes, int):
sizes = (sizes,)
check_valid_sizes("int", sizes, (8, 16, 32, 64))
dtypes, stubs = partition_attributes_and_stubs(
xp, numeric_dtype_names("uint", sizes)
)
check_dtypes(xp, dtypes, stubs)
return st.sampled_from(dtypes)
def _floating_dtypes(
xp: Any, *, sizes: FltSize | Sequence[FltSize] = (32, 64)
) -> st.SearchStrategy[DataType]:
"""Return a strategy for real-valued floating-point dtype objects.
``sizes`` contains the floating-point sizes in bits, defaulting to
``(32, 64)`` which covers all valid sizes.
"""
if isinstance(sizes, int):
sizes = (sizes,)
check_valid_sizes("int", sizes, (32, 64))
dtypes, stubs = partition_attributes_and_stubs(
xp, numeric_dtype_names("float", sizes)
)
check_dtypes(xp, dtypes, stubs)
return st.sampled_from(dtypes)
def _complex_dtypes(
xp: Any, *, sizes: CpxSize | Sequence[CpxSize] = (64, 128)
) -> st.SearchStrategy[DataType]:
"""Return a strategy for complex dtype objects.
``sizes`` contains the complex sizes in bits, defaulting to ``(64, 128)``
which covers all valid sizes.
"""
if isinstance(sizes, int):
sizes = (sizes,)
check_valid_sizes("complex", sizes, (64, 128))
dtypes, stubs = partition_attributes_and_stubs(
xp, numeric_dtype_names("complex", sizes)
)
check_dtypes(xp, dtypes, stubs)
return st.sampled_from(dtypes)
@proxies(_valid_tuple_axes)
def valid_tuple_axes(*args, **kwargs):
return _valid_tuple_axes(*args, **kwargs)
valid_tuple_axes.__doc__ = f"""
Return a strategy for permissible tuple-values for the ``axis``
argument in Array API sequential methods e.g. ``sum``, given the specified
dimensionality.
{_valid_tuple_axes.__doc__}
"""
@defines_strategy()
def mutually_broadcastable_shapes(
num_shapes: int,
*,
base_shape: Shape = (),
min_dims: int = 0,
max_dims: int | None = None,
min_side: int = 1,
max_side: int | None = None,
) -> st.SearchStrategy[BroadcastableShapes]:
return _mutually_broadcastable_shapes(
num_shapes=num_shapes,
base_shape=base_shape,
min_dims=min_dims,
max_dims=max_dims,
min_side=min_side,
max_side=max_side,
)
mutually_broadcastable_shapes.__doc__ = _mutually_broadcastable_shapes.__doc__
@defines_strategy()
def indices(
shape: Shape,
*,
min_dims: int = 0,
max_dims: int | None = None,
allow_newaxis: bool = False,
allow_ellipsis: bool = True,
) -> st.SearchStrategy[BasicIndex]:
"""Return a strategy for :xp-ref:`valid indices <indexing.html>` of
arrays with the specified shape, which may include dimensions of size zero.
It generates tuples containing some mix of integers, :obj:`python:slice`
objects, ``...`` (an ``Ellipsis``), and ``None``. When a length-one tuple
would be generated, this strategy may instead return the element which will
index the first axis, e.g. ``5`` instead of ``(5,)``.
* ``shape`` is the shape of the array that will be indexed, as a tuple of
integers >= 0. This must be at least two-dimensional for a tuple to be a
valid index; for one-dimensional arrays use
:func:`~hypothesis.strategies.slices` instead.
* ``min_dims`` is the minimum dimensionality of the resulting array from use
of the generated index.
* ``max_dims`` is the the maximum dimensionality of the resulting array,
defaulting to ``len(shape) if not allow_newaxis else
max(len(shape), min_dims) + 2``.
* ``allow_ellipsis`` specifies whether ``None`` is allowed in the index.
* ``allow_ellipsis`` specifies whether ``...`` is allowed in the index.
"""
check_type(tuple, shape, "shape")
check_argument(
all(isinstance(x, int) and x >= 0 for x in shape),
f"{shape=}, but all dimensions must be non-negative integers.",
)
check_type(bool, allow_newaxis, "allow_newaxis")
check_type(bool, allow_ellipsis, "allow_ellipsis")
check_type(int, min_dims, "min_dims")
if not allow_newaxis:
check_argument(
min_dims <= len(shape),
f"min_dims={min_dims} is larger than len(shape)={len(shape)}, "
"but it is impossible for an indexing operation to add dimensions ",
"when allow_newaxis=False.",
)
check_valid_dims(min_dims, "min_dims")
if max_dims is None:
if allow_newaxis:
max_dims = min(max(len(shape), min_dims) + 2, NDIM_MAX)
else:
max_dims = min(len(shape), NDIM_MAX)
check_type(int, max_dims, "max_dims")
assert isinstance(max_dims, int)
if not allow_newaxis:
check_argument(
max_dims <= len(shape),
f"max_dims={max_dims} is larger than len(shape)={len(shape)}, "
"but it is impossible for an indexing operation to add dimensions ",
"when allow_newaxis=False.",
)
check_valid_dims(max_dims, "max_dims")
order_check("dims", 0, min_dims, max_dims)
return BasicIndexStrategy(
shape,
min_dims=min_dims,
max_dims=max_dims,
allow_ellipsis=allow_ellipsis,
allow_newaxis=allow_newaxis,
allow_fewer_indices_than_dims=False,
)
# Cache for make_strategies_namespace()
_args_to_xps: WeakValueDictionary = WeakValueDictionary()
def make_strategies_namespace(
xp: Any, *, api_version: NominalVersion | None = None
) -> SimpleNamespace:
"""Creates a strategies namespace for the given array module.
* ``xp`` is the Array API library to automatically pass to the namespaced methods.
* ``api_version`` is the version of the Array API which the returned
strategies namespace should conform to. If ``None``, the latest API
version which ``xp`` supports will be inferred from ``xp.__array_api_version__``.
If a version string in the ``YYYY.MM`` format, the strategies namespace
will conform to that version if supported.
A :obj:`python:types.SimpleNamespace` is returned which contains all the
strategy methods in this module but without requiring the ``xp`` argument.
Creating and using a strategies namespace for NumPy's Array API
implementation would go like this:
.. code-block:: pycon
>>> xp.__array_api_version__ # xp is your desired array library
'2021.12'
>>> xps = make_strategies_namespace(xp)
>>> xps.api_version
'2021.12'
>>> x = xps.arrays(xp.int8, (2, 3)).example()
>>> x
Array([[-8, 6, 3],
[-6, 4, 6]], dtype=int8)
>>> x.__array_namespace__() is xp
True
"""
not_available_msg = (
"If the standard version you want is not available, please ensure "
"you're using the latest version of Hypothesis, then open an issue if "
"one doesn't already exist."
)
if api_version is None:
check_argument(
hasattr(xp, "__array_api_version__"),
f"Array module {xp.__name__} has no attribute __array_api_version__, "
"which is required when inferring api_version. If you believe "
f"{xp.__name__} is indeed an Array API module, try explicitly "
"passing an api_version.",
)
check_argument(
isinstance(xp.__array_api_version__, str)
and xp.__array_api_version__ in RELEASED_VERSIONS,
f"{xp.__array_api_version__=}, but it must "
f"be a valid version string {RELEASED_VERSIONS}. {not_available_msg}",
)
api_version = xp.__array_api_version__
inferred_version = True
else:
check_argument(
isinstance(api_version, str) and api_version in NOMINAL_VERSIONS,
f"{api_version=}, but it must be None, or a valid version "
f"string in {RELEASED_VERSIONS}. {not_available_msg}",
)
inferred_version = False
try:
array = xp.zeros(1)
array.__array_namespace__()
except Exception:
warn(
f"Could not determine whether module {xp.__name__} is an Array API library",
HypothesisWarning,
stacklevel=2,
)
try:
namespace = _args_to_xps[(xp, api_version)]
except (KeyError, TypeError):
pass
else:
return namespace
@defines_strategy(force_reusable_values=True)
def from_dtype(
dtype: DataType | str,
*,
min_value: int | float | None = None,
max_value: int | float | None = None,
allow_nan: bool | None = None,
allow_infinity: bool | None = None,
allow_subnormal: bool | None = None,
exclude_min: bool | None = None,
exclude_max: bool | None = None,
) -> st.SearchStrategy[bool | int | float | complex]:
return _from_dtype(
xp,
api_version,
dtype,
min_value=min_value,
max_value=max_value,
allow_nan=allow_nan,
allow_infinity=allow_infinity,
allow_subnormal=allow_subnormal,
exclude_min=exclude_min,
exclude_max=exclude_max,
)
@defines_strategy(force_reusable_values=True)
def arrays(
dtype: DataType | str | st.SearchStrategy[DataType] | st.SearchStrategy[str],
shape: int | Shape | st.SearchStrategy[Shape],
*,
elements: Mapping[str, Any] | st.SearchStrategy | None = None,
fill: st.SearchStrategy[Any] | None = None,
unique: bool = False,
) -> st.SearchStrategy:
return _arrays(
xp,
api_version,
dtype,
shape,
elements=elements,
fill=fill,
unique=unique,
)
@defines_strategy()
def scalar_dtypes() -> st.SearchStrategy[DataType]:
return _scalar_dtypes(xp, api_version)
@defines_strategy()
def boolean_dtypes() -> st.SearchStrategy[DataType]:
return _boolean_dtypes(xp)
@defines_strategy()
def real_dtypes() -> st.SearchStrategy[DataType]:
return _real_dtypes(xp)
@defines_strategy()
def numeric_dtypes() -> st.SearchStrategy[DataType]:
return _numeric_dtypes(xp, api_version)
@defines_strategy()
def integer_dtypes(
*, sizes: IntSize | Sequence[IntSize] = (8, 16, 32, 64)
) -> st.SearchStrategy[DataType]:
return _integer_dtypes(xp, sizes=sizes)
@defines_strategy()
def unsigned_integer_dtypes(
*, sizes: IntSize | Sequence[IntSize] = (8, 16, 32, 64)
) -> st.SearchStrategy[DataType]:
return _unsigned_integer_dtypes(xp, sizes=sizes)
@defines_strategy()
def floating_dtypes(
*, sizes: FltSize | Sequence[FltSize] = (32, 64)
) -> st.SearchStrategy[DataType]:
return _floating_dtypes(xp, sizes=sizes)
from_dtype.__doc__ = _from_dtype.__doc__
arrays.__doc__ = _arrays.__doc__
scalar_dtypes.__doc__ = _scalar_dtypes.__doc__
boolean_dtypes.__doc__ = _boolean_dtypes.__doc__
real_dtypes.__doc__ = _real_dtypes.__doc__
numeric_dtypes.__doc__ = _numeric_dtypes.__doc__
integer_dtypes.__doc__ = _integer_dtypes.__doc__
unsigned_integer_dtypes.__doc__ = _unsigned_integer_dtypes.__doc__
floating_dtypes.__doc__ = _floating_dtypes.__doc__
class StrategiesNamespace(SimpleNamespace):
def __init__(self, **kwargs):
for attr in ["name", "api_version"]:
if attr not in kwargs:
raise ValueError(f"'{attr}' kwarg required")
super().__init__(**kwargs)
@property
def complex_dtypes(self):
try:
return self.__dict__["complex_dtypes"]
except KeyError as e:
raise AttributeError(
"You attempted to access 'complex_dtypes', but it is not "
f"available for api_version='{self.api_version}' of "
f"xp={self.name}."
) from e
def __repr__(self):
f_args = self.name
if not inferred_version:
f_args += f", api_version='{self.api_version}'"
return f"make_strategies_namespace({f_args})"
kwargs = {
"name": xp.__name__,
"api_version": api_version,
"from_dtype": from_dtype,
"arrays": arrays,
"array_shapes": array_shapes,
"scalar_dtypes": scalar_dtypes,
"boolean_dtypes": boolean_dtypes,
"real_dtypes": real_dtypes,
"numeric_dtypes": numeric_dtypes,
"integer_dtypes": integer_dtypes,
"unsigned_integer_dtypes": unsigned_integer_dtypes,
"floating_dtypes": floating_dtypes,
"valid_tuple_axes": valid_tuple_axes,
"broadcastable_shapes": broadcastable_shapes,
"mutually_broadcastable_shapes": mutually_broadcastable_shapes,
"indices": indices,
}
if api_version > "2021.12":
@defines_strategy()
def complex_dtypes(
*, sizes: CpxSize | Sequence[CpxSize] = (64, 128)
) -> st.SearchStrategy[DataType]:
return _complex_dtypes(xp, sizes=sizes)
complex_dtypes.__doc__ = _complex_dtypes.__doc__
kwargs["complex_dtypes"] = complex_dtypes
namespace = StrategiesNamespace(**kwargs)
try:
_args_to_xps[(xp, api_version)] = namespace
except TypeError:
pass
return namespace
try:
import numpy as np
except ImportError:
if "sphinx" in sys.modules:
# This is pretty awkward, but also the best way available
from unittest.mock import Mock
np = Mock()
else:
np = None # type: ignore[assignment]
if np is not None:
class FloatInfo(NamedTuple):
bits: int
eps: float
max: float
min: float
smallest_normal: float
def mock_finfo(dtype: DataType) -> FloatInfo:
"""Returns a finfo object compliant with the Array API
Ensures all attributes are Python scalars and not NumPy scalars. This
lets us ignore corner cases with how NumPy scalars operate, such as
NumPy floats breaking our next_down() util.
Also ensures the finfo obj has the smallest_normal attribute. NumPy only
introduced it in v1.21.1, so we just use the equivalent tiny attribute
to keep mocking with older versions working.
"""
_finfo = np.finfo(dtype) # type: ignore[call-overload]
return FloatInfo(
int(_finfo.bits),
float(_finfo.eps),
float(_finfo.max),
float(_finfo.min),
float(_finfo.tiny),
)
mock_xp = SimpleNamespace(
__name__="mock",
__array_api_version__="2022.12",
# Data types
int8=np.int8,
int16=np.int16,
int32=np.int32,
int64=np.int64,
uint8=np.uint8,
uint16=np.uint16,
uint32=np.uint32,
uint64=np.uint64,
float32=np.float32,
float64=np.float64,
complex64=np.complex64,
complex128=np.complex128,
bool=np.bool_,
# Constants
nan=np.nan,
# Data type functions
astype=lambda x, d: x.astype(d),
iinfo=np.iinfo,
finfo=mock_finfo,
broadcast_arrays=np.broadcast_arrays,
# Creation functions
arange=np.arange,
asarray=np.asarray,
empty=np.empty,
zeros=np.zeros,
ones=np.ones,
# Manipulation functions
reshape=np.reshape,
# Element-wise functions
isnan=np.isnan,
isfinite=np.isfinite,
logical_or=np.logical_or,
# Statistical functions
sum=np.sum,
# Searching functions
nonzero=np.nonzero,
# Sorting functions
sort=np.sort,
# Set functions
unique_values=np.unique,
# Utility functions
any=np.any,
all=np.all,
)
| ArrayStrategy |
python | kubernetes-client__python | kubernetes/client/models/v1_namespace_status.py | {
"start": 383,
"end": 4616
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'conditions': 'list[V1NamespaceCondition]',
'phase': 'str'
}
attribute_map = {
'conditions': 'conditions',
'phase': 'phase'
}
def __init__(self, conditions=None, phase=None, local_vars_configuration=None): # noqa: E501
"""V1NamespaceStatus - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._conditions = None
self._phase = None
self.discriminator = None
if conditions is not None:
self.conditions = conditions
if phase is not None:
self.phase = phase
@property
def conditions(self):
"""Gets the conditions of this V1NamespaceStatus. # noqa: E501
Represents the latest available observations of a namespace's current state. # noqa: E501
:return: The conditions of this V1NamespaceStatus. # noqa: E501
:rtype: list[V1NamespaceCondition]
"""
return self._conditions
@conditions.setter
def conditions(self, conditions):
"""Sets the conditions of this V1NamespaceStatus.
Represents the latest available observations of a namespace's current state. # noqa: E501
:param conditions: The conditions of this V1NamespaceStatus. # noqa: E501
:type: list[V1NamespaceCondition]
"""
self._conditions = conditions
@property
def phase(self):
"""Gets the phase of this V1NamespaceStatus. # noqa: E501
Phase is the current lifecycle phase of the namespace. More info: https://kubernetes.io/docs/tasks/administer-cluster/namespaces/ # noqa: E501
:return: The phase of this V1NamespaceStatus. # noqa: E501
:rtype: str
"""
return self._phase
@phase.setter
def phase(self, phase):
"""Sets the phase of this V1NamespaceStatus.
Phase is the current lifecycle phase of the namespace. More info: https://kubernetes.io/docs/tasks/administer-cluster/namespaces/ # noqa: E501
:param phase: The phase of this V1NamespaceStatus. # noqa: E501
:type: str
"""
self._phase = phase
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1NamespaceStatus):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1NamespaceStatus):
return True
return self.to_dict() != other.to_dict()
| V1NamespaceStatus |
python | facebookresearch__faiss | faiss/gpu/test/test_gpu_index.py | {
"start": 7790,
"end": 12496
} | class ____(unittest.TestCase):
def test_interleaved(self):
res = faiss.StandardGpuResources()
for bits_per_code in [4, 5, 6, 8]:
d = 128
nb = 10000
nq = 20
rs = np.random.RandomState(123)
xb = rs.rand(nb, d).astype('float32')
xq = rs.rand(nq, d).astype('float32')
nlist = int(math.sqrt(nb))
sub_q = 16
nprobe = 16
config = faiss.GpuIndexIVFPQConfig()
config.interleavedLayout = True
idx_gpu = faiss.GpuIndexIVFPQ(res, d, nlist, sub_q, bits_per_code, faiss.METRIC_L2, config)
q = faiss.IndexFlatL2(d)
idx_cpu = faiss.IndexIVFPQ(q, d, nlist, sub_q, bits_per_code, faiss.METRIC_L2)
idx_gpu.train(xb)
idx_gpu.add(xb)
idx_gpu.copyTo(idx_cpu)
idx_gpu.nprobe = nprobe
idx_cpu.nprobe = nprobe
k = 20
# Try without precomputed codes
d_g, i_g = idx_gpu.search(xq, k)
d_c, i_c = idx_cpu.search(xq, k)
self.assertGreaterEqual((i_g == i_c).sum(), i_g.size * 0.9)
self.assertTrue(np.allclose(d_g, d_c, rtol=5e-5, atol=5e-5))
# Try with precomputed codes (different kernel)
idx_gpu.setPrecomputedCodes(True)
d_g, i_g = idx_gpu.search(xq, k)
d_c, i_c = idx_cpu.search(xq, k)
self.assertGreaterEqual((i_g == i_c).sum(), i_g.size * 0.9)
self.assertTrue(np.allclose(d_g, d_c, rtol=5e-5, atol=5e-5))
def test_copy_to_cpu(self):
res = faiss.StandardGpuResources()
for bits_per_code in [4, 5, 6, 8]:
d = 128
nb = 10000
nq = 20
rs = np.random.RandomState(234)
xb = rs.rand(nb, d).astype('float32')
xq = rs.rand(nq, d).astype('float32')
nlist = int(math.sqrt(nb))
sub_q = 16
bits_per_code = 8
nprobe = 4
config = faiss.GpuIndexIVFPQConfig()
config.interleavedLayout = True
idx_gpu = faiss.GpuIndexIVFPQ(res, d, nlist, sub_q, bits_per_code, faiss.METRIC_L2, config)
q = faiss.IndexFlatL2(d)
idx_cpu = faiss.IndexIVFPQ(q, d, nlist, sub_q, bits_per_code, faiss.METRIC_L2)
idx_gpu.train(xb)
idx_gpu.add(xb)
idx_gpu.copyTo(idx_cpu)
idx_gpu.nprobe = nprobe
idx_cpu.nprobe = nprobe
# Try without precomputed codes
d_g, i_g = idx_gpu.search(xq, 10)
d_c, i_c = idx_cpu.search(xq, 10)
self.assertGreaterEqual((i_g == i_c).sum(), i_g.size * 0.9)
self.assertTrue(np.allclose(d_g, d_c))
# Try with precomputed codes (different kernel)
idx_gpu.setPrecomputedCodes(True)
d_g, i_g = idx_gpu.search(xq, 10)
d_c, i_c = idx_cpu.search(xq, 10)
self.assertGreaterEqual((i_g == i_c).sum(), i_g.size * 0.9)
self.assertTrue(np.allclose(d_g, d_c))
def test_copy_to_gpu(self):
res = faiss.StandardGpuResources()
for bits_per_code in [4, 5, 6, 8]:
d = 128
nb = 10000
nq = 20
rs = np.random.RandomState(567)
xb = rs.rand(nb, d).astype('float32')
xq = rs.rand(nq, d).astype('float32')
nlist = int(math.sqrt(nb))
sub_q = 16
bits_per_code = 8
nprobe = 4
config = faiss.GpuIndexIVFPQConfig()
config.interleavedLayout = True
idx_gpu = faiss.GpuIndexIVFPQ(res, d, nlist, sub_q, bits_per_code, faiss.METRIC_L2, config)
q = faiss.IndexFlatL2(d)
idx_cpu = faiss.IndexIVFPQ(q, d, nlist, sub_q, bits_per_code, faiss.METRIC_L2)
idx_cpu.train(xb)
idx_cpu.add(xb)
idx_gpu.copyFrom(idx_cpu)
idx_gpu.nprobe = nprobe
idx_cpu.nprobe = nprobe
# Try without precomputed codes
d_g, i_g = idx_gpu.search(xq, 10)
d_c, i_c = idx_cpu.search(xq, 10)
self.assertGreaterEqual((i_g == i_c).sum(), i_g.size * 0.9)
self.assertTrue(np.allclose(d_g, d_c))
# Try with precomputed codes (different kernel)
idx_gpu.setPrecomputedCodes(True)
d_g, i_g = idx_gpu.search(xq, 10)
d_c, i_c = idx_cpu.search(xq, 10)
self.assertGreaterEqual((i_g == i_c).sum(), i_g.size * 0.9)
self.assertTrue(np.allclose(d_g, d_c))
# Make sure indices are properly stored in the IVF lists
| TestInterleavedIVFPQLayout |
python | ray-project__ray | python/ray/tune/schedulers/hyperband.py | {
"start": 1520,
"end": 17812
} | class ____(FIFOScheduler):
"""Implements the HyperBand early stopping algorithm.
HyperBandScheduler early stops trials using the HyperBand optimization
algorithm. It divides trials into brackets of varying sizes, and
periodically early stops low-performing trials within each bracket.
To use this implementation of HyperBand with Tune, all you need
to do is specify the max length of time a trial can run `max_t`, the time
units `time_attr`, the name of the reported objective value `metric`,
and if `metric` is to be maximized or minimized (`mode`).
We automatically determine reasonable values for the other
HyperBand parameters based on the given values.
For example, to limit trials to 10 minutes and early stop based on the
`episode_mean_reward` attr, construct:
``HyperBand('time_total_s', 'episode_reward_mean', max_t=600)``
Note that Tune's stopping criteria will be applied in conjunction with
HyperBand's early stopping mechanisms.
See also: https://blog.ml.cmu.edu/2018/12/12/massively-parallel-hyperparameter-optimization/
Args:
time_attr: The training result attr to use for comparing time.
Note that you can pass in something non-temporal such as
`training_iteration` as a measure of progress, the only requirement
is that the attribute should increase monotonically.
metric: The training result objective value attribute. Stopping
procedures will use this attribute. If None but a mode was passed,
the `ray.tune.result.DEFAULT_METRIC` will be used per default.
mode: One of {min, max}. Determines whether objective is
minimizing or maximizing the metric attribute.
max_t: max time units per trial. Trials will be stopped after
max_t time units (determined by time_attr) have passed.
The scheduler will terminate trials after this time has passed.
Note that this is different from the semantics of `max_t` as
mentioned in the original HyperBand paper.
reduction_factor: Same as `eta`. Determines how sharp
the difference is between bracket space-time allocation ratios.
stop_last_trials: Whether to terminate the trials after
reaching max_t. Defaults to True.
""" # noqa: E501
_supports_buffered_results = False
def __init__(
self,
time_attr: str = "training_iteration",
metric: Optional[str] = None,
mode: Optional[str] = None,
max_t: int = 81,
reduction_factor: float = 3,
stop_last_trials: bool = True,
):
assert max_t > 0, "Max (time_attr) not valid!"
if mode:
assert mode in ["min", "max"], "`mode` must be 'min' or 'max'!"
super().__init__()
self._eta = reduction_factor
self._s_max_1 = int(np.round(np.log(max_t) / np.log(reduction_factor))) + 1
self._max_t_attr = max_t
# bracket max trials
self._get_n0 = lambda s: int(np.ceil(self._s_max_1 / (s + 1) * self._eta**s))
# bracket initial iterations
self._get_r0 = lambda s: int((max_t * self._eta ** (-s)))
self._hyperbands = [[]] # list of hyperband iterations
self._trial_info = {} # Stores Trial -> Bracket, Band Iteration
# Tracks state for new trial add
self._state = {"bracket": None, "band_idx": 0}
self._num_stopped = 0
self._metric = metric
self._mode = mode
self._metric_op = None
if self._mode == "max":
self._metric_op = 1.0
elif self._mode == "min":
self._metric_op = -1.0
self._time_attr = time_attr
self._stop_last_trials = stop_last_trials
def set_search_properties(
self, metric: Optional[str], mode: Optional[str], **spec
) -> bool:
if self._metric and metric:
return False
if self._mode and mode:
return False
if metric:
self._metric = metric
if mode:
self._mode = mode
if self._mode == "max":
self._metric_op = 1.0
elif self._mode == "min":
self._metric_op = -1.0
if self._metric is None and self._mode:
# If only a mode was passed, use anonymous metric
self._metric = DEFAULT_METRIC
return True
def on_trial_add(self, tune_controller: "TuneController", trial: Trial):
"""Adds new trial.
On a new trial add, if current bracket is not filled,
add to current bracket. Else, if current band is not filled,
create new bracket, add to current bracket.
Else, create new iteration, create new bracket, add to bracket."""
if not self._metric or not self._metric_op:
raise ValueError(
"{} has been instantiated without a valid `metric` ({}) or "
"`mode` ({}) parameter. Either pass these parameters when "
"instantiating the scheduler, or pass them as parameters "
"to `tune.TuneConfig()`".format(
self.__class__.__name__, self._metric, self._mode
)
)
cur_bracket = self._state["bracket"]
cur_band = self._hyperbands[self._state["band_idx"]]
if cur_bracket is None or cur_bracket.filled():
retry = True
while retry:
# if current iteration is filled, create new iteration
if self._cur_band_filled():
cur_band = []
self._hyperbands.append(cur_band)
self._state["band_idx"] += 1
# cur_band will always be less than s_max_1 or else filled
s = len(cur_band)
assert s < self._s_max_1, "Current band is filled!"
if self._get_r0(s) == 0:
logger.info("Bracket too small - Retrying...")
cur_bracket = None
else:
retry = False
cur_bracket = self._create_bracket(s)
cur_band.append(cur_bracket)
self._state["bracket"] = cur_bracket
self._state["bracket"].add_trial(trial)
self._trial_info[trial] = cur_bracket, self._state["band_idx"]
def _create_bracket(self, s):
return _Bracket(
time_attr=self._time_attr,
max_trials=self._get_n0(s),
init_t_attr=self._get_r0(s),
max_t_attr=self._max_t_attr,
eta=self._eta,
s=s,
stop_last_trials=self._stop_last_trials,
)
def _cur_band_filled(self) -> bool:
"""Checks if the current band is filled.
The size of the current band should be equal to s_max_1"""
cur_band = self._hyperbands[self._state["band_idx"]]
return len(cur_band) == self._s_max_1
def on_trial_result(
self, tune_controller: "TuneController", trial: Trial, result: Dict
):
"""If bracket is finished, all trials will be stopped.
If a given trial finishes and bracket iteration is not done,
the trial will be paused and resources will be given up.
This scheduler will not start trials but will stop trials.
The current running trial will not be handled,
as the trialrunner will be given control to handle it."""
bracket, _ = self._trial_info[trial]
bracket.update_trial_stats(trial, result)
if bracket.continue_trial(trial):
return TrialScheduler.CONTINUE
logger.debug(f"Processing bracket after trial {trial} result")
action = self._process_bracket(tune_controller, bracket)
logger.debug(
f"{action} for {trial} on "
f"{self._time_attr}={result.get(self._time_attr)}"
)
return action
def _process_bracket(
self, tune_controller: "TuneController", bracket: "_Bracket"
) -> str:
"""This is called whenever a trial makes progress.
When all live trials in the bracket have no more iterations left,
Trials will be successively halved. If bracket is done, all
non-running trials will be stopped and cleaned up,
and during each halving phase, bad trials will be stopped while good
trials will return to "PENDING".
Note some implicit conditions here: In ``on_trial_result`` a trial is
either continued (e.g. if it didn't reach the time threshold for the bracket)
or this method (``_process_bracket``) is called. If there are other trials left
that still haven't reached the threshold, the trial is PAUSED. This means
that when the bracket is actually processed (``bracket.cur_iter_done``), there
is at most one RUNNING trial (which is the trial that is currently processed)
and the rest are either PAUSED (as explained above) or TERMINATED/ERRORED
(if they finish separately).
"""
action = TrialScheduler.PAUSE
if bracket.cur_iter_done():
if bracket.finished():
bracket.cleanup_full(tune_controller)
return TrialScheduler.STOP
bracket.is_being_processed = True
good, bad = bracket.successive_halving(self._metric, self._metric_op)
logger.debug(
f"Processing {len(good)} good and {len(bad)} bad trials in "
f"bracket {bracket}.\n"
f"Good: {good}\nBad: {bad}"
)
# kill bad trials
self._num_stopped += len(bad)
for t in bad:
if t.status == Trial.PAUSED or t.is_saving:
logger.debug(f"Stopping other trial {str(t)}")
tune_controller.stop_trial(t)
elif t.status == Trial.RUNNING:
# See the docstring: There can only be at most one RUNNING
# trial, which is the current trial.
logger.debug(f"Stopping current trial {str(t)}")
bracket.cleanup_trial(t)
action = TrialScheduler.STOP
else:
# Trials cannot be ERROR/TERMINATED, as then they would have
# been removed from the bracket (in `bracket.cleanup_trial`).
# Trials cannot be PENDING, as then they wouldn't have reported
# enough results to finish the bracket, and it wouldn't be
# processed.
raise TuneError(
f"Trial with unexpected bad status encountered: "
f"{str(t)} is {t.status}"
)
# ready the good trials - if trial is too far ahead, don't continue
for t in good:
if bracket.continue_trial(t):
# The scheduler should have cleaned up this trial already.
assert t.status not in (Trial.ERROR, Trial.TERMINATED), (
f"Good trial {t.trial_id} is in an invalid state: {t.status}\n"
"Expected trial to be either PAUSED, PENDING, or RUNNING.\n"
"If you encounter this, please file an issue on the Ray Github."
)
if t.status == Trial.PAUSED or t.is_saving:
logger.debug(f"Unpausing trial {str(t)}")
self._unpause_trial(tune_controller, t)
bracket.trials_to_unpause.add(t)
elif t.status == Trial.RUNNING:
# See the docstring: There can only be at most one RUNNING
# trial, which is the current trial.
logger.debug(f"Continuing current trial {str(t)}")
action = TrialScheduler.CONTINUE
# else: PENDING trial (from a previous unpause) should stay as is.
elif bracket.finished() and bracket.stop_last_trials:
# Scheduler decides to not continue trial because the bracket
# reached max_t. In this case, stop the trials
if t.status == Trial.PAUSED or t.is_saving:
logger.debug(f"Bracket finished. Stopping other trial {str(t)}")
tune_controller.stop_trial(t)
elif t.status == Trial.RUNNING:
# See the docstring: There can only be at most one RUNNING
# trial, which is the current trial.
logger.debug(
f"Bracket finished. Stopping current trial {str(t)}"
)
bracket.cleanup_trial(t)
action = TrialScheduler.STOP
return action
def _unpause_trial(self, tune_controller: "TuneController", trial: Trial):
"""No-op by default."""
return
def on_trial_remove(self, tune_controller: "TuneController", trial: Trial):
"""Notification when trial terminates.
Trial info is removed from bracket. Triggers halving if bracket is
not finished."""
bracket, _ = self._trial_info[trial]
bracket.cleanup_trial(trial)
if not bracket.finished() and not bracket.is_being_processed:
logger.debug(f"Processing bracket after trial {trial} removed")
self._process_bracket(tune_controller, bracket)
def on_trial_complete(
self, tune_controller: "TuneController", trial: Trial, result: Dict
):
"""Cleans up trial info from bracket if trial completed early."""
self.on_trial_remove(tune_controller, trial)
def on_trial_error(self, tune_controller: "TuneController", trial: Trial):
"""Cleans up trial info from bracket if trial errored early."""
self.on_trial_remove(tune_controller, trial)
def choose_trial_to_run(self, tune_controller: "TuneController") -> Optional[Trial]:
"""Fair scheduling within iteration by completion percentage.
List of trials not used since all trials are tracked as state
of scheduler. If iteration is occupied (ie, no trials to run),
then look into next iteration.
"""
for hyperband in self._hyperbands:
# band will have None entries if no resources
# are to be allocated to that bracket.
scrubbed = [b for b in hyperband if b is not None]
for bracket in sorted(scrubbed, key=lambda b: b.completion_percentage()):
for trial in bracket.current_trials():
if (
trial.status == Trial.PAUSED
and trial in bracket.trials_to_unpause
) or trial.status == Trial.PENDING:
return trial
return None
def debug_string(self) -> str:
"""This provides a progress notification for the algorithm.
For each bracket, the algorithm will output a string as follows:
Bracket(Max Size (n)=5, Milestone (r)=33, completed=14.6%):
{PENDING: 2, RUNNING: 3, TERMINATED: 2}
"Max Size" indicates the max number of pending/running experiments
set according to the Hyperband algorithm.
"Milestone" indicates the iterations a trial will run for before
the next halving will occur.
"Completed" indicates an approximate progress metric. Some brackets,
like ones that are unfilled, will not reach 100%.
"""
out = "Using HyperBand: "
out += "num_stopped={} total_brackets={}".format(
self._num_stopped, sum(len(band) for band in self._hyperbands)
)
for i, band in enumerate(self._hyperbands):
out += "\nRound #{}:".format(i)
for bracket in band:
if bracket:
out += "\n {}".format(bracket)
return out
def state(self) -> Dict[str, int]:
return {
"num_brackets": sum(len(band) for band in self._hyperbands),
"num_stopped": self._num_stopped,
}
| HyperBandScheduler |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/interfaces.py | {
"start": 3307,
"end": 3610
} | class ____(Protocol):
class Error(Exception):
def __getattr__(self, key: str) -> Any: ...
class OperationalError(Error):
pass
class InterfaceError(Error):
pass
class IntegrityError(Error):
pass
def __getattr__(self, key: str) -> Any: ...
| DBAPIModule |
python | ray-project__ray | release/serve_tests/workloads/serve_resnet_benchmark.py | {
"start": 2509,
"end": 6860
} | class ____:
def __init__(self):
# For mutiple process scheduled in same node, torch.hub.load doesn't
# handle the multi process to dowloand module well. So this is to make sure
# there is only one replica to download the package
if os.path.exists("/home/ray/.cache/torch/") is False:
self.utils = torch.hub.load(
"NVIDIA/DeepLearningExamples:torchhub",
"nvidia_convnets_processing_utils",
)
with open("/home/ray/.cache/torch/success", "w") as _:
pass
else:
counter = 3
while counter:
print("waiting for torch hub NVIDIA package download...")
time.sleep(20)
if os.path.exists("/home/ray/.cache/torch/success"):
self.utils = torch.hub.load(
"NVIDIA/DeepLearningExamples:torchhub",
"nvidia_convnets_processing_utils",
)
break
counter -= 1
if counter == 0:
raise Exception(
"Failed to load module nvidia_convnets_processing_utils"
)
def __call__(self, uris: List[str]):
return [self.utils.prepare_input_from_uri(uri) for uri in uris]
async def measure_http_throughput_tps(data_size: int = 8, requests_sent: int = 8):
tps_stats = []
model_inference_stats = []
async def fetch(session):
async with session.get(
"http://localhost:8000/", json=input_uris * int(data_size / len(input_uris))
) as response:
return await response.json()
async with aiohttp.ClientSession() as session:
for _ in range(requests_sent):
start = time.time()
res = await fetch(session)
end = time.time()
tps_stats.append(data_size / (end - start))
model_inference_stats.append(res["model_inference_latency"])
return tps_stats, model_inference_stats
async def trial(measure_func, data_size: int = 8, num_clients: int = 1):
client_tasks = [measure_func for _ in range(num_clients)]
result_stats_list = await asyncio.gather(
*[client_task(data_size) for client_task in client_tasks]
)
throughput_stats_tps = []
for client_stats in result_stats_list:
throughput_stats_tps.extend(client_stats[0])
throughput_mean = round(np.mean(throughput_stats_tps), 2)
model_inference_latency = []
for client_stats in result_stats_list:
model_inference_latency.extend(client_stats[1])
inference_latency_mean = round(np.mean(model_inference_latency), 2)
return throughput_mean, inference_latency_mean
@click.command()
@click.option(
"--gpu-env",
type=bool,
is_flag=True,
default=False,
help="If it is set, the model inference will be run on the GPU,"
"otherwise it is run on CPU",
)
@click.option("--smoke-run", type=bool, is_flag=True, default=False)
def main(gpu_env: Optional[bool], smoke_run: Optional[bool]):
test_name = "resnet50_cpu"
device = "cpu"
if gpu_env:
test_name = "resnet50_gpu"
device = "cuda"
io = ImageObjectioner.options(ray_actor_options={"num_gpus": 1}).bind(
DataDownloader.bind(), device=device
)
else:
io = ImageObjectioner.bind(DataDownloader.bind(), device=device)
handle = serve.run(io)
if smoke_run:
res = handle.predict.remote(input_uris)
print(res.result())
else:
result = {}
print("warming up...")
for _ in range(10):
handle.predict.remote([input_uris[0]]).result()
print("start load testing...")
batch_sizes = [16, 32, 64]
for batch_size in batch_sizes:
throughput_mean_tps, model_inference_latency_mean = asyncio.run(
trial(measure_http_throughput_tps, batch_size)
)
result[f"batch size {batch_size}"] = {
"throughput_mean_tps": throughput_mean_tps,
"model_inference_latency_mean": model_inference_latency_mean,
}
print(throughput_mean_tps, model_inference_latency_mean)
save_test_results({test_name: result})
if __name__ == "__main__":
main()
| DataDownloader |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 878325,
"end": 879110
} | class ____(sgqlc.types.relay.Connection):
"""Review comment threads for a pull request review."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("PullRequestReviewThreadEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Field(sgqlc.types.list_of("PullRequestReviewThread"), graphql_name="nodes")
"""A list of nodes."""
page_info = sgqlc.types.Field(sgqlc.types.non_null(PageInfo), graphql_name="pageInfo")
"""Information to aid in pagination."""
total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount")
"""Identifies the total count of items in the connection."""
| PullRequestReviewThreadConnection |
python | tensorflow__tensorflow | tensorflow/python/keras/backend.py | {
"start": 5352,
"end": 28506
} | class ____(threading.local):
"""_DummyEagerGraph provides a thread local `key` attribute.
We can't use threading.local directly, i.e. without subclassing, because
gevent monkey patches threading.local and its version does not support
weak references.
"""
class _WeakReferencableClass:
"""This dummy class is needed for two reasons.
- We need something that supports weak references. Basic types like string
and ints don't.
- We need something whose hash and equality are based on object identity
to make sure they are treated as different keys to _GRAPH_LEARNING_PHASES.
An empty Python class satisfies both of these requirements.
"""
pass
def __init__(self):
# Constructors for classes subclassing threading.local run once
# per thread accessing something in the class. Thus, each thread will
# get a different key.
super(_DummyEagerGraph, self).__init__()
self.key = _DummyEagerGraph._WeakReferencableClass()
self.learning_phase_is_set = False
_DUMMY_EAGER_GRAPH = _DummyEagerGraph()
# This boolean flag can be set to True to leave variable initialization
# up to the user.
# Change its value via `manual_variable_initialization(value)`.
_MANUAL_VAR_INIT = False
# This list holds the available devices.
# It is populated when `_get_available_gpus()` is called for the first time.
# We assume our devices don't change henceforth.
_LOCAL_DEVICES = None
# The below functions are kept accessible from backend for compatibility.
epsilon = backend_config.epsilon
floatx = backend_config.floatx
image_data_format = backend_config.image_data_format
set_epsilon = backend_config.set_epsilon
set_floatx = backend_config.set_floatx
set_image_data_format = backend_config.set_image_data_format
@doc_controls.do_not_generate_docs
def backend():
"""Publicly accessible method for determining the current backend.
Only exists for API compatibility with multi-backend Keras.
Returns:
The string "tensorflow".
"""
return 'tensorflow'
@dispatch.add_dispatch_support
@doc_controls.do_not_generate_docs
def cast_to_floatx(x):
"""Cast a Numpy array to the default Keras float type.
Args:
x: Numpy array or TensorFlow tensor.
Returns:
The same array (Numpy array if `x` was a Numpy array, or TensorFlow tensor
if `x` was a tensor), cast to its new type.
Example:
>>> tf.keras.backend.floatx()
'float32'
>>> arr = np.array([1.0, 2.0], dtype='float64')
>>> arr.dtype
dtype('float64')
>>> new_arr = cast_to_floatx(arr)
>>> new_arr
array([1., 2.], dtype=float32)
>>> new_arr.dtype
dtype('float32')
"""
if isinstance(x, (tensor_lib.Tensor,
variables_module.Variable,
sparse_tensor.SparseTensor)):
return math_ops.cast(x, dtype=floatx())
return numpy_compat.np_asarray(x, dtype=floatx())
def get_uid(prefix=''):
"""Associates a string prefix with an integer counter in a TensorFlow graph.
Args:
prefix: String prefix to index.
Returns:
Unique integer ID.
Example:
>>> get_uid('dense')
1
>>> get_uid('dense')
2
"""
graph = get_graph()
if graph not in PER_GRAPH_OBJECT_NAME_UIDS:
PER_GRAPH_OBJECT_NAME_UIDS[graph] = collections.defaultdict(int)
layer_name_uids = PER_GRAPH_OBJECT_NAME_UIDS[graph]
layer_name_uids[prefix] += 1
return layer_name_uids[prefix]
def reset_uids():
"""Resets graph identifiers.
"""
PER_GRAPH_OBJECT_NAME_UIDS.clear()
OBSERVED_NAMES.clear()
def clear_session():
"""Resets all state generated by Keras.
Keras manages a global state, which it uses to implement the Functional
model-building API and to uniquify autogenerated layer names.
If you are creating many models in a loop, this global state will consume
an increasing amount of memory over time, and you may want to clear it.
Calling `clear_session()` releases the global state: this helps avoid clutter
from old models and layers, especially when memory is limited.
Example 1: calling `clear_session()` when creating models in a loop
```python
for _ in range(100):
# Without `clear_session()`, each iteration of this loop will
# slightly increase the size of the global state managed by Keras
model = tf.keras.Sequential([tf.keras.layers.Dense(10) for _ in range(10)])
for _ in range(100):
# With `clear_session()` called at the beginning,
# Keras starts with a blank state at each iteration
# and memory consumption is constant over time.
tf.keras.backend.clear_session()
model = tf.keras.Sequential([tf.keras.layers.Dense(10) for _ in range(10)])
```
Example 2: resetting the layer name generation counter
>>> import tensorflow as tf
>>> layers = [tf.keras.layers.Dense(10) for _ in range(10)]
>>> new_layer = tf.keras.layers.Dense(10)
>>> print(new_layer.name)
dense_10
>>> tf.keras.backend.set_learning_phase(1)
>>> print(tf.keras.backend.learning_phase())
1
>>> tf.keras.backend.clear_session()
>>> new_layer = tf.keras.layers.Dense(10)
>>> print(new_layer.name)
dense
"""
global _SESSION
global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned
global _GRAPH_VARIABLES # pylint: disable=global-variable-not-assigned
global _GRAPH_TF_OPTIMIZERS # pylint: disable=global-variable-not-assigned
global _GRAPH
_GRAPH.graph = None
ops.reset_default_graph()
reset_uids()
_SESSION.session = None
graph = get_graph()
with graph.as_default():
_DUMMY_EAGER_GRAPH.learning_phase_is_set = False
_GRAPH_LEARNING_PHASES.clear()
# Create the learning phase placeholder in graph using the default factory.
_GRAPH_LEARNING_PHASES.setdefault(graph)
_GRAPH_VARIABLES.pop(graph, None)
_GRAPH_TF_OPTIMIZERS.pop(graph, None)
if context.executing_eagerly():
# Clear pending nodes in eager executors, kernel caches and step_containers.
context.context().clear_kernel_cache()
@doc_controls.do_not_generate_docs
def manual_variable_initialization(value):
"""Sets the manual variable initialization flag.
This boolean flag determines whether
variables should be initialized
as they are instantiated (default), or if
the user should handle the initialization
(e.g. via `tf.compat.v1.initialize_all_variables()`).
Args:
value: Python boolean.
"""
global _MANUAL_VAR_INIT
_MANUAL_VAR_INIT = value
@doc_controls.do_not_generate_docs
def learning_phase():
"""Returns the learning phase flag.
The learning phase flag is a bool tensor (0 = test, 1 = train)
to be passed as input to any Keras function
that uses a different behavior at train time and test time.
Returns:
Learning phase (scalar integer tensor or Python integer).
"""
graph = ops.get_default_graph()
if graph is getattr(_GRAPH, 'graph', None):
# Don't enter an init_scope for the learning phase if eager execution
# is enabled but we're inside the Keras workspace graph.
learning_phase = symbolic_learning_phase()
else:
with ops.init_scope():
# We always check & set the learning phase inside the init_scope,
# otherwise the wrong default_graph will be used to look up the learning
# phase inside of functions & defuns.
#
# This is because functions & defuns (both in graph & in eager mode)
# will always execute non-eagerly using a function-specific default
# subgraph.
learning_phase = _GRAPH_LEARNING_PHASES[None]
_mark_func_graph_as_unsaveable(graph, learning_phase)
return learning_phase
def global_learning_phase_is_set():
return _DUMMY_EAGER_GRAPH.learning_phase_is_set
def _mark_func_graph_as_unsaveable(graph, learning_phase):
"""Mark func graph as unsaveable due to use of symbolic keras learning phase.
Functions that capture the symbolic learning phase cannot be exported to
SavedModel. Mark the funcgraph as unsaveable, so that an error will be raised
if it is exported.
Args:
graph: Graph or FuncGraph object.
learning_phase: Learning phase placeholder or int defined in the graph.
"""
if graph.building_function and is_placeholder(learning_phase):
graph.mark_as_unsaveable(
'The keras learning phase placeholder was used inside a function. '
'Exporting placeholders is not supported when saving out a SavedModel. '
'Please call `tf.keras.backend.set_learning_phase(0)` in the function '
'to set the learning phase to a constant value.')
def symbolic_learning_phase():
graph = get_graph()
with graph.as_default():
return _GRAPH_LEARNING_PHASES[graph]
def _default_learning_phase():
if context.executing_eagerly():
return 0
else:
with name_scope(''):
return array_ops.placeholder_with_default(
False, shape=(), name='keras_learning_phase')
@doc_controls.do_not_generate_docs
def set_learning_phase(value):
"""Sets the learning phase to a fixed value.
The backend learning phase affects any code that calls
`backend.learning_phase()`
In particular, all Keras built-in layers use the learning phase as the default
for the `training` arg to `Layer.__call__`.
User-written layers and models can achieve the same behavior with code that
looks like:
```python
def call(self, inputs, training=None):
if training is None:
training = backend.learning_phase()
```
Args:
value: Learning phase value, either 0 or 1 (integers).
0 = test, 1 = train
Raises:
ValueError: if `value` is neither `0` nor `1`.
"""
warnings.warn('`tf.keras.backend.set_learning_phase` is deprecated and '
'will be removed after 2020-10-11. To update it, simply '
'pass a True/False value to the `training` argument of the '
'`__call__` method of your layer or model.')
deprecated_internal_set_learning_phase(value)
def deprecated_internal_set_learning_phase(value):
"""A deprecated internal implementation of set_learning_phase.
This method is an internal-only version of `set_learning_phase` that
does not raise a deprecation error. It is required because
saved_model needs to keep working with user code that uses the deprecated
learning phase methods until those APIs are fully removed from the public API.
Specifically SavedModel saving needs to make sure the learning phase is 0
during tracing even if users overwrote it to a different value.
But, we don't want to raise deprecation warnings for users when savedmodel
sets learning phase just for compatibility with code that relied on
explicitly setting the learning phase for other values.
Args:
value: Learning phase value, either 0 or 1 (integers). 0 = test, 1 = train
Raises:
ValueError: if `value` is neither `0` nor `1`.
"""
global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned
if value not in {0, 1}:
raise ValueError('Expected learning phase to be 0 or 1.')
with ops.init_scope():
if context.executing_eagerly():
# In an eager context, the learning phase values applies to both the eager
# context and the internal Keras graph.
_DUMMY_EAGER_GRAPH.learning_phase_is_set = True
_GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key] = value
_GRAPH_LEARNING_PHASES[get_graph()] = value
@tf_contextlib.contextmanager
@doc_controls.do_not_generate_docs
def learning_phase_scope(value):
"""Provides a scope within which the learning phase is equal to `value`.
The learning phase gets restored to its original value upon exiting the scope.
Args:
value: Learning phase value, either 0 or 1 (integers).
0 = test, 1 = train
Yields:
None.
Raises:
ValueError: if `value` is neither `0` nor `1`.
"""
warnings.warn('`tf.keras.backend.learning_phase_scope` is deprecated and '
'will be removed after 2020-10-11. To update it, simply '
'pass a True/False value to the `training` argument of the '
'`__call__` method of your layer or model.')
with deprecated_internal_learning_phase_scope(value):
try:
yield
finally:
pass
@tf_contextlib.contextmanager
def deprecated_internal_learning_phase_scope(value):
"""An internal-only version of `learning_phase_scope`.
Unlike the public method, this method does not raise a deprecation warning.
This is needed because saved model saving needs to set learning phase
to maintain compatibility
with code that sets/gets the learning phase, but saved model
saving itself shouldn't raise a deprecation warning.
We can get rid of this method and its usages when the public API is
removed.
Args:
value: Learning phase value, either 0 or 1 (integers). 0 = test, 1 = train
Yields:
None.
Raises:
ValueError: if `value` is neither `0` nor `1`.
"""
global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned
if value not in {0, 1}:
raise ValueError('Expected learning phase to be 0 or 1.')
with ops.init_scope():
if context.executing_eagerly():
previous_eager_value = _GRAPH_LEARNING_PHASES.get(
_DUMMY_EAGER_GRAPH.key, None)
previous_graph_value = _GRAPH_LEARNING_PHASES.get(get_graph(), None)
learning_phase_previously_set = _DUMMY_EAGER_GRAPH.learning_phase_is_set
try:
deprecated_internal_set_learning_phase(value)
yield
finally:
# Restore learning phase to initial value.
if not learning_phase_previously_set:
_DUMMY_EAGER_GRAPH.learning_phase_is_set = False
with ops.init_scope():
if context.executing_eagerly():
if previous_eager_value is not None:
_GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key] = previous_eager_value
elif _DUMMY_EAGER_GRAPH.key in _GRAPH_LEARNING_PHASES:
del _GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key]
graph = get_graph()
if previous_graph_value is not None:
_GRAPH_LEARNING_PHASES[graph] = previous_graph_value
elif graph in _GRAPH_LEARNING_PHASES:
del _GRAPH_LEARNING_PHASES[graph]
@tf_contextlib.contextmanager
def eager_learning_phase_scope(value):
"""Internal scope that sets the learning phase in eager / tf.function only.
Args:
value: Learning phase value, either 0 or 1 (integers).
0 = test, 1 = train
Yields:
None.
Raises:
ValueError: if `value` is neither `0` nor `1`.
"""
global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned
assert value in {0, 1}
assert ops.executing_eagerly_outside_functions()
global_learning_phase_was_set = global_learning_phase_is_set()
if global_learning_phase_was_set:
previous_value = learning_phase()
try:
_GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key] = value
yield
finally:
# Restore learning phase to initial value or unset.
if global_learning_phase_was_set:
_GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key] = previous_value
else:
del _GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key]
def _as_graph_element(obj):
"""Convert `obj` to a graph element if possible, otherwise return `None`.
Args:
obj: Object to convert.
Returns:
The result of `obj._as_graph_element()` if that method is available;
otherwise `None`.
"""
conv_fn = getattr(obj, '_as_graph_element', None)
if conv_fn and callable(conv_fn):
return conv_fn()
return None
def _assert_same_graph(original_item, item):
"""Fail if the 2 items are from different graphs.
Args:
original_item: Original item to check against.
item: Item to check.
Raises:
ValueError: if graphs do not match.
"""
original_graph = getattr(original_item, 'graph', None)
graph = getattr(item, 'graph', None)
if original_graph and graph and original_graph is not graph:
raise ValueError(
'%s must be from the same graph as %s (graphs are %s and %s).' %
(item, original_item, graph, original_graph))
def _current_graph(op_input_list, graph=None):
"""Returns the appropriate graph to use for the given inputs.
This library method provides a consistent algorithm for choosing the graph
in which an Operation should be constructed:
1. If the default graph is being used to construct a function, we
use the default graph.
2. If the "graph" is specified explicitly, we validate that all of the inputs
in "op_input_list" are compatible with that graph.
3. Otherwise, we attempt to select a graph from the first Operation-
or Tensor-valued input in "op_input_list", and validate that all other
such inputs are in the same graph.
4. If the graph was not specified and it could not be inferred from
"op_input_list", we attempt to use the default graph.
Args:
op_input_list: A list of inputs to an operation, which may include `Tensor`,
`Operation`, and other objects that may be converted to a graph element.
graph: (Optional) The explicit graph to use.
Raises:
TypeError: If op_input_list is not a list or tuple, or if graph is not a
Graph.
ValueError: If a graph is explicitly passed and not all inputs are from it,
or if the inputs are from multiple graphs, or we could not find a graph
and there was no default graph.
Returns:
The appropriate graph to use for the given inputs.
"""
current_default_graph = ops.get_default_graph()
if current_default_graph.building_function:
return current_default_graph
op_input_list = tuple(op_input_list) # Handle generators correctly
if graph and not isinstance(graph, ops.Graph):
raise TypeError('Input graph needs to be a Graph: %s' % (graph,))
# 1. We validate that all of the inputs are from the same graph. This is
# either the supplied graph parameter, or the first one selected from one
# the graph-element-valued inputs. In the latter case, we hold onto
# that input in original_graph_element so we can provide a more
# informative error if a mismatch is found.
original_graph_element = None
for op_input in op_input_list:
# Determine if this is a valid graph_element.
# TODO(josh11b): Note that we exclude subclasses of Tensor. Need to clean this
# up.
if (isinstance(op_input, (
ops.Operation, tensor_lib.Tensor, composite_tensor.CompositeTensor)) and
((not isinstance(op_input, tensor_lib.Tensor))
or type(op_input) == tensor_lib.Tensor)): # pylint: disable=unidiomatic-typecheck
graph_element = op_input
else:
graph_element = _as_graph_element(op_input)
if graph_element is not None:
if not graph:
original_graph_element = graph_element
graph = getattr(graph_element, 'graph', None)
elif original_graph_element is not None:
_assert_same_graph(original_graph_element, graph_element)
elif graph_element.graph is not graph:
raise ValueError('%s is not from the passed-in graph.' % graph_element)
# 2. If all else fails, we use the default graph, which is always there.
return graph or current_default_graph
def _get_session(op_input_list=()):
"""Returns the session object for the current thread."""
global _SESSION
default_session = ops.get_default_session()
if default_session is not None:
session = default_session
else:
if ops.inside_function():
raise RuntimeError('Cannot get session inside Tensorflow graph function.')
# If we don't have a session, or that session does not match the current
# graph, create and cache a new session.
if (getattr(_SESSION, 'session', None) is None or
_SESSION.session.graph is not _current_graph(op_input_list)):
# If we are creating the Session inside a tf.distribute.Strategy scope,
# we ask the strategy for the right session options to use.
if distribute_lib.has_strategy():
configure_and_create_distributed_session(
distribute_lib.get_strategy())
else:
_SESSION.session = session_module.Session(
config=get_default_session_config())
session = _SESSION.session
return session
def get_session(op_input_list=()):
"""Returns the TF session to be used by the backend.
If a default TensorFlow session is available, we will return it.
Else, we will return the global Keras session assuming it matches
the current graph.
If no global Keras session exists at this point:
we will create a new global session.
Note that you can manually set the global session
via `K.set_session(sess)`.
Args:
op_input_list: An option sequence of tensors or ops, which will be used
to determine the current graph. Otherwise the default graph will be
used.
Returns:
A TensorFlow session.
"""
session = _get_session(op_input_list)
if not _MANUAL_VAR_INIT:
with session.graph.as_default():
_initialize_variables(session)
return session
def get_graph():
if context.executing_eagerly():
global _GRAPH
if not getattr(_GRAPH, 'graph', None):
_GRAPH.graph = func_graph.FuncGraph('keras_graph')
return _GRAPH.graph
else:
return ops.get_default_graph()
@tf_contextlib.contextmanager
def _scratch_graph(graph=None):
"""Retrieve a shared and temporary func graph.
The eager execution path lifts a subgraph from the keras global graph into
a scratch graph in order to create a function. DistributionStrategies, in
turn, constructs multiple functions as well as a final combined function. In
order for that logic to work correctly, all of the functions need to be
created on the same scratch FuncGraph.
Args:
graph: A graph to be used as the current scratch graph. If not set then
a scratch graph will either be retrieved or created:
Yields:
The current scratch graph.
"""
global _CURRENT_SCRATCH_GRAPH
scratch_graph = getattr(_CURRENT_SCRATCH_GRAPH, 'graph', None)
# If scratch graph and `graph` are both configured, they must match.
if (scratch_graph is not None and graph is not None and
scratch_graph is not graph):
raise ValueError('Multiple scratch graphs specified.')
if scratch_graph:
yield scratch_graph
return
graph = graph or func_graph.FuncGraph('keras_scratch_graph')
try:
_CURRENT_SCRATCH_GRAPH.graph = graph
yield graph
finally:
_CURRENT_SCRATCH_GRAPH.graph = None
def set_session(session):
"""Sets the global TensorFlow session.
Args:
session: A TF Session.
"""
global _SESSION
_SESSION.session = session
def get_default_session_config():
if os.environ.get('OMP_NUM_THREADS'):
logging.warning(
'OMP_NUM_THREADS is no longer used by the default Keras config. '
'To configure the number of threads, use tf.config.threading APIs.')
config = get_config()
config.allow_soft_placement = True
return config
def get_default_graph_uid_map():
graph = ops.get_default_graph()
name_uid_map = PER_GRAPH_OBJECT_NAME_UIDS.get(graph, None)
if name_uid_map is None:
name_uid_map = collections.defaultdict(int)
PER_GRAPH_OBJECT_NAME_UIDS[graph] = name_uid_map
return name_uid_map
# DEVICE MANIPULATION
| _DummyEagerGraph |
python | wandb__wandb | wandb/automations/_generated/integrations_by_entity.py | {
"start": 1109,
"end": 1458
} | class ____(GQLResult):
typename__: Typename[Literal["GitHubOAuthIntegration", "Integration"]]
IntegrationsByEntity.model_rebuild()
IntegrationsByEntityEntity.model_rebuild()
IntegrationsByEntityEntityIntegrations.model_rebuild()
IntegrationsByEntityEntityIntegrationsEdges.model_rebuild()
| IntegrationsByEntityEntityIntegrationsEdgesNodeIntegration |
python | keras-team__keras | keras/src/callbacks/history.py | {
"start": 139,
"end": 1301
} | class ____(Callback):
"""Callback that records events into a `History` object.
This callback is automatically applied to
every Keras model. The `History` object
gets returned by the `fit()` method of models.
Example:
>>> model = Sequential([layers.Dense(10)])
>>> model.compile(SGD(), loss='mse')
>>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5),
... epochs=10, verbose=1)
>>> print(history.params)
{'verbose': 1, 'epochs': 10, 'steps': 1}
>>> # check the keys of history object
>>> print(history.history.keys())
dict_keys(['loss'])
"""
def __init__(self):
super().__init__()
self.history = {}
def on_train_begin(self, logs=None):
self.epoch = []
def on_epoch_end(self, epoch, logs=None):
logs = logs or {}
self.epoch.append(epoch)
for k, v in logs.items():
self.history.setdefault(k, []).append(v)
# Set the history attribute on the model after the epoch ends. This will
# make sure that the state which is set is the latest one.
self.model.history = self
| History |
python | kamyu104__LeetCode-Solutions | Python/clone-binary-tree-with-random-pointer.py | {
"start": 3432,
"end": 4073
} | class ____(object):
def copyRandomBinaryTree(self, root):
"""
:type root: Node
:rtype: NodeCopy
"""
def dfs(node, lookup):
if not node:
return
lookup[node].val = node.val
lookup[node].left = lookup[node.left]
lookup[node].right = lookup[node.right]
lookup[node].random = lookup[node.random]
dfs(node.left, lookup)
dfs(node.right, lookup)
lookup = collections.defaultdict(lambda: NodeCopy())
lookup[None] = None
dfs(root, lookup)
return lookup[root]
| Solution2_Recu |
python | huggingface__transformers | src/transformers/models/encodec/modeling_encodec.py | {
"start": 9407,
"end": 9983
} | class ____(nn.Module):
"""
LSTM without worrying about the hidden state, nor the layout of the data. Expects input as convolutional layout.
"""
def __init__(self, config: EncodecConfig, dimension: int):
super().__init__()
self.lstm = nn.LSTM(dimension, dimension, config.num_lstm_layers)
def forward(self, hidden_states):
hidden_states = hidden_states.permute(2, 0, 1)
hidden_states = self.lstm(hidden_states)[0] + hidden_states
hidden_states = hidden_states.permute(1, 2, 0)
return hidden_states
| EncodecLSTM |
python | matplotlib__matplotlib | lib/matplotlib/patches.py | {
"start": 46833,
"end": 52868
} | class ____(Polygon):
"""
Like Arrow, but lets you set head width and head height independently.
"""
_edge_default = True
def __str__(self):
return "FancyArrow()"
@_docstring.interpd
def __init__(self, x, y, dx, dy, *,
width=0.001, length_includes_head=False, head_width=None,
head_length=None, shape='full', overhang=0,
head_starts_at_zero=False, **kwargs):
"""
Parameters
----------
x, y : float
The x and y coordinates of the arrow base.
dx, dy : float
The length of the arrow along x and y direction.
width : float, default: 0.001
Width of full arrow tail.
length_includes_head : bool, default: False
True if head is to be counted in calculating the length.
head_width : float or None, default: 3*width
Total width of the full arrow head.
head_length : float or None, default: 1.5*head_width
Length of arrow head.
shape : {'full', 'left', 'right'}, default: 'full'
Draw the left-half, right-half, or full arrow.
overhang : float, default: 0
Fraction that the arrow is swept back (0 overhang means
triangular shape). Can be negative or greater than one.
head_starts_at_zero : bool, default: False
If True, the head starts being drawn at coordinate 0
instead of ending at coordinate 0.
**kwargs
`.Patch` properties:
%(Patch:kwdoc)s
"""
self._x = x
self._y = y
self._dx = dx
self._dy = dy
self._width = width
self._length_includes_head = length_includes_head
self._head_width = head_width
self._head_length = head_length
self._shape = shape
self._overhang = overhang
self._head_starts_at_zero = head_starts_at_zero
self._make_verts()
super().__init__(self.verts, closed=True, **kwargs)
def set_data(self, *, x=None, y=None, dx=None, dy=None, width=None,
head_width=None, head_length=None):
"""
Set `.FancyArrow` x, y, dx, dy, width, head_with, and head_length.
Values left as None will not be updated.
Parameters
----------
x, y : float or None, default: None
The x and y coordinates of the arrow base.
dx, dy : float or None, default: None
The length of the arrow along x and y direction.
width : float or None, default: None
Width of full arrow tail.
head_width : float or None, default: None
Total width of the full arrow head.
head_length : float or None, default: None
Length of arrow head.
"""
if x is not None:
self._x = x
if y is not None:
self._y = y
if dx is not None:
self._dx = dx
if dy is not None:
self._dy = dy
if width is not None:
self._width = width
if head_width is not None:
self._head_width = head_width
if head_length is not None:
self._head_length = head_length
self._make_verts()
self.set_xy(self.verts)
def _make_verts(self):
if self._head_width is None:
head_width = 3 * self._width
else:
head_width = self._head_width
if self._head_length is None:
head_length = 1.5 * head_width
else:
head_length = self._head_length
distance = np.hypot(self._dx, self._dy)
if self._length_includes_head:
length = distance
else:
length = distance + head_length
if np.size(length) == 0:
self.verts = np.empty([0, 2]) # display nothing if empty
else:
# start by drawing horizontal arrow, point at (0, 0)
hw, hl = head_width, head_length
hs, lw = self._overhang, self._width
left_half_arrow = np.array([
[0.0, 0.0], # tip
[-hl, -hw / 2], # leftmost
[-hl * (1 - hs), -lw / 2], # meets stem
[-length, -lw / 2], # bottom left
[-length, 0],
])
# if we're not including the head, shift up by head length
if not self._length_includes_head:
left_half_arrow += [head_length, 0]
# if the head starts at 0, shift up by another head length
if self._head_starts_at_zero:
left_half_arrow += [head_length / 2, 0]
# figure out the shape, and complete accordingly
if self._shape == 'left':
coords = left_half_arrow
else:
right_half_arrow = left_half_arrow * [1, -1]
if self._shape == 'right':
coords = right_half_arrow
elif self._shape == 'full':
# The half-arrows contain the midpoint of the stem,
# which we can omit from the full arrow. Including it
# twice caused a problem with xpdf.
coords = np.concatenate([left_half_arrow[:-1],
right_half_arrow[-2::-1]])
else:
raise ValueError(f"Got unknown shape: {self._shape!r}")
if distance != 0:
cx = self._dx / distance
sx = self._dy / distance
else:
# Account for division by zero
cx, sx = 0, 1
M = [[cx, sx], [-sx, cx]]
self.verts = np.dot(coords, M) + [
self._x + self._dx,
self._y + self._dy,
]
_docstring.interpd.register(
FancyArrow="\n".join(
(inspect.getdoc(FancyArrow.__init__) or "").splitlines()[2:]))
| FancyArrow |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingTypeEquals1.py | {
"start": 1634,
"end": 1884
} | class ____(CParent): ...
_TC = TypeVar("_TC", bound=CParent)
def func8(a: _TC, b: _TC) -> _TC:
if type(a) == CChild:
reveal_type(a, expected_text="CChild*")
return a
reveal_type(a, expected_text="CParent*")
return a
| CChild |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 30221,
"end": 30556
} | class ____(FieldValues):
"""
Valid and invalid values for `RegexField`.
"""
valid_inputs = {
'a9': 'a9',
}
invalid_inputs = {
'A9': ["This value does not match the required pattern."]
}
outputs = {}
field = serializers.RegexField(regex=re.compile('[a-z][0-9]'))
| TestiCompiledRegexField |
python | doocs__leetcode | solution/0600-0699/0616.Add Bold Tag in String/Solution.py | {
"start": 0,
"end": 352
} | class ____:
def __init__(self):
self.children = [None] * 128
self.is_end = False
def insert(self, word):
node = self
for c in word:
idx = ord(c)
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.is_end = True
| Trie |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/limit_and_offset/tutorial001.py | {
"start": 433,
"end": 1659
} | class ____(HeroBase):
id: int
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
app = FastAPI()
@app.on_event("startup")
def on_startup():
create_db_and_tables()
@app.post("/heroes/", response_model=HeroPublic)
def create_hero(hero: HeroCreate):
with Session(engine) as session:
db_hero = Hero.model_validate(hero)
session.add(db_hero)
session.commit()
session.refresh(db_hero)
return db_hero
@app.get("/heroes/", response_model=List[HeroPublic])
def read_heroes(offset: int = 0, limit: int = Query(default=100, le=100)):
with Session(engine) as session:
heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
return heroes
@app.get("/heroes/{hero_id}", response_model=HeroPublic)
def read_hero(hero_id: int):
with Session(engine) as session:
hero = session.get(Hero, hero_id)
if not hero:
raise HTTPException(status_code=404, detail="Hero not found")
return hero
| HeroPublic |
python | pytransitions__transitions | tests/test_graphviz.py | {
"start": 13161,
"end": 13561
} | class ____(TestDiagrams):
machine_cls = LockedGraphMachine # type: Type[LockedGraphMachine]
@skipIf(sys.version_info < (3, ), "Python 2.7 cannot retrieve __name__ from partials")
def test_function_callbacks_annotation(self):
super(TestDiagramsLocked, self).test_function_callbacks_annotation()
@skipIf(pgv is None, 'NestedGraph diagram test requires graphviz')
| TestDiagramsLocked |
python | google__jax | tests/pallas/tpu_pallas_call_print_test.py | {
"start": 1441,
"end": 4915
} | class ____(PallasBaseTest):
def test_debug_print(self):
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
)
def kernel(x_ref, o_ref):
pl.debug_print('It works!')
x = jnp.arange(8 * 128, dtype=jnp.float32).reshape((8, 128))
compiled_kernel = (
jax.jit(kernel)
.lower(x)
.compile({'xla_tpu_enable_log_recorder': 'true'})
)
with jtu.capture_stderr() as get_output:
jax.block_until_ready(compiled_kernel(x))
self.assertIn('It works!', get_output())
def test_debug_print_in_index_map(self):
def index_map(i):
pl.debug_print('It works!')
return (i, 0)
@functools.partial(
self.pallas_call,
grid=(1,),
in_specs=(pl.BlockSpec(index_map=index_map),),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
)
def kernel(x_ref, o_ref):
o_ref[...] = x_ref[...]
x = jnp.arange(8 * 128, dtype=jnp.float32).reshape((8, 128))
compiled_kernel = (
jax.jit(kernel)
.lower(x)
.compile({'xla_tpu_enable_log_recorder': 'true'})
)
with jtu.capture_stderr() as get_output:
jax.block_until_ready(compiled_kernel(x))
self.assertIn('It works!', get_output())
def test_debug_print_with_values(self):
@functools.partial(
self.pallas_call,
in_specs=(pl.BlockSpec(memory_space=pltpu.SMEM),),
out_shape=jax.ShapeDtypeStruct((8, 128), jnp.float32),
)
def kernel(x_ref, o_ref):
pl.debug_print('BEGIN1 x[0] == {}', x_ref[0])
pl.debug_print('BEGIN2 x[0] == {} ; x[1] == {} ; END', x_ref[0], x_ref[1])
x = jnp.array([42, 24]).astype(jnp.int32)
compiled_kernel = (
jax.jit(kernel)
.lower(x)
.compile({'xla_tpu_enable_log_recorder': 'true'})
)
with jtu.capture_stderr() as get_output:
jax.block_until_ready(compiled_kernel(x))
output = get_output()
self.assertIn('BEGIN1 x[0] == 42', output)
self.assertIn('BEGIN2 x[0] == 42 ; x[1] == 24 ; END', output)
@parameterized.named_parameters(
(f"{'_'.join(map(str, shape))}_{dtype.__name__}", shape, dtype)
for shape in (
(2, 8, 128),
# test unaligned shapes
(3,),
(3, 4),
(2, 3, 4),
(2, 9, 129),
)
for dtype in (jnp.int32, jnp.uint32, jnp.float32)
)
def test_debug_print_vector(self, shape, dtype):
@functools.partial(
self.pallas_call,
out_shape=jax.ShapeDtypeStruct(shape, dtype),
)
def kernel(x_ref, o_ref):
pl.debug_print("{}", x_ref[...])
o_ref[...] = x_ref[...]
n = np.prod(shape)
x = jnp.arange(n, dtype=dtype).reshape(shape)
compiled_kernel = (
jax.jit(kernel)
.lower(x)
.compile({"xla_tpu_enable_log_recorder": "true"})
)
with jtu.capture_stderr() as get_output:
jax.block_until_ready(compiled_kernel(x))
output = get_output()
numbers = [
int(num)
for line in output.splitlines()
if (match := re.search(r"\{(.*)", line)) # extract contents after `{`
for num in re.findall(r"\d+", match.group(1))
]
# Check if the numbers in the output match the values generated by `arange`.
self.assertLen(numbers, n)
self.assertTrue(all(num == i for i, num in enumerate(numbers)))
if __name__ == '__main__':
absltest.main(testLoader=jtu.JaxTestLoader())
| PallasCallPrintTest |
python | huggingface__transformers | src/transformers/models/imagegpt/configuration_imagegpt.py | {
"start": 765,
"end": 6195
} | class ____(PreTrainedConfig):
"""
This is the configuration class to store the configuration of a [`ImageGPTModel`]. It is
used to instantiate a GPT-2 model according to the specified arguments, defining the model architecture.
Instantiating a configuration with the defaults will yield a similar configuration to that of the ImageGPT
[openai/imagegpt-small](https://huggingface.co/openai/imagegpt-small) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 512):
Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`ImageGPTModel`].
n_positions (`int`, *optional*, defaults to 32*32):
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048).
n_embd (`int`, *optional*, defaults to 512):
Dimensionality of the embeddings and hidden states.
n_layer (`int`, *optional*, defaults to 24):
Number of hidden layers in the Transformer encoder.
n_head (`int`, *optional*, defaults to 8):
Number of attention heads for each attention layer in the Transformer encoder.
n_inner (`int`, *optional*, defaults to None):
Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
activation_function (`str`, *optional*, defaults to `"quick_gelu"`):
Activation function (can be one of the activation functions defined in src/transformers/activations.py).
Defaults to "quick_gelu".
resid_pdrop (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
embd_pdrop (`int`, *optional*, defaults to 0.1):
The dropout ratio for the embeddings.
attn_pdrop (`float`, *optional*, defaults to 0.1):
The dropout ratio for the attention.
layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
The epsilon to use in the layer normalization layers.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
scale_attn_weights (`bool`, *optional*, defaults to `True`):
Scale attention weights by dividing by sqrt(hidden_size)..
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models).
scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
Whether to additionally scale attention weights by `1 / layer_idx + 1`.
reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
dot-product/softmax to float() when training with mixed precision.
Example:
```python
>>> from transformers import ImageGPTConfig, ImageGPTModel
>>> # Initializing a ImageGPT configuration
>>> configuration = ImageGPTConfig()
>>> # Initializing a model (with random weights) from the configuration
>>> model = ImageGPTModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "imagegpt"
keys_to_ignore_at_inference = ["past_key_values"]
attribute_map = {
"hidden_size": "n_embd",
"max_position_embeddings": "n_positions",
"num_attention_heads": "n_head",
"num_hidden_layers": "n_layer",
}
def __init__(
self,
vocab_size=512 + 1, # add one for start of sentence (sos) token
n_positions=32 * 32,
n_embd=512,
n_layer=24,
n_head=8,
n_inner=None,
activation_function="quick_gelu",
resid_pdrop=0.1,
embd_pdrop=0.1,
attn_pdrop=0.1,
layer_norm_epsilon=1e-5,
initializer_range=0.02,
scale_attn_weights=True,
use_cache=True,
tie_word_embeddings=False,
scale_attn_by_inverse_layer_idx=False,
reorder_and_upcast_attn=False,
**kwargs,
):
self.vocab_size = vocab_size
self.n_positions = n_positions
self.n_embd = n_embd
self.n_layer = n_layer
self.n_head = n_head
self.n_inner = n_inner
self.activation_function = activation_function
self.resid_pdrop = resid_pdrop
self.embd_pdrop = embd_pdrop
self.attn_pdrop = attn_pdrop
self.layer_norm_epsilon = layer_norm_epsilon
self.initializer_range = initializer_range
self.scale_attn_weights = scale_attn_weights
self.use_cache = use_cache
self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
self.reorder_and_upcast_attn = reorder_and_upcast_attn
self.tie_word_embeddings = tie_word_embeddings
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
__all__ = ["ImageGPTConfig"]
| ImageGPTConfig |
python | MongoEngine__mongoengine | tests/fields/test_lazy_reference_field.py | {
"start": 214,
"end": 12472
} | class ____(MongoDBTestCase):
def test_lazy_reference_config(self):
# Make sure ReferenceField only accepts a document class or a string
# with a document class name.
with pytest.raises(ValidationError):
LazyReferenceField(EmbeddedDocument)
def test___repr__(self):
class Animal(Document):
pass
class Ocurrence(Document):
animal = LazyReferenceField(Animal)
Animal.drop_collection()
Ocurrence.drop_collection()
animal = Animal()
oc = Ocurrence(animal=animal)
assert "LazyReference" in repr(oc.animal)
def test___getattr___unknown_attr_raises_attribute_error(self):
class Animal(Document):
pass
class Ocurrence(Document):
animal = LazyReferenceField(Animal)
Animal.drop_collection()
Ocurrence.drop_collection()
animal = Animal().save()
oc = Ocurrence(animal=animal)
with pytest.raises(AttributeError):
oc.animal.not_exist
def test_lazy_reference_simple(self):
class Animal(Document):
name = StringField()
tag = StringField()
class Ocurrence(Document):
person = StringField()
animal = LazyReferenceField(Animal)
Animal.drop_collection()
Ocurrence.drop_collection()
animal = Animal(name="Leopard", tag="heavy").save()
Ocurrence(person="test", animal=animal).save()
p = Ocurrence.objects.get()
assert isinstance(p.animal, LazyReference)
fetched_animal = p.animal.fetch()
assert fetched_animal == animal
# `fetch` keep cache on referenced document by default...
animal.tag = "not so heavy"
animal.save()
double_fetch = p.animal.fetch()
assert fetched_animal is double_fetch
assert double_fetch.tag == "heavy"
# ...unless specified otherwise
fetch_force = p.animal.fetch(force=True)
assert fetch_force is not fetched_animal
assert fetch_force.tag == "not so heavy"
def test_lazy_reference_fetch_invalid_ref(self):
class Animal(Document):
name = StringField()
tag = StringField()
class Ocurrence(Document):
person = StringField()
animal = LazyReferenceField(Animal)
Animal.drop_collection()
Ocurrence.drop_collection()
animal = Animal(name="Leopard", tag="heavy").save()
Ocurrence(person="test", animal=animal).save()
animal.delete()
p = Ocurrence.objects.get()
assert isinstance(p.animal, LazyReference)
with pytest.raises(DoesNotExist):
p.animal.fetch()
def test_lazy_reference_set(self):
class Animal(Document):
meta = {"allow_inheritance": True}
name = StringField()
tag = StringField()
class Ocurrence(Document):
person = StringField()
animal = LazyReferenceField(Animal)
Animal.drop_collection()
Ocurrence.drop_collection()
class SubAnimal(Animal):
nick = StringField()
animal = Animal(name="Leopard", tag="heavy").save()
sub_animal = SubAnimal(nick="doggo", name="dog").save()
for ref in (
animal,
animal.pk,
DBRef(animal._get_collection_name(), animal.pk),
LazyReference(Animal, animal.pk),
sub_animal,
sub_animal.pk,
DBRef(sub_animal._get_collection_name(), sub_animal.pk),
LazyReference(SubAnimal, sub_animal.pk),
):
p = Ocurrence(person="test", animal=ref).save()
p.reload()
assert isinstance(p.animal, LazyReference)
p.animal.fetch()
def test_lazy_reference_bad_set(self):
class Animal(Document):
name = StringField()
tag = StringField()
class Ocurrence(Document):
person = StringField()
animal = LazyReferenceField(Animal)
Animal.drop_collection()
Ocurrence.drop_collection()
class BadDoc(Document):
pass
animal = Animal(name="Leopard", tag="heavy").save()
baddoc = BadDoc().save()
for bad in (
42,
"foo",
baddoc,
DBRef(baddoc._get_collection_name(), animal.pk),
LazyReference(BadDoc, animal.pk),
):
with pytest.raises(ValidationError):
Ocurrence(person="test", animal=bad).save()
def test_lazy_reference_query_conversion(self):
"""Ensure that LazyReferenceFields can be queried using objects and values
of the type of the primary key of the referenced object.
"""
class Member(Document):
user_num = IntField(primary_key=True)
class BlogPost(Document):
title = StringField()
author = LazyReferenceField(Member, dbref=False)
Member.drop_collection()
BlogPost.drop_collection()
m1 = Member(user_num=1)
m1.save()
m2 = Member(user_num=2)
m2.save()
post1 = BlogPost(title="post 1", author=m1)
post1.save()
post2 = BlogPost(title="post 2", author=m2)
post2.save()
post = BlogPost.objects(author=m1).first()
assert post.id == post1.id
post = BlogPost.objects(author=m2).first()
assert post.id == post2.id
# Same thing by passing a LazyReference instance
post = BlogPost.objects(author=LazyReference(Member, m2.pk)).first()
assert post.id == post2.id
def test_lazy_reference_query_conversion_dbref(self):
"""Ensure that LazyReferenceFields can be queried using objects and values
of the type of the primary key of the referenced object.
"""
class Member(Document):
user_num = IntField(primary_key=True)
class BlogPost(Document):
title = StringField()
author = LazyReferenceField(Member, dbref=True)
Member.drop_collection()
BlogPost.drop_collection()
m1 = Member(user_num=1)
m1.save()
m2 = Member(user_num=2)
m2.save()
post1 = BlogPost(title="post 1", author=m1)
post1.save()
post2 = BlogPost(title="post 2", author=m2)
post2.save()
post = BlogPost.objects(author=m1).first()
assert post.id == post1.id
post = BlogPost.objects(author=m2).first()
assert post.id == post2.id
# Same thing by passing a LazyReference instance
post = BlogPost.objects(author=LazyReference(Member, m2.pk)).first()
assert post.id == post2.id
def test_lazy_reference_passthrough(self):
class Animal(Document):
name = StringField()
tag = StringField()
class Ocurrence(Document):
animal = LazyReferenceField(Animal, passthrough=False)
animal_passthrough = LazyReferenceField(Animal, passthrough=True)
Animal.drop_collection()
Ocurrence.drop_collection()
animal = Animal(name="Leopard", tag="heavy").save()
Ocurrence(animal=animal, animal_passthrough=animal).save()
p = Ocurrence.objects.get()
assert isinstance(p.animal, LazyReference)
with pytest.raises(KeyError):
p.animal["name"]
with pytest.raises(AttributeError):
p.animal.name
assert p.animal.pk == animal.pk
assert p.animal_passthrough.name == "Leopard"
assert p.animal_passthrough["name"] == "Leopard"
# Should not be able to access referenced document's methods
with pytest.raises(AttributeError):
p.animal.save
with pytest.raises(KeyError):
p.animal["save"]
def test_lazy_reference_not_set(self):
class Animal(Document):
name = StringField()
tag = StringField()
class Ocurrence(Document):
person = StringField()
animal = LazyReferenceField(Animal)
Animal.drop_collection()
Ocurrence.drop_collection()
Ocurrence(person="foo").save()
p = Ocurrence.objects.get()
assert p.animal is None
def test_lazy_reference_equality(self):
class Animal(Document):
name = StringField()
tag = StringField()
Animal.drop_collection()
animal = Animal(name="Leopard", tag="heavy").save()
animalref = LazyReference(Animal, animal.pk)
assert animal == animalref
assert animalref == animal
other_animalref = LazyReference(Animal, ObjectId("54495ad94c934721ede76f90"))
assert animal != other_animalref
assert other_animalref != animal
def test_lazy_reference_embedded(self):
class Animal(Document):
name = StringField()
tag = StringField()
class EmbeddedOcurrence(EmbeddedDocument):
in_list = ListField(LazyReferenceField(Animal))
direct = LazyReferenceField(Animal)
class Ocurrence(Document):
in_list = ListField(LazyReferenceField(Animal))
in_embedded = EmbeddedDocumentField(EmbeddedOcurrence)
direct = LazyReferenceField(Animal)
Animal.drop_collection()
Ocurrence.drop_collection()
animal1 = Animal(name="doggo").save()
animal2 = Animal(name="cheeta").save()
def check_fields_type(occ):
assert isinstance(occ.direct, LazyReference)
for elem in occ.in_list:
assert isinstance(elem, LazyReference)
assert isinstance(occ.in_embedded.direct, LazyReference)
for elem in occ.in_embedded.in_list:
assert isinstance(elem, LazyReference)
occ = Ocurrence(
in_list=[animal1, animal2],
in_embedded={"in_list": [animal1, animal2], "direct": animal1},
direct=animal1,
).save()
check_fields_type(occ)
occ.reload()
check_fields_type(occ)
occ.direct = animal1.id
occ.in_list = [animal1.id, animal2.id]
occ.in_embedded.direct = animal1.id
occ.in_embedded.in_list = [animal1.id, animal2.id]
check_fields_type(occ)
def test_lazy_reference_embedded_dereferencing(self):
# Test case for #2375
# -- Test documents
class Author(Document):
name = StringField()
class AuthorReference(EmbeddedDocument):
author = LazyReferenceField(Author)
class Book(Document):
authors = EmbeddedDocumentListField(AuthorReference)
# -- Cleanup
Author.drop_collection()
Book.drop_collection()
# -- Create test data
author_1 = Author(name="A1").save()
author_2 = Author(name="A2").save()
author_3 = Author(name="A3").save()
book = Book(
authors=[
AuthorReference(author=author_1),
AuthorReference(author=author_2),
AuthorReference(author=author_3),
]
).save()
with query_counter() as qc:
book = Book.objects.first()
# Accessing the list must not trigger dereferencing.
book.authors
assert qc == 1
for ref in book.authors:
with pytest.raises(AttributeError):
ref["author"].name
assert isinstance(ref.author, LazyReference)
assert isinstance(ref.author.id, ObjectId)
def test_lazy_reference_in_list_with_changed_element(self):
class Animal(Document):
name = StringField()
tag = StringField()
class Ocurrence(Document):
in_list = ListField(LazyReferenceField(Animal))
Animal.drop_collection()
Ocurrence.drop_collection()
animal1 = Animal(name="doggo").save()
animal1.tag = "blue"
occ = Ocurrence(in_list=[animal1]).save()
animal1.save()
assert isinstance(occ.in_list[0], LazyReference)
assert occ.in_list[0].pk == animal1.pk
| TestLazyReferenceField |
python | skorch-dev__skorch | skorch/helper.py | {
"start": 701,
"end": 4359
} | class ____(dict):
"""Wrapper for Python dict that makes it sliceable across values.
Use this if your input data is a dictionary and you have problems
with sklearn not being able to slice it. Wrap your dict with
SliceDict and it should usually work.
Note:
* SliceDict cannot be indexed by integers, if you want one row,
say row 3, use `[3:4]`.
* SliceDict accepts numpy arrays and torch tensors as values.
Examples
--------
>>> X = {'key0': val0, 'key1': val1}
>>> search = GridSearchCV(net, params, ...)
>>> search.fit(X, y) # raises error
>>> Xs = SliceDict(key0=val0, key1=val1) # or Xs = SliceDict(**X)
>>> search.fit(Xs, y) # works
"""
def __init__(self, **kwargs):
lengths = [value.shape[0] for value in kwargs.values()]
lengths_set = set(lengths)
if lengths_set and (len(lengths_set) != 1):
raise ValueError(
"Initialized with items of different lengths: {}"
"".format(', '.join(map(str, sorted(lengths_set)))))
if not lengths:
self._len = 0
else:
self._len = lengths[0]
super().__init__(**kwargs)
def __len__(self):
return self._len
def __getitem__(self, sl):
if isinstance(sl, int):
# Indexing with integers is not well-defined because that
# recudes the dimension of arrays by one, messing up
# lengths and shapes.
raise ValueError("SliceDict cannot be indexed by integers.")
if isinstance(sl, str):
return super().__getitem__(sl)
return type(self)(**{k: v[sl] for k, v in self.items()})
def __setitem__(self, key, value):
if not isinstance(key, str):
raise TypeError("Key must be str, not {}.".format(type(key)))
length = value.shape[0]
if not self.keys():
self._len = length
if self._len != length:
raise ValueError(
"Cannot set array with shape[0] != {}"
"".format(self._len))
super().__setitem__(key, value)
def update(self, kwargs):
for key, value in kwargs.items():
self.__setitem__(key, value)
def __repr__(self):
out = super().__repr__()
return "SliceDict(**{})".format(out)
@property
def shape(self):
return (self._len,)
def copy(self):
return type(self)(**self)
def fromkeys(self, *args, **kwargs):
"""fromkeys method makes no sense with SliceDict and is thus not
supported."""
raise TypeError("SliceDict does not support fromkeys.")
def __eq__(self, other):
if self.keys() != other.keys():
return False
for key, val in self.items():
val_other = other[key]
# torch tensors
if is_torch_data_type(val):
if not is_torch_data_type(val_other):
return False
if not (val == val_other).all():
return False
continue
# numpy arrays
if isinstance(val, np.ndarray):
if not isinstance(val_other, np.ndarray):
return False
if not (val == val_other).all():
return False
continue
# rest
if val != val_other:
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
# This class must be an instance of Sequence and have an ndim
# attribute because sklearn will test this.
| SliceDict |
python | ansible__ansible | lib/ansible/modules/unarchive.py | {
"start": 30160,
"end": 37777
} | class ____(object):
def __init__(self, src, b_dest, file_args, module):
self.src = src
self.b_dest = b_dest
self.file_args = file_args
self.opts = module.params['extra_opts']
self.module = module
if self.module.check_mode:
self.module.exit_json(skipped=True, msg="remote module (%s) does not support check mode when using gtar" % self.module._name)
self.excludes = [path.rstrip('/') for path in self.module.params['exclude']]
self.include_files = self.module.params['include']
self.cmd_path = None
self.tar_type = None
self.zipflag = '-z'
self._files_in_archive = []
def _get_tar_type(self):
cmd = [self.cmd_path, '--version']
(rc, out, err) = self.module.run_command(cmd)
tar_type = None
if out.startswith('bsdtar'):
tar_type = 'bsd'
elif out.startswith('tar') and 'GNU' in out:
tar_type = 'gnu'
return tar_type
@property
def files_in_archive(self):
if self._files_in_archive:
return self._files_in_archive
cmd = [self.cmd_path, '--list', '-C', self.b_dest]
if self.zipflag:
cmd.append(self.zipflag)
if self.opts:
cmd.extend(['--show-transformed-names'] + self.opts)
if self.excludes:
cmd.extend(['--exclude=' + f for f in self.excludes])
cmd.extend(['-f', self.src])
if self.include_files:
cmd.extend(self.include_files)
locale = get_best_parsable_locale(self.module)
rc, out, err = self.module.run_command(cmd, cwd=self.b_dest, environ_update=dict(LANG=locale, LC_ALL=locale, LC_MESSAGES=locale, LANGUAGE=locale))
if rc != 0:
self.module.debug(err)
raise UnarchiveError('Unable to list files in the archive: %s' % err)
for filename in out.splitlines():
# Compensate for locale-related problems in gtar output (octal unicode representation) #11348
# filename = filename.decode('string_escape')
filename = to_native(codecs.escape_decode(filename)[0])
# We don't allow absolute filenames. If the user wants to unarchive rooted in "/"
# they need to use "dest: '/'". This follows the defaults for gtar, pax, etc.
# Allowing absolute filenames here also causes bugs: https://github.com/ansible/ansible/issues/21397
if filename.startswith('/'):
filename = filename[1:]
exclude_flag = False
if self.excludes:
for exclude in self.excludes:
if fnmatch.fnmatch(filename, exclude):
exclude_flag = True
break
if not exclude_flag:
self._files_in_archive.append(to_native(filename))
return self._files_in_archive
def is_unarchived(self):
cmd = [self.cmd_path, '--diff', '-C', self.b_dest]
if self.zipflag:
cmd.append(self.zipflag)
if self.opts:
cmd.extend(['--show-transformed-names'] + self.opts)
if self.file_args['owner']:
cmd.append('--owner=' + quote(self.file_args['owner']))
if self.file_args['group']:
cmd.append('--group=' + quote(self.file_args['group']))
if self.module.params['keep_newer']:
cmd.append('--keep-newer-files')
if self.excludes:
cmd.extend(['--exclude=' + f for f in self.excludes])
cmd.extend(['-f', self.src])
if self.include_files:
cmd.extend(self.include_files)
locale = get_best_parsable_locale(self.module)
rc, out, err = self.module.run_command(cmd, cwd=self.b_dest, environ_update=dict(LANG=locale, LC_ALL=locale, LC_MESSAGES=locale, LANGUAGE=locale))
# Check whether the differences are in something that we're
# setting anyway
# What is different
unarchived = True
old_out = out
out = ''
run_uid = os.getuid()
# When unarchiving as a user, or when owner/group/mode is supplied --diff is insufficient
# Only way to be sure is to check request with what is on disk (as we do for zip)
# Leave this up to set_fs_attributes_if_different() instead of inducing a (false) change
for line in old_out.splitlines() + err.splitlines():
# FIXME: Remove the bogus lines from error-output as well !
# Ignore bogus errors on empty filenames (when using --split-component)
if EMPTY_FILE_RE.search(line):
continue
if run_uid == 0 and not self.file_args['owner'] and OWNER_DIFF_RE.search(line):
out += line + '\n'
if run_uid == 0 and not self.file_args['group'] and GROUP_DIFF_RE.search(line):
out += line + '\n'
if not self.file_args['mode'] and MODE_DIFF_RE.search(line):
out += line + '\n'
differ_regexes = [
MOD_TIME_DIFF_RE, MISSING_FILE_RE, INVALID_OWNER_RE,
INVALID_GROUP_RE, SYMLINK_DIFF_RE, CONTENT_DIFF_RE,
SIZE_DIFF_RE
]
for regex in differ_regexes:
if regex.search(line):
out += line + '\n'
if out:
unarchived = False
return dict(unarchived=unarchived, rc=rc, out=out, err=err, cmd=cmd)
def unarchive(self):
cmd = [self.cmd_path, '--extract', '-C', self.b_dest]
if self.zipflag:
cmd.append(self.zipflag)
if self.opts:
cmd.extend(['--show-transformed-names'] + self.opts)
if self.file_args['owner']:
cmd.append('--owner=' + quote(self.file_args['owner']))
if self.file_args['group']:
cmd.append('--group=' + quote(self.file_args['group']))
if self.module.params['keep_newer']:
cmd.append('--keep-newer-files')
if self.excludes:
cmd.extend(['--exclude=' + f for f in self.excludes])
cmd.extend(['-f', self.src])
if self.include_files:
cmd.extend(self.include_files)
locale = get_best_parsable_locale(self.module)
rc, out, err = self.module.run_command(cmd, cwd=self.b_dest, environ_update=dict(LANG=locale, LC_ALL=locale, LC_MESSAGES=locale, LANGUAGE=locale))
return dict(cmd=cmd, rc=rc, out=out, err=err)
def can_handle_archive(self):
# Prefer gtar (GNU tar) as it supports the compression options -z, -j and -J
try:
self.cmd_path = get_bin_path('gtar')
except ValueError:
# Fallback to tar
try:
self.cmd_path = get_bin_path('tar')
except ValueError:
return False, "Unable to find required 'gtar' or 'tar' binary in the path"
self.tar_type = self._get_tar_type()
if self.tar_type != 'gnu':
return False, 'Command "%s" detected as tar type %s. GNU tar required.' % (self.cmd_path, self.tar_type)
try:
if self.files_in_archive:
return True, None
except UnarchiveError as e:
return False, 'Command "%s" could not handle archive: %s' % (self.cmd_path, to_native(e))
# Errors and no files in archive assume that we weren't able to
# properly unarchive it
return False, 'Command "%s" found no files in archive. Empty archive files are not supported.' % self.cmd_path
# Class to handle tar files that aren't compressed
| TgzArchive |
python | realpython__materials | python-self-type/accounts_future_module.py | {
"start": 97,
"end": 651
} | class ____:
account_number: int
balance: float
def display_balance(self) -> BankAccount:
print(f"Account Number: {self.account_number}")
print(f"Balance: ${self.balance:,.2f}\n")
return self
def deposit(self, amount: float) -> BankAccount:
self.balance += amount
return self
def withdraw(self, amount: float) -> BankAccount:
if self.balance >= amount:
self.balance -= amount
else:
print("Insufficient balance")
return self
@dataclass
| BankAccount |
python | lazyprogrammer__machine_learning_examples | hmm_class/hmm_classifier.py | {
"start": 626,
"end": 3121
} | class ____:
def __init__(self):
pass
def fit(self, X, Y, V):
K = len(set(Y)) # number of classes - assume 0..K-1
N = len(Y)
self.models = []
self.priors = []
for k in range(K):
# gather all the training data for this class
thisX = [x for x, y in zip(X, Y) if y == k]
C = len(thisX)
self.priors.append(np.log(C) - np.log(N))
hmm = HMM(5)
hmm.fit(thisX, V=V, print_period=1, learning_rate=1e-2, max_iter=80)
self.models.append(hmm)
def score(self, X, Y):
N = len(Y)
correct = 0
for x, y in zip(X, Y):
lls = [hmm.log_likelihood(x) + prior for hmm, prior in zip(self.models, self.priors)]
p = np.argmax(lls)
if p == y:
correct += 1
return float(correct) / N
# def remove_punctuation(s):
# return s.translate(None, string.punctuation)
def get_tags(s):
tuples = pos_tag(word_tokenize(s))
return [y for x, y in tuples]
def get_data():
word2idx = {}
current_idx = 0
X = []
Y = []
for fn, label in zip(('robert_frost.txt', 'edgar_allan_poe.txt'), (0, 1)):
count = 0
for line in open(fn):
line = line.rstrip()
if line:
print(line)
# tokens = remove_punctuation(line.lower()).split()
tokens = get_tags(line)
if len(tokens) > 1:
# scan doesn't work nice here, technically could fix...
for token in tokens:
if token not in word2idx:
word2idx[token] = current_idx
current_idx += 1
sequence = np.array([word2idx[w] for w in tokens])
X.append(sequence)
Y.append(label)
count += 1
print(count)
if count >= 50:
break
print("Vocabulary:", word2idx.keys())
return X, Y, current_idx
def main():
X, Y, V = get_data()
print("len(X):", len(X))
print("Vocabulary size:", V)
X, Y = shuffle(X, Y)
N = 20 # number to test
Xtrain, Ytrain = X[:-N], Y[:-N]
Xtest, Ytest = X[-N:], Y[-N:]
model = HMMClassifier()
model.fit(Xtrain, Ytrain, V)
print("Score:", model.score(Xtest, Ytest))
if __name__ == '__main__':
main()
| HMMClassifier |
python | getsentry__sentry | src/sentry/overwatch/endpoints/overwatch_rpc.py | {
"start": 5971,
"end": 7545
} | class ____(Endpoint):
"""
Get Sentry organization IDs for a GitHub repository.
GET /prevent/pr-review/github/sentry-org?repoId={repoId}
"""
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.CODECOV
authentication_classes = (OverwatchRpcSignatureAuthentication,)
permission_classes = ()
enforce_rate_limit = False
def get(self, request: Request) -> Response:
if not request.auth or not isinstance(
request.successful_authenticator, OverwatchRpcSignatureAuthentication
):
raise PermissionDenied
repo_id = request.GET.get("repoId")
if not repo_id:
raise ParseError("Missing required query parameter: repoId")
organization_ids = Repository.objects.filter(
external_id=repo_id,
provider="integrations:github",
status=ObjectStatus.ACTIVE,
).values_list("organization_id", flat=True)
organizations = Organization.objects.filter(id__in=organization_ids)
# Return all orgs with their consent status for AI features
return Response(
data={
"organizations": [
{
"org_id": org.id,
"org_slug": org.slug,
"org_name": org.name,
"has_consent": _can_use_prevent_ai_features(org),
}
for org in organizations
]
}
)
| PreventPrReviewSentryOrgEndpoint |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_pinned_searches.py | {
"start": 5138,
"end": 7486
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-pinned-searches"
method = "delete"
@cached_property
def member(self):
user = self.create_user("test@test.com")
self.create_member(organization=self.organization, user=user)
return user
def get_response(self, *args, **params):
return super().get_response(*((self.organization.slug,) + args), **params)
def test(self) -> None:
saved_search = SavedSearch.objects.create(
organization=self.organization,
owner_id=self.member.id,
type=SearchType.ISSUE.value,
query="wat",
visibility=Visibility.OWNER_PINNED,
)
other_saved_search = SavedSearch.objects.create(
organization=self.organization,
owner_id=self.user.id,
type=SearchType.ISSUE.value,
query="wat",
visibility=Visibility.OWNER_PINNED,
)
self.login_as(self.member)
self.get_success_response(type=saved_search.type, status_code=204)
assert not SavedSearch.objects.filter(id=saved_search.id).exists()
assert SavedSearch.objects.filter(id=other_saved_search.id).exists()
# Test calling multiple times works ok, doesn't cause other rows to
# delete
self.get_success_response(type=saved_search.type, status_code=204)
assert SavedSearch.objects.filter(id=other_saved_search.id).exists()
def test_views_deleted(self) -> None:
self.login_as(self.member)
saved_search = SavedSearch.objects.create(
organization=self.organization,
owner_id=self.member.id,
type=SearchType.ISSUE.value,
query="wat",
visibility=Visibility.OWNER_PINNED,
)
self.get_success_response(type=saved_search.type, status_code=204)
assert not SavedSearch.objects.filter(id=saved_search.id).exists()
assert not GroupSearchView.objects.filter(
organization=self.organization, user_id=self.member.id
).exists()
def test_invalid_type(self) -> None:
self.login_as(self.member)
resp = self.get_response(type=55)
assert resp.status_code == 400
assert "Invalid input for `type`" in resp.data["detail"]
| DeleteOrganizationPinnedSearchTest |
python | explosion__spaCy | spacy/lang/ca/__init__.py | {
"start": 412,
"end": 700
} | class ____(BaseDefaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
infixes = TOKENIZER_INFIXES
suffixes = TOKENIZER_SUFFIXES
prefixes = TOKENIZER_PREFIXES
stop_words = STOP_WORDS
lex_attr_getters = LEX_ATTRS
syntax_iterators = SYNTAX_ITERATORS
| CatalanDefaults |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/from_tensor_slices_test.py | {
"start": 17520,
"end": 18679
} | class ____(
test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
dataset_range=[10, 100],
repetitions=[1, 3],
seed=[None, 19],
reshuffle_each_iteration=[True, False])))
def testGlobalShuffleTensorSlicesDataset(
self,
dataset_range: int,
repetitions: int,
seed: Optional[int],
reshuffle_each_iteration: bool):
dataset = dataset_ops.Dataset.from_tensor_slices(list(range(dataset_range)))
if repetitions > 1:
dataset = dataset.repeat(repetitions)
dataset = global_shuffle_op._global_shuffle(
dataset, seed=seed, reshuffle_each_iteration=reshuffle_each_iteration)
dataset_output = self.getDatasetOutput(
dataset, requires_initialization=True)
expected = list(range(dataset_range)) * repetitions
self.assertCountEqual(dataset_output, expected)
self.assertNotEqual(dataset_output, expected)
self.assertLen(expected, self.evaluate(dataset.cardinality()))
| FromTensorSlicesGlobalShuffleTest |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 10258,
"end": 10652
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layers = torch.nn.ModuleDict(
{
"0": torch.nn.Linear(10, 10),
}
)
def __getitem__(self, key: str) -> torch.nn.Module:
return self.layers[key]
def forward(self, x):
x = self["0"](x)
return x
| CustomGetItemModuleDict |
python | keras-team__keras | keras/src/optimizers/schedules/learning_rate_schedule_test.py | {
"start": 12408,
"end": 15392
} | class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(
schedules.CosineDecayRestarts(
initial_learning_rate=0.05,
first_decay_steps=10,
alpha=0.1,
t_mul=3.0,
m_mul=4.0,
name="my_cdr",
)
)
def np_cosine_decay_restarts(
self, step, decay_steps, t_mul=2.0, m_mul=1.0, alpha=0.0
):
fac = 1.0
while step >= decay_steps:
step -= decay_steps
decay_steps *= t_mul
fac *= m_mul
completed_fraction = step / decay_steps
decay = fac * 0.5 * (1.0 + math.cos(math.pi * completed_fraction))
return (1.0 - alpha) * decay + alpha
def test_decay(self):
num_training_steps = 1000
initial_lr = 1.0
for step in range(0, 1500, 250):
decayed_lr = schedules.CosineDecayRestarts(
initial_lr, num_training_steps
)
expected = self.np_cosine_decay_restarts(step, num_training_steps)
self.assertAllClose(decayed_lr(step), expected, 1e-6)
def test_float64(self):
num_training_steps = 1000
initial_lr = np.float64(1.0)
for step in range(0, 1500, 250):
decayed_lr = schedules.CosineDecayRestarts(
initial_lr, num_training_steps
)
expected = self.np_cosine_decay_restarts(step, num_training_steps)
self.assertAllClose(decayed_lr(step), expected, 1e-6)
def test_alpha(self):
num_training_steps = 1000
initial_lr = 1.0
alpha = 0.1
for step in range(0, 1500, 250):
decayed_lr = schedules.CosineDecayRestarts(
initial_lr, num_training_steps, alpha=alpha
)
expected = self.np_cosine_decay_restarts(
step, num_training_steps, alpha=alpha
)
self.assertAllClose(decayed_lr(step), expected, 1e-6)
def test_mmul(self):
num_training_steps = 1000
initial_lr = 1.0
m_mul = 0.9
for step in range(0, 1500, 250):
decayed_lr = schedules.CosineDecayRestarts(
initial_lr, num_training_steps, m_mul=m_mul
)
expected = self.np_cosine_decay_restarts(
step, num_training_steps, m_mul=m_mul
)
self.assertAllClose(decayed_lr(step), expected, 1e-6)
def test_tmul(self):
num_training_steps = 1000
initial_lr = 1.0
t_mul = 1.0
for step in range(0, 1500, 250):
decayed_lr = schedules.CosineDecayRestarts(
initial_lr, num_training_steps, t_mul=t_mul
)
expected = self.np_cosine_decay_restarts(
step, num_training_steps, t_mul=t_mul
)
self.assertAllClose(decayed_lr(step), expected, 1e-6)
| CosineDecayRestartsTest |
python | pypa__pipenv | pipenv/vendor/packaging/version.py | {
"start": 4509,
"end": 16212
} | class ____(_BaseVersion):
"""This class abstracts handling of a project's versions.
A :class:`Version` instance is comparison aware and can be compared and
sorted using the standard Python interfaces.
>>> v1 = Version("1.0a5")
>>> v2 = Version("1.0")
>>> v1
<Version('1.0a5')>
>>> v2
<Version('1.0')>
>>> v1 < v2
True
>>> v1 == v2
False
>>> v1 > v2
False
>>> v1 >= v2
False
>>> v1 <= v2
True
"""
_regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
_key: CmpKey
def __init__(self, version: str) -> None:
"""Initialize a Version object.
:param version:
The string representation of a version which will be parsed and normalized
before use.
:raises InvalidVersion:
If the ``version`` does not conform to PEP 440 in any way then this
exception will be raised.
"""
# Validate the version and parse it into pieces
match = self._regex.search(version)
if not match:
raise InvalidVersion(f"Invalid version: '{version}'")
# Store the parsed out pieces of the version
self._version = _Version(
epoch=int(match.group("epoch")) if match.group("epoch") else 0,
release=tuple(int(i) for i in match.group("release").split(".")),
pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
post=_parse_letter_version(
match.group("post_l"), match.group("post_n1") or match.group("post_n2")
),
dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
local=_parse_local_version(match.group("local")),
)
# Generate a key which will be used for sorting
self._key = _cmpkey(
self._version.epoch,
self._version.release,
self._version.pre,
self._version.post,
self._version.dev,
self._version.local,
)
def __repr__(self) -> str:
"""A representation of the Version that shows all internal state.
>>> Version('1.0.0')
<Version('1.0.0')>
"""
return f"<Version('{self}')>"
def __str__(self) -> str:
"""A string representation of the version that can be rounded-tripped.
>>> str(Version("1.0a5"))
'1.0a5'
"""
parts = []
# Epoch
if self.epoch != 0:
parts.append(f"{self.epoch}!")
# Release segment
parts.append(".".join(str(x) for x in self.release))
# Pre-release
if self.pre is not None:
parts.append("".join(str(x) for x in self.pre))
# Post-release
if self.post is not None:
parts.append(f".post{self.post}")
# Development release
if self.dev is not None:
parts.append(f".dev{self.dev}")
# Local version segment
if self.local is not None:
parts.append(f"+{self.local}")
return "".join(parts)
@property
def epoch(self) -> int:
"""The epoch of the version.
>>> Version("2.0.0").epoch
0
>>> Version("1!2.0.0").epoch
1
"""
return self._version.epoch
@property
def release(self) -> tuple[int, ...]:
"""The components of the "release" segment of the version.
>>> Version("1.2.3").release
(1, 2, 3)
>>> Version("2.0.0").release
(2, 0, 0)
>>> Version("1!2.0.0.post0").release
(2, 0, 0)
Includes trailing zeroes but not the epoch or any pre-release / development /
post-release suffixes.
"""
return self._version.release
@property
def pre(self) -> tuple[str, int] | None:
"""The pre-release segment of the version.
>>> print(Version("1.2.3").pre)
None
>>> Version("1.2.3a1").pre
('a', 1)
>>> Version("1.2.3b1").pre
('b', 1)
>>> Version("1.2.3rc1").pre
('rc', 1)
"""
return self._version.pre
@property
def post(self) -> int | None:
"""The post-release number of the version.
>>> print(Version("1.2.3").post)
None
>>> Version("1.2.3.post1").post
1
"""
return self._version.post[1] if self._version.post else None
@property
def dev(self) -> int | None:
"""The development number of the version.
>>> print(Version("1.2.3").dev)
None
>>> Version("1.2.3.dev1").dev
1
"""
return self._version.dev[1] if self._version.dev else None
@property
def local(self) -> str | None:
"""The local version segment of the version.
>>> print(Version("1.2.3").local)
None
>>> Version("1.2.3+abc").local
'abc'
"""
if self._version.local:
return ".".join(str(x) for x in self._version.local)
else:
return None
@property
def public(self) -> str:
"""The public portion of the version.
>>> Version("1.2.3").public
'1.2.3'
>>> Version("1.2.3+abc").public
'1.2.3'
>>> Version("1.2.3+abc.dev1").public
'1.2.3'
"""
return str(self).split("+", 1)[0]
@property
def base_version(self) -> str:
"""The "base version" of the version.
>>> Version("1.2.3").base_version
'1.2.3'
>>> Version("1.2.3+abc").base_version
'1.2.3'
>>> Version("1!1.2.3+abc.dev1").base_version
'1!1.2.3'
The "base version" is the public version of the project without any pre or post
release markers.
"""
parts = []
# Epoch
if self.epoch != 0:
parts.append(f"{self.epoch}!")
# Release segment
parts.append(".".join(str(x) for x in self.release))
return "".join(parts)
@property
def is_prerelease(self) -> bool:
"""Whether this version is a pre-release.
>>> Version("1.2.3").is_prerelease
False
>>> Version("1.2.3a1").is_prerelease
True
>>> Version("1.2.3b1").is_prerelease
True
>>> Version("1.2.3rc1").is_prerelease
True
>>> Version("1.2.3dev1").is_prerelease
True
"""
return self.dev is not None or self.pre is not None
@property
def is_postrelease(self) -> bool:
"""Whether this version is a post-release.
>>> Version("1.2.3").is_postrelease
False
>>> Version("1.2.3.post1").is_postrelease
True
"""
return self.post is not None
@property
def is_devrelease(self) -> bool:
"""Whether this version is a development release.
>>> Version("1.2.3").is_devrelease
False
>>> Version("1.2.3.dev1").is_devrelease
True
"""
return self.dev is not None
@property
def major(self) -> int:
"""The first item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").major
1
"""
return self.release[0] if len(self.release) >= 1 else 0
@property
def minor(self) -> int:
"""The second item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").minor
2
>>> Version("1").minor
0
"""
return self.release[1] if len(self.release) >= 2 else 0
@property
def micro(self) -> int:
"""The third item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").micro
3
>>> Version("1").micro
0
"""
return self.release[2] if len(self.release) >= 3 else 0
def _parse_letter_version(
letter: str | None, number: str | bytes | SupportsInt | None
) -> tuple[str, int] | None:
if letter:
# We consider there to be an implicit 0 in a pre-release if there is
# not a numeral associated with it.
if number is None:
number = 0
# We normalize any letters to their lower case form
letter = letter.lower()
# We consider some words to be alternate spellings of other words and
# in those cases we want to normalize the spellings to our preferred
# spelling.
if letter == "alpha":
letter = "a"
elif letter == "beta":
letter = "b"
elif letter in ["c", "pre", "preview"]:
letter = "rc"
elif letter in ["rev", "r"]:
letter = "post"
return letter, int(number)
if not letter and number:
# We assume if we are given a number, but we are not given a letter
# then this is using the implicit post release syntax (e.g. 1.0-1)
letter = "post"
return letter, int(number)
return None
_local_version_separators = re.compile(r"[\._-]")
def _parse_local_version(local: str | None) -> LocalType | None:
"""
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
"""
if local is not None:
return tuple(
part.lower() if not part.isdigit() else int(part)
for part in _local_version_separators.split(local)
)
return None
def _cmpkey(
epoch: int,
release: tuple[int, ...],
pre: tuple[str, int] | None,
post: tuple[str, int] | None,
dev: tuple[str, int] | None,
local: LocalType | None,
) -> CmpKey:
# When we compare a release version, we want to compare it with all of the
# trailing zeros removed. So we'll use a reverse the list, drop all the now
# leading zeros until we come to something non zero, then take the rest
# re-reverse it back into the correct order and make it a tuple and use
# that for our sorting key.
_release = tuple(
reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
)
# We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
# We'll do this by abusing the pre segment, but we _only_ want to do this
# if there is not a pre or a post segment. If we have one of those then
# the normal sorting rules will handle this case correctly.
if pre is None and post is None and dev is not None:
_pre: CmpPrePostDevType = NegativeInfinity
# Versions without a pre-release (except as noted above) should sort after
# those with one.
elif pre is None:
_pre = Infinity
else:
_pre = pre
# Versions without a post segment should sort before those with one.
if post is None:
_post: CmpPrePostDevType = NegativeInfinity
else:
_post = post
# Versions without a development segment should sort after those with one.
if dev is None:
_dev: CmpPrePostDevType = Infinity
else:
_dev = dev
if local is None:
# Versions without a local segment should sort before those with one.
_local: CmpLocalType = NegativeInfinity
else:
# Versions with a local segment need that segment parsed to implement
# the sorting rules in PEP440.
# - Alpha numeric segments sort before numeric segments
# - Alpha numeric segments sort lexicographically
# - Numeric segments sort numerically
# - Shorter versions sort before longer versions when the prefixes
# match exactly
_local = tuple(
(i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
)
return epoch, _release, _pre, _post, _dev, _local
| Version |
python | pypa__pipenv | pipenv/vendor/pexpect/replwrap.py | {
"start": 310,
"end": 5976
} | class ____(object):
"""Wrapper for a REPL.
:param cmd_or_spawn: This can either be an instance of :class:`pexpect.spawn`
in which a REPL has already been started, or a str command to start a new
REPL process.
:param str orig_prompt: The prompt to expect at first.
:param str prompt_change: A command to change the prompt to something more
unique. If this is ``None``, the prompt will not be changed. This will
be formatted with the new and continuation prompts as positional
parameters, so you can use ``{}`` style formatting to insert them into
the command.
:param str new_prompt: The more unique prompt to expect after the change.
:param str extra_init_cmd: Commands to do extra initialisation, such as
disabling pagers.
"""
def __init__(self, cmd_or_spawn, orig_prompt, prompt_change,
new_prompt=PEXPECT_PROMPT,
continuation_prompt=PEXPECT_CONTINUATION_PROMPT,
extra_init_cmd=None):
if isinstance(cmd_or_spawn, basestring):
self.child = pexpect.spawn(cmd_or_spawn, echo=False, encoding='utf-8')
else:
self.child = cmd_or_spawn
if self.child.echo:
# Existing spawn instance has echo enabled, disable it
# to prevent our input from being repeated to output.
self.child.setecho(False)
self.child.waitnoecho()
if prompt_change is None:
self.prompt = orig_prompt
else:
self.set_prompt(orig_prompt,
prompt_change.format(new_prompt, continuation_prompt))
self.prompt = new_prompt
self.continuation_prompt = continuation_prompt
self._expect_prompt()
if extra_init_cmd is not None:
self.run_command(extra_init_cmd)
def set_prompt(self, orig_prompt, prompt_change):
self.child.expect(orig_prompt)
self.child.sendline(prompt_change)
def _expect_prompt(self, timeout=-1, async_=False):
return self.child.expect_exact([self.prompt, self.continuation_prompt],
timeout=timeout, async_=async_)
def run_command(self, command, timeout=-1, async_=False):
"""Send a command to the REPL, wait for and return output.
:param str command: The command to send. Trailing newlines are not needed.
This should be a complete block of input that will trigger execution;
if a continuation prompt is found after sending input, :exc:`ValueError`
will be raised.
:param int timeout: How long to wait for the next prompt. -1 means the
default from the :class:`pexpect.spawn` object (default 30 seconds).
None means to wait indefinitely.
:param bool async_: On Python 3.4, or Python 3.3 with asyncio
installed, passing ``async_=True`` will make this return an
:mod:`asyncio` Future, which you can yield from to get the same
result that this method would normally give directly.
"""
# Split up multiline commands and feed them in bit-by-bit
cmdlines = command.splitlines()
# splitlines ignores trailing newlines - add it back in manually
if command.endswith('\n'):
cmdlines.append('')
if not cmdlines:
raise ValueError("No command was given")
if async_:
from ._async import repl_run_command_async
return repl_run_command_async(self, cmdlines, timeout)
res = []
self.child.sendline(cmdlines[0])
for line in cmdlines[1:]:
self._expect_prompt(timeout=timeout)
res.append(self.child.before)
self.child.sendline(line)
# Command was fully submitted, now wait for the next prompt
if self._expect_prompt(timeout=timeout) == 1:
# We got the continuation prompt - command was incomplete
self.child.kill(signal.SIGINT)
self._expect_prompt(timeout=1)
raise ValueError("Continuation prompt found - input was incomplete:\n"
+ command)
return u''.join(res + [self.child.before])
def python(command=sys.executable):
"""Start a Python shell and return a :class:`REPLWrapper` object."""
return REPLWrapper(command, u">>> ", u"import sys; sys.ps1={0!r}; sys.ps2={1!r}")
def _repl_sh(command, args, non_printable_insert):
child = pexpect.spawn(command, args, echo=False, encoding='utf-8')
# If the user runs 'env', the value of PS1 will be in the output. To avoid
# replwrap seeing that as the next prompt, we'll embed the marker characters
# for invisible characters in the prompt; these show up when inspecting the
# environment variable, but not when bash displays the prompt.
ps1 = PEXPECT_PROMPT[:5] + non_printable_insert + PEXPECT_PROMPT[5:]
ps2 = PEXPECT_CONTINUATION_PROMPT[:5] + non_printable_insert + PEXPECT_CONTINUATION_PROMPT[5:]
prompt_change = u"PS1='{0}' PS2='{1}' PROMPT_COMMAND=''".format(ps1, ps2)
return REPLWrapper(child, u'\\$', prompt_change,
extra_init_cmd="export PAGER=cat")
def bash(command="bash"):
"""Start a bash shell and return a :class:`REPLWrapper` object."""
bashrc = os.path.join(os.path.dirname(__file__), 'bashrc.sh')
return _repl_sh(command, ['--rcfile', bashrc], non_printable_insert='\\[\\]')
def zsh(command="zsh", args=("--no-rcs", "-V", "+Z")):
"""Start a zsh shell and return a :class:`REPLWrapper` object."""
return _repl_sh(command, list(args), non_printable_insert='%(!..)')
| REPLWrapper |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/source.py | {
"start": 5231,
"end": 5720
} | class ____(BraintreeExtractor):
"""
Extractor for Plans stream.
It parses output XML and finds all `Plan` occurrences in it.
"""
def extract_records(
self,
response: requests.Response,
) -> List[Record]:
data = XmlUtil.dict_from_xml(response.text)
plans = self._extract_as_array(data, "plans")
return [Plan(**self._get_json_from_resource(BPlan(None, plan))).dict(exclude_unset=True) for plan in plans]
@dataclass
| PlanExtractor |
python | spyder-ide__spyder | spyder/widgets/dependencies.py | {
"start": 3549,
"end": 7443
} | class ____(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
# Widgets
note1 = _(
"Optional modules are not required to run Spyder but enhance "
"its functions."
)
note2 = _(
"New dependencies or changed ones will be correctly detected only "
"after Spyder is restarted."
)
notes_vmargin = "0.4em" if WIN else "0.3em"
label = QLabel(
(
"<style>"
"ul, li {{margin-left: -15px}}"
"li {{margin-bottom: {}}}"
"</style>"
"<ul>"
"<li>{}</li>"
"<li>{}</li>"
"</ul>"
).format(notes_vmargin, note1, note2)
)
self.treewidget = DependenciesTreeWidget(self)
self.copy_btn = QPushButton(_("Copy to clipboard"))
ok_btn = SpyderDialogButtonBox(QDialogButtonBox.Ok)
# Widget setup
self.setWindowTitle(
_("Dependencies for Spyder {}").format(__version__)
)
self.setModal(False)
self.copy_btn.setEnabled(False)
# Create a QStackedWidget
self.stacked_widget = QStackedWidget()
# Create a loading message
self.loading_pane = EmptyMessageWidget(
self,
"dependencies",
_("Dependency information will be retrieved shortly. "
"Please wait..."),
bottom_stretch=1,
spinner=True,
)
# Add the loading label and tree widget to the stacked widget
self.stacked_widget.addWidget(self.loading_pane)
self.stacked_widget.addWidget(self.treewidget)
# Make sure the loading label is the one shown initially
self.stacked_widget.setCurrentWidget(self.loading_pane)
# Layout
hlayout = QHBoxLayout()
hlayout.addWidget(self.copy_btn)
hlayout.addStretch()
hlayout.addWidget(ok_btn)
vlayout = QVBoxLayout()
vlayout.setContentsMargins(*((5 * AppStyle.MarginSize,) * 4))
vlayout.addWidget(self.stacked_widget)
vlayout.addSpacing(AppStyle.MarginSize)
vlayout.addWidget(label)
vlayout.addSpacing((-2 if MAC else 1) * AppStyle.MarginSize)
vlayout.addLayout(hlayout)
self.setLayout(vlayout)
self.setFixedSize(860, 560)
# Signals
self.copy_btn.clicked.connect(self.copy_to_clipboard)
ok_btn.accepted.connect(self.accept)
def set_data(self, dependencies):
self.treewidget.update_dependencies(dependencies)
self.treewidget.resize_columns_to_contents()
# Once data is loaded, switch to the tree widget
self.stacked_widget.setCurrentWidget(self.treewidget)
# Enable copy button
self.copy_btn.setEnabled(True)
def copy_to_clipboard(self):
from spyder.dependencies import status
QApplication.clipboard().setText(status())
def test():
"""Run dependency widget test"""
from spyder import dependencies
# Test sample
dependencies.add("IPython", "IPython", "Enhanced Python interpreter",
">=20.0")
dependencies.add("matplotlib", "matplotlib", "Interactive data plotting",
">=1.0")
dependencies.add("sympy", "sympy", "Symbolic Mathematics", ">=10.0",
kind=OPTIONAL)
dependencies.add("foo", "foo", "Non-existent module", ">=1.0")
dependencies.add("numpy", "numpy", "Edit arrays in Variable Explorer",
">=0.10", kind=OPTIONAL)
from spyder.utils.qthelpers import qapplication
app = qapplication() # noqa
dlg = DependenciesDialog(None)
dlg.set_data(dependencies.DEPENDENCIES)
dlg.show()
sys.exit(dlg.exec_())
if __name__ == '__main__':
test()
| DependenciesDialog |
python | google__jax | tests/hijax_test.py | {
"start": 6192,
"end": 6376
} | class ____(HiPrimitive):
def abstract_eval(_, *in_avals):
return TupTy(in_avals), set()
def to_lojax(self, *elts):
return HiTup(elts)
make_tup_p = MakeTup('make_tup')
| MakeTup |
python | kamyu104__LeetCode-Solutions | Python/split-with-minimum-sum.py | {
"start": 61,
"end": 286
} | class ____(object):
def splitNum(self, num):
"""
:type num: int
:rtype: int
"""
sorted_num = "".join(sorted(str(num)))
return int(sorted_num[::2])+int(sorted_num[1::2])
| Solution |
python | django__django | tests/admin_views/tests.py | {
"start": 205230,
"end": 205799
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
def setUp(self):
self.client.force_login(self.superuser)
def test_GET_parent_add(self):
"""
InlineModelAdmin broken?
"""
response = self.client.get(reverse("admin:admin_views_parent_add"))
self.assertEqual(response.status_code, 200)
@override_settings(ROOT_URLCONF="admin_views.urls")
| TestInlineNotEditable |
python | pydata__xarray | xarray/coding/cftime_offsets.py | {
"start": 12920,
"end": 13536
} | class ____(BaseCFTimeOffset):
_freq = "ME"
def __apply__(self, other):
n = _adjust_n_months(other.day, self.n, other.daysinmonth)
return _shift_month(other, n, "end")
def onOffset(self, date) -> bool:
"""Check if the given date is in the set of possible dates created
using a length-one version of this offset class."""
return date.day == date.daysinmonth
_MONTH_ABBREVIATIONS = {
1: "JAN",
2: "FEB",
3: "MAR",
4: "APR",
5: "MAY",
6: "JUN",
7: "JUL",
8: "AUG",
9: "SEP",
10: "OCT",
11: "NOV",
12: "DEC",
}
| MonthEnd |
python | getsentry__sentry | src/sentry/api/serializers/models/pullrequest.py | {
"start": 1082,
"end": 2429
} | class ____(Serializer):
def get_attrs(self, item_list, user, **kwargs):
users_by_author = get_users_for_pull_requests(item_list, user)
repositories = list(Repository.objects.filter(id__in=[c.repository_id for c in item_list]))
repository_map = {repository.id: repository for repository in repositories}
serialized_repos = {r["id"]: r for r in serialize(repositories, user)}
result = {}
for item in item_list:
repository_id = str(item.repository_id)
external_url = ""
if item.repository_id in repository_map:
external_url = item.get_external_url()
result[item] = {
"repository": serialized_repos.get(repository_id, {}),
"external_url": external_url,
"user": users_by_author.get(str(item.author_id), {}) if item.author_id else {},
}
return result
def serialize(self, obj: PullRequest, attrs, user, **kwargs) -> PullRequestSerializerResponse:
return {
"id": obj.key,
"title": obj.title,
"message": obj.message,
"dateCreated": obj.date_added,
"repository": attrs["repository"],
"author": attrs["user"],
"externalUrl": attrs["external_url"],
}
| PullRequestSerializer |
python | pytorch__pytorch | tools/jit/test/test_gen_unboxing.py | {
"start": 337,
"end": 2410
} | class ____(unittest.TestCase):
def test_get_custom_build_selector_with_allowlist(
self,
mock_gen_unboxing: NonCallableMock,
mock_make_file_manager: NonCallableMock,
mock_parse_native_yaml: NonCallableMock,
mock_get_custom_build_selector: NonCallableMock,
) -> None:
args = ["--op-registration-allowlist=op1", "--op-selection-yaml-path=path2"]
gen_unboxing.main(args)
mock_get_custom_build_selector.assert_called_once_with(["op1"], "path2")
def test_get_custom_build_selector_with_allowlist_yaml(
self,
mock_gen_unboxing: NonCallableMock,
mock_make_file_manager: NonCallableMock,
mock_parse_native_yaml: NonCallableMock,
mock_get_custom_build_selector: NonCallableMock,
) -> None:
temp_file = tempfile.NamedTemporaryFile()
temp_file.write(b"- aten::add.Tensor")
temp_file.seek(0)
args = [
f"--TEST-ONLY-op-registration-allowlist-yaml-path={temp_file.name}",
"--op-selection-yaml-path=path2",
]
gen_unboxing.main(args)
mock_get_custom_build_selector.assert_called_once_with(
["aten::add.Tensor"], "path2"
)
temp_file.close()
def test_get_custom_build_selector_with_both_allowlist_and_yaml(
self,
mock_gen_unboxing: NonCallableMock,
mock_make_file_manager: NonCallableMock,
mock_parse_native_yaml: NonCallableMock,
mock_get_custom_build_selector: NonCallableMock,
) -> None:
temp_file = tempfile.NamedTemporaryFile()
temp_file.write(b"- aten::add.Tensor")
temp_file.seek(0)
args = [
"--op-registration-allowlist=op1",
f"--TEST-ONLY-op-registration-allowlist-yaml-path={temp_file.name}",
"--op-selection-yaml-path=path2",
]
gen_unboxing.main(args)
mock_get_custom_build_selector.assert_called_once_with(["op1"], "path2")
temp_file.close()
if __name__ == "__main__":
unittest.main()
| TestGenUnboxing |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py | {
"start": 48145,
"end": 48598
} | class ____(rnn_cell_wrapper_impl.ResidualWrapperBase,
_RNNCellWrapperV1):
"""RNNCell wrapper that ensures cell inputs are added to the outputs."""
def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation
super(ResidualWrapper, self).__init__(*args, **kwargs)
__init__.__doc__ = rnn_cell_wrapper_impl.ResidualWrapperBase.__init__.__doc__
@tf_export(v1=["nn.rnn_cell.DeviceWrapper"])
| ResidualWrapper |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/schedule_dry_run.py | {
"start": 533,
"end": 788
} | class ____(graphene.Union):
class Meta:
types = (
GrapheneDryRunInstigationTick,
GraphenePythonError,
GrapheneScheduleNotFoundError,
)
name = "ScheduleDryRunResult"
| GrapheneScheduleDryRunResult |
python | pytorch__pytorch | torch/_inductor/codegen/cpp_template.py | {
"start": 546,
"end": 5021
} | class ____(KernelTemplate):
index_counter = itertools.count()
def __init__(
self,
name: str,
input_nodes,
layout: ir.Layout,
num_threads: int,
epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
) -> None:
super().__init__(name)
self.input_nodes = input_nodes
self.index = next(self.index_counter)
self.output_node: Union[ir.Buffer, list[ir.Buffer]] = ir.Buffer(
name=f"buf_out{self.index}", layout=layout
)
self.layout = layout
self.num_threads = num_threads
self.epilogue_creator = epilogue_creator
def generate(self, **kwargs):
kernel_name = f"cpp_{self.name}"
with (
patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)),
patch.object(ir.FlexibleLayout, "allow_indexing", True),
V.graph.set_current_device(self.layout.device),
CppTemplateKernel(
kernel_name=kernel_name, num_threads=self.num_threads
) as kernel,
):
code = kernel.render(self, **kwargs)
_, call_args, _, _ = kernel.args.python_argdefs()
log.debug("Generated Code:\n%s", code)
log.debug(
"Args: cpp_argdefs: %s, python_argdefs: %s",
kernel.args.cpp_argdefs(),
kernel.args.python_argdefs(),
)
expected_args = list(
unique(input_node.get_name() for input_node in self.input_nodes)
)
if isinstance(self.output_node, Iterable):
expected_args.extend([node.get_name() for node in self.output_node])
else:
expected_args.extend([self.output_node.get_name()])
assert list(call_args)[: len(expected_args)] == expected_args, (
call_args,
expected_args,
)
extra_args = V.graph.sizevars.size_hints(
map(sympy.expand, call_args[len(expected_args) :])
)
# Cast the size hint from int to ctypes.c_ulonglong explicitly
# since in cpp kernel, we bind it to C long
extra_args = tuple(ctypes.c_ulonglong(x) for x in extra_args)
kernel_hash_name = f"cpp_{self.name}_{self.index}"
# Create the BenchmarkRequest for CPP
bmreq = CppBenchmarkRequest(
kernel_name=kernel_name,
input_tensor_meta=TensorMeta.from_irnodes(self.input_nodes),
# pyrefly: ignore [bad-argument-type]
output_tensor_meta=TensorMeta.from_irnodes(self.output_node),
extra_args=extra_args,
source_code=code,
)
def make_kernel_render(
template_node: ir.CppTemplateBuffer,
flag_template_buffer_has_other_users: bool,
epilogue_nodes: Optional[list[ir.IRNode]] = None,
):
kernel = CppTemplateKernel(
kernel_name=str(Placeholder.KERNEL_NAME), num_threads=self.num_threads
)
render = functools.partial(
kernel.render,
self,
template_buffer_node=template_node,
flag_template_buffer_has_other_users=flag_template_buffer_has_other_users,
epilogue_nodes=epilogue_nodes,
**kwargs,
)
return kernel, render
return CppTemplateCaller(
kernel_hash_name,
self.name,
self.input_nodes,
# pyrefly: ignore [index-error]
self.output_node[0].get_layout()
if isinstance(self.output_node, Iterable)
else self.output_node.get_layout(),
make_kernel_render,
bmreq,
self,
)
def header(self) -> IndentedBuffer:
res = IndentedBuffer()
res.writeline("#include <torch/csrc/inductor/cpp_prefix.h>")
# TODO: add c10::ForcedUnroll test to test_aoti_abi_check
res.splice("""#include <c10/util/Unroll.h>""")
res.splice("""#include <torch/csrc/inductor/aoti_torch/c/shim.h>""")
enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [
"linux",
"win32",
]
if enable_kernel_profile:
res.writelines(["#include <torch/csrc/inductor/aoti_runtime/utils.h>"])
return res
def render(self, **kwargs) -> str:
raise NotImplementedError
| CppTemplate |
python | coleifer__peewee | tests/mysql_ext.py | {
"start": 763,
"end": 929
} | class ____(TestModel):
person = ForeignKeyField(Person, backref='notes')
content = TextField()
timestamp = DateTimeField(default=datetime.datetime.now)
| Note |
python | apache__airflow | airflow-core/tests/unit/cli/commands/test_cheat_sheet_command.py | {
"start": 2370,
"end": 2898
} | class ____:
@classmethod
def setup_class(cls):
cls.parser = cli_parser.get_parser()
@mock.patch("airflow.cli.cli_parser.airflow_commands", MOCK_COMMANDS)
def test_should_display_index(self, stdout_capture):
with stdout_capture as temp_stdout:
args = self.parser.parse_args(["cheat-sheet"])
args.func(args)
output = temp_stdout.getvalue()
assert ALL_COMMANDS in output
assert SECTION_A in output
assert SECTION_E in output
| TestCheatSheetCommand |
python | pytorch__pytorch | torch/distributed/checkpoint/filesystem.py | {
"start": 2145,
"end": 2331
} | class ____(Enum):
TORCH_SAVE = "torch_save"
SAFETENSORS = "safetensors"
DEFAULT_SUFFIX = ".distcp"
def _generate_uuid() -> str:
return str(uuid.uuid4())
| SerializationFormat |
python | pallets__werkzeug | src/werkzeug/routing/converters.py | {
"start": 2402,
"end": 3274
} | class ____(BaseConverter):
"""Matches one of the items provided. Items can either be Python
identifiers or strings::
Rule('/<any(about, help, imprint, class, "foo,bar"):page_name>')
:param map: the :class:`Map`.
:param items: this function accepts the possible items as positional
arguments.
.. versionchanged:: 2.2
Value is validated when building a URL.
"""
def __init__(self, map: Map, *items: str) -> None:
super().__init__(map)
self.items = set(items)
self.regex = f"(?:{'|'.join([re.escape(x) for x in items])})"
def to_url(self, value: t.Any) -> str:
if value in self.items:
return str(value)
valid_values = ", ".join(f"'{item}'" for item in sorted(self.items))
raise ValueError(f"'{value}' is not one of {valid_values}")
| AnyConverter |
python | ray-project__ray | python/ray/dag/tests/experimental/actor_defs.py | {
"start": 62,
"end": 1838
} | class ____:
def __init__(self, init_value, fail_after=None, sys_exit=False):
self.i = init_value
self.fail_after = fail_after
self.sys_exit = sys_exit
self.count = 0
def _fail_if_needed(self):
if self.fail_after and self.count > self.fail_after:
# Randomize the failures to better cover multi actor scenarios.
if random.random() > 0.5:
if self.sys_exit:
os._exit(1)
else:
raise RuntimeError("injected fault")
def inc(self, x):
self.i += x
self.count += 1
self._fail_if_needed()
return self.i
def double_and_inc(self, x):
self.i *= 2
self.i += x
return self.i
def echo(self, x):
self.count += 1
self._fail_if_needed()
return x
def append_to(self, lst):
lst.append(self.i)
return lst
def inc_two(self, x, y):
self.i += x
self.i += y
return self.i
def sleep(self, x):
time.sleep(x)
return x
@ray.method(num_returns=2)
def return_two(self, x):
return x, x + 1
def read_input(self, x):
return x
@ray.method(num_returns=2)
def inc_and_return_two(self, x):
self.i += x
return self.i, self.i + 1
@ray.method(num_returns=1)
def return_two_as_one(self, x):
return x, x + 1
@ray.method(num_returns=2)
def return_two_from_three(self, x):
return x, x + 1, x + 2
@ray.method(num_returns=2)
def return_two_but_raise_exception(self, x):
raise RuntimeError
return 1, 2
def get_events(self):
return getattr(self, "__ray_cgraph_events", [])
@ray.remote
| Actor |
python | huggingface__transformers | src/transformers/models/video_llama_3/modular_video_llama_3.py | {
"start": 5674,
"end": 8186
} | class ____(PreTrainedConfig):
"""
This is the configuration class to store the configuration of a [`VideoLlama3Model`]. It is used to instantiate a
VideoLLaMA3 model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of
VideoLLaMA3-2B [lkhl/VideoLLaMA3-2B-Image-HF](https://huggingface.co/lkhl/VideoLLaMA3-2B-Image-HF).
Args:
text_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `Qwen2Config`):
The config object or dictionary of the text backbone.
vision_config (`Union[PreTrainedConfig, dict]`, *optional*, defaults to `VideoLlama3VisionConfig`):
The config object or dictionary of the vision backbone.
image_token_id (`int`, *optional*, defaults to 151655):
The image token index to encode the image prompt.
video_token_id (`int`, *optional*, defaults to 151656):
The video token index to encode the image prompt.
"""
model_type = "video_llama_3"
sub_configs = {"vision_config": VideoLlama3VisionConfig, "text_config": AutoConfig}
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
text_config=None,
vision_config=None,
image_token_id=151655,
video_token_id=151656,
**kwargs,
):
if isinstance(vision_config, dict):
self.vision_config = self.sub_configs["vision_config"](**vision_config)
elif isinstance(vision_config, PreTrainedConfig):
self.vision_config = vision_config
elif vision_config is None:
self.vision_config = self.sub_configs["vision_config"]()
else:
raise ValueError(
f"vision_config must be of type `dict` or `PreTrainedConfig`, but got {type(vision_config)}."
)
if isinstance(text_config, dict):
self.text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
elif isinstance(text_config, PreTrainedConfig):
self.text_config = text_config
elif text_config is None:
self.text_config = CONFIG_MAPPING["qwen2"]()
else:
raise ValueError(f"text_config must be of type `dict` or `PreTrainedConfig`, but got {type(text_config)}.")
self.image_token_id = image_token_id
self.video_token_id = video_token_id
super().__init__(**kwargs)
| VideoLlama3Config |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 20970,
"end": 22015
} | class ____(Interface):
"""An object representing a Pyramid authorization policy.
.. deprecated:: 2.0
Authentication policies have been removed in favor of security
policies. See :ref:`upgrading_auth_20` for more information.
"""
def permits(context, principals, permission):
"""Return an instance of :class:`pyramid.security.Allowed` if any
of the ``principals`` is allowed the ``permission`` in the current
``context``, else return an instance of
:class:`pyramid.security.Denied`.
"""
def principals_allowed_by_permission(context, permission):
"""Return a set of principal identifiers allowed by the
``permission`` in ``context``. This behavior is optional; if you
choose to not implement it you should define this method as
something which raises a ``NotImplementedError``. This method
will only be called when the
``pyramid.security.principals_allowed_by_permission`` API is
used."""
| IAuthorizationPolicy |
python | PrefectHQ__prefect | src/prefect/server/orchestration/global_policy.py | {
"start": 7281,
"end": 8079
} | class ____(
BaseUniversalTransform[
orm_models.Run, Union[core.FlowRunPolicy, core.TaskRunPolicy]
]
):
"""
Records the amount of time a run spends in the running state.
"""
async def before_transition(
self, context: GenericOrchestrationContext[orm_models.Run, Any]
) -> None:
if self.nullified_transition():
return
if context.proposed_state is not None:
# if exiting a running state...
if context.initial_state and context.initial_state.is_running():
# increment the run time by the time spent in the previous state
context.run.total_run_time += (
context.proposed_state.timestamp - context.initial_state.timestamp
)
| IncrementRunTime |
python | PrefectHQ__prefect | src/prefect/server/exceptions.py | {
"start": 596,
"end": 735
} | class ____(Exception):
"""Raised to indicate that a flow run's graph has more nodes that the configured
maximum"""
| FlowRunGraphTooLarge |
python | ipython__ipython | tests/test_guarded_eval.py | {
"start": 7286,
"end": 7392
} | class ____:
@staticmethod
def static_method() -> HeapType:
return HeapType()
| HasStaticMethod |
python | scikit-learn__scikit-learn | sklearn/utils/_mocking.py | {
"start": 11824,
"end": 12570
} | class ____(BaseEstimator):
"""Wrap estimator which will not expose `sample_weight`.
Parameters
----------
est : estimator, default=None
The estimator to wrap.
"""
def __init__(self, est=None):
self.est = est
def fit(self, X, y):
return self.est.fit(X, y)
def predict(self, X):
return self.est.predict(X)
def predict_proba(self, X):
return self.est.predict_proba(X)
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags._skip_test = True
return tags
def _check_response(method):
def check(self):
return self.response_methods is not None and method in self.response_methods
return check
| NoSampleWeightWrapper |
python | gevent__gevent | src/gevent/tests/known_failures.py | {
"start": 2663,
"end": 3952
} | class ____(object):
__slots__ = (
'__name__',
# When does the class of this condition apply?
'when',
# When should this test be run alone, if it's run?
'run_alone',
# Should this test be ignored during coverage measurement?
'ignore_coverage',
# {name: (Condition, value)}
'options',
)
def __init__(self, when, run_alone, ignore_coverage, options):
assert isinstance(when, Condition)
assert isinstance(run_alone, Condition)
assert isinstance(ignore_coverage, Condition)
self.when = when
self.__name__ = None # pylint:disable=non-str-assignment-to-dunder-name
self.run_alone = run_alone
self.ignore_coverage = ignore_coverage
if options:
for v in options.values():
assert isinstance(v, tuple) and len(v) == 2
assert isinstance(v[0], Condition)
self.options = options
def __set_name__(self, owner, name):
self.__name__ = name
def __repr__(self):
return '<%s for %s when=%r=%s run_alone=%r=%s>' % (
type(self).__name__,
self.__name__,
self.when, bool(self.when),
self.run_alone, bool(self.run_alone)
)
| _Definition |
python | streamlit__streamlit | lib/streamlit/vendor/pympler/asizeof.py | {
"start": 29127,
"end": 47398
} | class ____(object):
"""Type definition class."""
base = 0 # basic size in bytes
both = None # both data and code if True, code only if False
item = 0 # item size in bytes
kind = None # _kind_... value
leng = None # _len_...() function or None
refs = None # _..._refs() function or None
type = None # original type
vari = None # item size attr name or _Not_vari
xtyp = None # if True, not _getsizeof'd
def __init__(self, **kwds):
self.reset(**kwds)
def __lt__(self, unused): # for Python 3+
return True
def __repr__(self):
return repr(self.args())
def __str__(self):
t = [str(self.base), str(self.item)]
for f in (self.leng, self.refs):
t.append(_nameof(f) or "n/a")
if not self.both:
t.append("(code only)")
return ", ".join(t)
def args(self): # as args tuple
"""Return all attributes as arguments tuple."""
return (
self.base,
self.item,
self.leng,
self.refs,
self.both,
self.kind,
self.type,
self.xtyp,
)
def dup(self, other=None, **kwds):
"""Duplicate attributes of dict or other typedef."""
t = other or _dict_typedef
d = t.kwds()
d.update(kwds)
self.reset(**d)
def flat(self, obj, mask=0):
"""Return the aligned flat size."""
s = self.base
if self.leng and self.item > 0: # include items
s += self.leng(obj) * self.item
# workaround sys.getsizeof bug for _array types
# (in some Python versions) and for other types
# with variable .itemsize like numpy.arrays, etc.
if not self.xtyp:
s = _getsizeof(obj, s)
if mask: # alignment mask
s = (s + mask) & ~mask
# if (mask + 1) & mask:
# raise _OptionError(self.flat, mask=mask)
return s
def format(self):
"""Return format dict."""
a = _nameof(self.leng)
return dict(
leng=((" (%s)" % (a,)) if a else _NN),
item="var" if self.vari else self.item,
code=_NN if self.both else " (code only)",
base=self.base,
kind=self.kind,
)
def kwds(self):
"""Return all attributes as keywords dict."""
return dict(
base=self.base,
both=self.both,
item=self.item,
kind=self.kind,
leng=self.leng,
refs=self.refs,
type=self.type,
vari=self.vari,
xtyp=self.xtyp,
)
def reset(
self,
base=0,
item=0,
leng=None,
refs=None,
both=True,
kind=None,
type=None,
vari=_Not_vari,
xtyp=False,
**extra,
):
"""Reset all specified typedef attributes."""
v = vari or _Not_vari
if v != str(v): # attr name
e = dict(vari=v)
elif base < 0:
e = dict(base=base)
elif both not in (False, True):
e = dict(both=both)
elif item < 0:
e = dict(item=item)
elif kind not in _all_kinds:
e = dict(kind=kind)
elif leng not in _all_lens: # XXX or not callable(leng)
e = dict(leng=leng)
elif refs not in _all_refs: # XXX or not callable(refs)
e = dict(refs=refs)
elif xtyp not in (False, True):
e = dict(xtyp=xtyp)
elif extra:
e = {}
else:
self.base = base
self.both = both
self.item = item
self.kind = kind
self.leng = leng
self.refs = refs
self.type = type # unchecked, as-is
self.vari = v
self.xtyp = xtyp
return
e.update(extra)
raise _OptionError(self.reset, **e)
def save(self, t, base=0, heap=False):
"""Save this typedef plus its class typedef."""
c, k = _key2tuple(t)
if k and k not in _typedefs: # instance key
_typedefs[k] = self
if c and c not in _typedefs: # class key
b = _basicsize(type(t), base=base, heap=heap)
k = _kind_ignored if _isignored(t) else self.kind
_typedefs[c] = _Typedef(
base=b, both=False, kind=k, type=t, refs=_type_refs
)
elif t not in _typedefs:
if not _isbuiltin2(t): # array, range, xrange in Python 2.x
s = " ".join((self.vari, _moduleof(t), _nameof(t)))
s = "%r %s %s" % ((c, k), self.both, s.strip())
raise KeyError("typedef %r bad: %s" % (self, s))
_typedefs[t] = _Typedef(
base=_basicsize(t, base=base), both=False, kind=_kind_ignored, type=t
)
def set(self, safe_len=False, **kwds):
"""Set one or more attributes."""
if kwds: # double check
d = self.kwds()
d.update(kwds)
self.reset(**d)
if safe_len and self.item:
self.leng = _len
_typedefs = {} # type: Dict[type, _Typedef]
def _typedef_both(
t,
base=0,
item=0,
leng=None,
refs=None,
kind=_kind_static,
heap=False,
vari=_Not_vari,
):
"""Add new typedef for both data and code."""
v = _Typedef(
base=_basicsize(t, base=base),
item=_itemsize(t, item),
refs=refs,
leng=leng,
both=True,
kind=kind,
type=t,
vari=vari,
)
v.save(t, base=base, heap=heap)
return v # for _dict_typedef
def _typedef_code(t, base=0, refs=None, kind=_kind_static, heap=False):
"""Add new typedef for code only."""
v = _Typedef(
base=_basicsize(t, base=base), refs=refs, both=False, kind=kind, type=t
)
v.save(t, base=base, heap=heap)
return v # for _dict_typedef
# Static typedefs for data and code types
_typedef_both(complex)
_typedef_both(float)
_typedef_both(int, leng=_len_int) # see _len_int
_typedef_both(
list, refs=_seq_refs, leng=_len_list, item=_sizeof_Cvoidp
) # sizeof(PyObject*)
_typedef_both(
tuple, refs=_seq_refs, leng=_len, item=_sizeof_Cvoidp
) # sizeof(PyObject*)
_typedef_both(property, refs=_prop_refs)
_typedef_both(type(Ellipsis))
_typedef_both(type(None))
# _Slots are "tuple-like", REMOVED see _Slots.__doc__
# _typedef_both(_Slots, item=_sizeof_Cvoidp,
# leng=_len_slots, # length less one
# refs=None, # but no referents
# heap=True) # plus head
# dict, dictproxy, dict_proxy and other dict-like types
_dict_typedef = _typedef_both(
dict, item=_sizeof_CPyDictEntry, leng=_len_dict, refs=_dict_refs
)
# XXX any class __dict__ is <type dict_proxy> in Python 3+?
_typedef_both(
type(_Typedef.__dict__), item=_sizeof_CPyDictEntry, leng=_len_dict, refs=_dict_refs
)
# other dict-like classes and types may be derived or inferred,
# provided the module and class name is listed here (see functions
# _isdictype and _infer_dict for further details)
_dict_types = dict(
UserDict=("IterableUserDict", "UserDict"),
weakref=("WeakKeyDictionary", "WeakValueDictionary"),
)
try: # <type module> is essentially a dict
_typedef_both(
Types.ModuleType,
base=_dict_typedef.base,
item=_dict_typedef.item + _sizeof_CPyModuleObject,
leng=_len_module,
refs=_module_refs,
)
except AttributeError: # missing
pass
# Newer or obsolete types
from array import array as _array # array type
def _len_array(obj):
"""Array length (in bytes!)."""
return len(obj) * obj.itemsize
def _array_kwds(obj):
# since item size varies by the array data type, set
# itemsize to 1 byte and use _len_array in bytes;
# _getsizeof(array) returns array plus base size
b = max(56, _getsizeof(obj, 0) - _len_array(obj))
return dict(
base=b,
leng=_len_array,
item=_sizeof_Cbyte,
vari="itemsize", # array.itemsize
xtyp=True,
) # never _getsizeof'd
_all_lens.add(_len_array) # type: ignore
try: # bool has non-zero __itemsize__ in 3.0
_typedef_both(bool)
except NameError: # missing
pass
try:
_typedef_both(bytearray, item=_sizeof_Cbyte, leng=_len_bytearray)
except NameError: # bytearray new in 2.6, 3.0
pass
try:
if type(bytes) is not type(str): # bytes is str in 2.6, bytes new in 2.6, 3.0
_typedef_both(bytes, item=_sizeof_Cbyte, leng=_len) # bytes new in 2.6, 3.0
except NameError: # missing
pass
# try: # XXX like bytes
# _typedef_both(str8, item=_sizeof_Cbyte, leng=_len) # str8 new in 2.6, 3.0
# except NameError: # missing
# pass
try:
_typedef_both(enumerate, refs=_enum_refs)
except NameError: # missing
pass
try: # Exception is type in Python 3+
_typedef_both(Exception, refs=_exc_refs)
except Exception: # missing
pass
try:
_typedef_both(frozenset, item=_sizeof_Csetentry, leng=_len_set, refs=_seq_refs)
except NameError: # missing
pass
try:
_typedef_both(set, item=_sizeof_Csetentry, leng=_len_set, refs=_seq_refs)
except NameError: # missing
pass
try: # not callable()
_typedef_both(Types.GetSetDescriptorType)
except AttributeError: # missing
pass
try: # not callable()
_typedef_both(Types.MemberDescriptorType)
except AttributeError: # missing
pass
try:
_typedef_both(type(NotImplemented)) # == Types.NotImplementedType
except NameError: # missing
pass
try: # MCCABE 19
import numpy as _numpy # NumPy array, matrix, etc.
try:
_numpy_memmap = _numpy.memmap
except AttributeError:
_numpy_memmap = None
try:
from mmap import PAGESIZE as _PAGESIZE
if _PAGESIZE < 1024:
raise ImportError
except ImportError:
_PAGESIZE = 4096 # 4 KiB, typical
def _isnumpy(obj):
"""Return True for a NumPy arange, array, matrix, memmap, ndarray, etc. instance."""
# not every numpy obj hasattr(obj, 'base')
if (
hasattr(obj, "dtype")
and hasattr(obj, "itemsize")
and hasattr(obj, "nbytes")
):
try:
return _moduleof(_classof(obj)).startswith("numpy") or _moduleof(
type(obj)
).startswith("numpy")
except (AttributeError, OSError, ValueError): # on iOS/Pythonista
pass
return False
def _len_numpy(obj):
"""NumPy array, matrix, etc. length (in bytes!)."""
return obj.nbytes # == obj.size * obj.itemsize
def _len_numpy_memmap(obj):
"""Approximate NumPy memmap in-memory size (in bytes!)."""
nb = int(obj.nbytes * _amapped)
# round up to multiple of virtual memory page size
return ((nb + _PAGESIZE - 1) // _PAGESIZE) * _PAGESIZE
def _numpy_kwds(obj):
t = type(obj)
# .nbytes is included in sys.sizeof size for most numpy
# objects except for numpy.memmap (and for the latter it
# is the length of the file to be memory-mapped which by
# default is the file size less the offset specified)
if t is _numpy_memmap: # isinstance(obj, _numpy_memmap)
b, _len_, nb = 144, _len_numpy_memmap, 0
else: # XXX 96, 128, 144 typical?
b, _len_, nb = 96, _len_numpy, obj.nbytes
# since item size depends on the nympy data type, set
# itemsize to 1 byte and use _len_numpy in bytes; note,
# function itemsize returns the actual size in bytes,
# function alen returns the length in number of items
return dict(
base=_getsizeof(obj, b) - nb,
item=_sizeof_Cbyte, # not obj.itemsize!
leng=_len_,
refs=_numpy_refs,
vari="itemsize", # numpy.itemsize
xtyp=True,
) # never _getsizeof'd
def _numpy_refs(obj, named):
"""Return the .base object for NumPy slices, views, etc."""
return _refs(obj, named, "base")
_all_lens.add(_len_numpy) # type: ignore
_all_lens.add(_len_numpy_memmap) # type: ignore
_all_refs.add(_numpy_refs) # type: ignore
except ImportError: # no NumPy
_numpy = _numpy_kwds = None # type: ignore # see function _typedef below
def _isnumpy(unused): # PYCHOK expected
"""Not applicable, no NumPy."""
return False
try:
_typedef_both(range)
except NameError: # missing
pass
try:
_typedef_both(reversed, refs=_enum_refs)
except NameError: # missing
pass
try:
_typedef_both(
slice, item=_sizeof_Cvoidp, leng=_len_slice
) # XXX worst-case itemsize?
except NameError: # missing
pass
try:
from os import stat
_typedef_both(type(stat(curdir)), refs=_stat_refs) # stat_result
except ImportError: # missing
pass
try:
from os import statvfs
_typedef_both(
type(statvfs(curdir)),
refs=_statvfs_refs, # statvfs_result
item=_sizeof_Cvoidp,
leng=_len,
)
except ImportError: # missing
pass
try:
from struct import Struct # only in Python 2.5 and 3.0
_typedef_both(Struct, item=_sizeof_Cbyte, leng=_len_struct) # len in bytes
except ImportError: # missing
pass
try:
_typedef_both(Types.TracebackType, refs=_tb_refs)
except AttributeError: # missing
pass
_typedef_both(str, leng=_len_unicode, item=_sizeof_Cunicode)
try: # <type 'KeyedRef'>
_typedef_both(Weakref.KeyedRef, refs=_weak_refs, heap=True) # plus head
except AttributeError: # missing
pass
try: # <type 'weakproxy'>
_typedef_both(Weakref.ProxyType)
except AttributeError: # missing
pass
try: # <type 'weakref'>
_typedef_both(Weakref.ReferenceType, refs=_weak_refs)
except AttributeError: # missing
pass
# some other, callable types
_typedef_code(object, kind=_kind_ignored)
_typedef_code(super, kind=_kind_ignored)
_typedef_code(_Type_type, kind=_kind_ignored)
try:
_typedef_code(classmethod, refs=_im_refs)
except NameError:
pass
try:
_typedef_code(staticmethod, refs=_im_refs)
except NameError:
pass
try:
_typedef_code(Types.MethodType, refs=_im_refs)
except NameError:
pass
try: # generator (expression), no itemsize, no len(), not callable()
_typedef_both(Types.GeneratorType, refs=_gen_refs)
except AttributeError: # missing
pass
try: # <type 'weakcallableproxy'>
_typedef_code(Weakref.CallableProxyType, refs=_weak_refs)
except AttributeError: # missing
pass
# any type-specific iterators
s = [_items({}), _keys({}), _values({})]
try: # reversed list and tuples iterators
s.extend([reversed([]), reversed(())])
except NameError: # missing
pass
try: # callable-iterator
from re import finditer
s.append(finditer(_NN, _NN))
del finditer
except ImportError: # missing
pass
for t in _values(_typedefs):
if t.type and t.leng:
try: # create an (empty) instance
s.append(t.type())
except TypeError:
pass
for t in s:
try:
i = iter(t)
_typedef_both(type(i), leng=_len_iter, refs=_iter_refs, item=0) # no itemsize!
except (KeyError, TypeError): # ignore non-iterables, duplicates, etc.
pass
del i, s, t
def _typedef(obj, derive=False, frames=False, infer=False): # MCCABE 25
"""Create a new typedef for an object."""
t = type(obj)
v = _Typedef(base=_basicsize(t, obj=obj), kind=_kind_dynamic, type=t)
# _printf('new %r %r/%r %s', t, _basicsize(t), _itemsize(t), _repr(dir(obj)))
if ismodule(obj): # handle module like dict
v.dup(
item=_dict_typedef.item + _sizeof_CPyModuleObject,
leng=_len_module,
refs=_module_refs,
)
elif _isframe(obj):
v.set(
base=_basicsize(t, base=_sizeof_CPyFrameObject, obj=obj),
item=_itemsize(t),
leng=_len_frame,
refs=_frame_refs,
)
if not frames: # ignore frames
v.set(kind=_kind_ignored)
elif iscode(obj):
v.set(
base=_basicsize(t, base=_sizeof_CPyCodeObject, obj=obj),
item=_sizeof_Cvoidp,
leng=_len_code,
refs=_co_refs,
both=False,
) # code only
elif callable(obj):
if isclass(obj): # class or type
v.set(refs=_class_refs, both=False) # code only
if _isignored(obj):
v.set(kind=_kind_ignored)
elif isbuiltin(obj): # function or method
v.set(both=False, kind=_kind_ignored) # code only
elif isfunction(obj):
v.set(refs=_func_refs, both=False) # code only
elif ismethod(obj):
v.set(refs=_im_refs, both=False) # code only
elif isclass(t): # callable instance, e.g. SCons,
# handle like any other instance further below
v.set(item=_itemsize(t), safe_len=True, refs=_inst_refs) # not code only!
else:
v.set(both=False) # code only
elif _issubclass(t, dict):
v.dup(kind=_kind_derived)
elif _isdictype(obj) or (infer and _infer_dict(obj)):
v.dup(kind=_kind_inferred)
elif _iscell(obj):
v.set(item=_itemsize(t), refs=_cell_refs)
elif _isnamedtuple(obj):
v.set(refs=_namedtuple_refs)
elif _numpy and _isnumpy(obj):
v.set(**_numpy_kwds(obj))
elif isinstance(obj, _array):
v.set(**_array_kwds(obj))
elif _isignored(obj):
v.set(kind=_kind_ignored)
else: # assume an instance of some class
if derive:
p = _derive_typedef(t)
if p: # duplicate parent
v.dup(other=p, kind=_kind_derived)
return v
if _issubclass(t, Exception):
v.set(item=_itemsize(t), safe_len=True, refs=_exc_refs, kind=_kind_derived)
elif isinstance(obj, Exception):
v.set(item=_itemsize(t), safe_len=True, refs=_exc_refs)
else:
v.set(item=_itemsize(t), safe_len=True, refs=_inst_refs)
return v
| _Typedef |
python | PrefectHQ__prefect | src/prefect/server/utilities/database.py | {
"start": 11214,
"end": 11743
} | class ____(functions.GenericFunction[DateTime]):
"""Platform-independent way to add a timestamp and an interval"""
type: Timestamp = Timestamp()
inherit_cache: bool = True
def __init__(
self,
dt: _SQLExpressionOrLiteral[datetime.datetime],
interval: _SQLExpressionOrLiteral[datetime.timedelta],
**kwargs: Any,
):
super().__init__(
sa.type_coerce(dt, Timestamp()),
sa.type_coerce(interval, sa.Interval()),
**kwargs,
)
| date_add |
python | marshmallow-code__marshmallow | tests/test_deserialization.py | {
"start": 59876,
"end": 60074
} | class ____(Schema):
email = fields.Email()
colors = fields.Str(validate=validate.OneOf(["red", "blue"]))
age = fields.Integer(validate=validate.Range(min=0, min_inclusive=False))
| Validator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/source.py | {
"start": 1488,
"end": 14588
} | class ____(AbstractSource):
continue_sync_on_stream_failure = True
@staticmethod
def _get_org_repositories(
config: Mapping[str, Any], authenticator: MultipleTokenAuthenticator, is_check_connection: bool = False
) -> Tuple[List[str], List[str], Optional[str]]:
"""
Parse config/repositories and produce two lists: organizations, repositories.
Args:
config (dict): Dict representing connector's config
authenticator(MultipleTokenAuthenticator): authenticator object
"""
config_repositories = set(config.get("repositories"))
repositories = set()
organizations = set()
unchecked_repos = set()
unchecked_orgs = set()
pattern = None
for org_repos in config_repositories:
_, _, repos = org_repos.partition("/")
if "*" in repos:
unchecked_orgs.add(org_repos)
else:
unchecked_repos.add(org_repos)
if unchecked_orgs:
org_names = [org.split("/")[0] for org in unchecked_orgs]
pattern = "|".join([f"({org.replace('*', '.*')})" for org in unchecked_orgs])
stream = Repositories(authenticator=authenticator, organizations=org_names, api_url=config.get("api_url"), pattern=pattern)
stream.exit_on_rate_limit = True if is_check_connection else False
for record in read_full_refresh(stream):
repositories.add(record["full_name"])
organizations.add(record["organization"])
unchecked_repos = unchecked_repos - repositories
if unchecked_repos:
stream = RepositoryStats(
authenticator=authenticator,
repositories=list(unchecked_repos),
api_url=config.get("api_url"),
# This parameter is deprecated and in future will be used sane default, page_size: 10
page_size_for_large_streams=config.get("page_size_for_large_streams", constants.DEFAULT_PAGE_SIZE_FOR_LARGE_STREAM),
)
stream.exit_on_rate_limit = True if is_check_connection else False
for record in read_full_refresh(stream):
repositories.add(record["full_name"])
organization = record.get("organization", {}).get("login")
if organization:
organizations.add(organization)
return list(organizations), list(repositories), pattern
@staticmethod
def get_access_token(config: Mapping[str, Any]):
# Before we supported oauth, personal_access_token was called `access_token` and it lived at the
# config root. So we first check to make sure any backwards compatbility is handled.
if "access_token" in config:
return constants.PERSONAL_ACCESS_TOKEN_TITLE, config["access_token"]
credentials = config.get("credentials", {})
if "access_token" in credentials:
return constants.ACCESS_TOKEN_TITLE, credentials["access_token"]
if "personal_access_token" in credentials:
return constants.PERSONAL_ACCESS_TOKEN_TITLE, credentials["personal_access_token"]
raise Exception("Invalid config format")
def _get_authenticator(self, config: Mapping[str, Any]):
_, token = self.get_access_token(config)
tokens = [t.strip() for t in token.split(constants.TOKEN_SEPARATOR)]
return MultipleTokenAuthenticatorWithRateLimiter(tokens=tokens)
def _validate_and_transform_config(self, config: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
config = self._ensure_default_values(config)
config = self._validate_repositories(config)
config = self._validate_branches(config)
return config
def _ensure_default_values(self, config: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
config.setdefault("api_url", "https://api.github.com")
api_url_parsed = urlparse(config["api_url"])
if not api_url_parsed.scheme.startswith("http"):
message = "Please enter a full url for `API URL` field starting with `http`"
elif api_url_parsed.scheme == "http" and not self._is_http_allowed():
message = "HTTP connection is insecure and is not allowed in this environment. Please use `https` instead."
elif not api_url_parsed.netloc:
message = "Please provide a correct API URL."
else:
return config
raise AirbyteTracedException(message=message, failure_type=FailureType.config_error)
def _validate_repositories(self, config: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
if config.get("repositories"):
pass
elif config.get("repository"):
config["repositories"] = set(filter(None, config["repository"].split(" ")))
return config
def _validate_branches(self, config: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
if config.get("branches"):
pass
elif config.get("branch"):
config["branches"] = set(filter(None, config["branch"].split(" ")))
return config
@staticmethod
def _is_http_allowed() -> bool:
return getenv("DEPLOYMENT_MODE", "").upper() != "CLOUD"
def user_friendly_error_message(self, message: str) -> str:
user_message = ""
if "404 Client Error: Not Found for url: https://api.github.com/repos/" in message:
# 404 Client Error: Not Found for url: https://api.github.com/repos/airbytehq/airbyte3?per_page=100
full_repo_name = message.split("https://api.github.com/repos/")[1].split("?")[0]
user_message = f'Repo name: "{full_repo_name}" is unknown, "repository" config option should use existing full repo name <organization>/<repository>'
elif "404 Client Error: Not Found for url: https://api.github.com/orgs/" in message:
# 404 Client Error: Not Found for url: https://api.github.com/orgs/airbytehqBLA/repos?per_page=100
org_name = message.split("https://api.github.com/orgs/")[1].split("/")[0]
user_message = f'Organization name: "{org_name}" is unknown, "repository" config option should be updated. Please validate your repository config.'
elif "401 Client Error: Unauthorized for url" in message or ("Error: Unauthorized" in message and "401" in message):
# 401 Client Error: Unauthorized for url: https://api.github.com/orgs/datarootsio/repos?per_page=100&sort=updated&direction=desc
user_message = (
"Github credentials have expired or changed, please review your credentials and re-authenticate or renew your access token."
)
return user_message
def check_connection(self, logger: logging.Logger, config: Mapping[str, Any]) -> Tuple[bool, Any]:
config = self._validate_and_transform_config(config)
try:
authenticator = self._get_authenticator(config)
_, repositories, _ = self._get_org_repositories(config=config, authenticator=authenticator, is_check_connection=True)
if not repositories:
return (
False,
"Some of the provided repositories couldn't be found. Please verify if every entered repository has a valid name and it matches the following format: airbytehq/airbyte airbytehq/another-repo airbytehq/* airbytehq/airbyte.",
)
return True, None
except MessageRepresentationAirbyteTracedErrors as e:
user_message = self.user_friendly_error_message(e.message)
return False, user_message or e.message
except Exception as e:
message = repr(e)
user_message = self.user_friendly_error_message(message)
return False, user_message or message
def streams(self, config: Mapping[str, Any]) -> List[Stream]:
authenticator = self._get_authenticator(config)
config = self._validate_and_transform_config(config)
try:
organizations, repositories, pattern = self._get_org_repositories(config=config, authenticator=authenticator)
except Exception as e:
message = repr(e)
user_message = self.user_friendly_error_message(message)
if user_message:
raise AirbyteTracedException(
internal_message=message, message=user_message, failure_type=FailureType.config_error, exception=e
)
else:
raise e
if not any((organizations, repositories)):
user_message = (
"No streams available. Looks like your config for repositories or organizations is not valid."
" Please, check your permissions, names of repositories and organizations."
" Needed scopes: repo, read:org, read:repo_hook, read:user, read:discussion, workflow."
)
raise AirbyteTracedException(
internal_message="No streams available. Please check permissions",
message=user_message,
failure_type=FailureType.config_error,
)
# This parameter is deprecated and in future will be used sane default, page_size: 10
page_size = config.get("page_size_for_large_streams", constants.DEFAULT_PAGE_SIZE_FOR_LARGE_STREAM)
access_token_type, _ = self.get_access_token(config)
max_waiting_time = config.get("max_waiting_time", 10) * 60
organization_args = {
"authenticator": authenticator,
"organizations": organizations,
"api_url": config.get("api_url"),
"access_token_type": access_token_type,
"max_waiting_time": max_waiting_time,
}
start_date = config.get("start_date")
organization_args_with_start_date = {**organization_args, "start_date": start_date}
repository_args = {
"authenticator": authenticator,
"api_url": config.get("api_url"),
"repositories": repositories,
"page_size_for_large_streams": page_size,
"access_token_type": access_token_type,
"max_waiting_time": max_waiting_time,
}
repository_args_with_start_date = {**repository_args, "start_date": start_date}
pull_requests_stream = PullRequests(**repository_args_with_start_date)
projects_stream = Projects(**repository_args_with_start_date)
project_columns_stream = ProjectColumns(projects_stream, **repository_args_with_start_date)
teams_stream = Teams(**organization_args)
team_members_stream = TeamMembers(parent=teams_stream, **repository_args)
workflow_runs_stream = WorkflowRuns(**repository_args_with_start_date)
return [
IssueTimelineEvents(**repository_args),
Assignees(**repository_args),
Branches(**repository_args),
Collaborators(**repository_args),
Comments(**repository_args_with_start_date),
CommitCommentReactions(**repository_args_with_start_date),
CommitComments(**repository_args_with_start_date),
Commits(**repository_args_with_start_date, branches_to_pull=config.get("branches", [])),
ContributorActivity(**repository_args),
Deployments(**repository_args_with_start_date),
Events(**repository_args_with_start_date),
IssueCommentReactions(**repository_args_with_start_date),
IssueEvents(**repository_args_with_start_date),
IssueLabels(**repository_args),
IssueMilestones(**repository_args_with_start_date),
IssueReactions(**repository_args_with_start_date),
Issues(**repository_args_with_start_date),
Organizations(**organization_args),
ProjectCards(project_columns_stream, **repository_args_with_start_date),
project_columns_stream,
projects_stream,
PullRequestCommentReactions(**repository_args_with_start_date),
PullRequestCommits(parent=pull_requests_stream, **repository_args),
PullRequestStats(**repository_args_with_start_date),
ProjectsV2(**repository_args_with_start_date),
pull_requests_stream,
Releases(**repository_args_with_start_date),
Repositories(**organization_args_with_start_date, pattern=pattern),
ReviewComments(**repository_args_with_start_date),
Reviews(**repository_args_with_start_date),
Stargazers(**repository_args_with_start_date),
Tags(**repository_args),
teams_stream,
team_members_stream,
Users(**organization_args),
Workflows(**repository_args_with_start_date),
workflow_runs_stream,
WorkflowJobs(parent=workflow_runs_stream, **repository_args_with_start_date),
TeamMemberships(parent=team_members_stream, **repository_args),
]
| SourceGithub |
python | pypa__warehouse | warehouse/integrations/secrets/utils.py | {
"start": 3259,
"end": 4728
} | class ____:
def __init__(self, token: str, public_url: str, source: str | None = None):
self.token = token
self.public_url = public_url
self.source = source
@classmethod
def from_api_record(cls, record, *, matchers=TOKEN_LEAK_MATCHERS):
if not isinstance(record, dict):
raise InvalidTokenLeakRequestError(
f"Record is not a dict but: {str(record)[:100]}", reason="format"
)
missing_keys = sorted({"token", "type", "url"} - set(record))
if missing_keys:
raise InvalidTokenLeakRequestError(
f"Record is missing attribute(s): {', '.join(missing_keys)}",
reason="format",
)
matcher_code = record["type"]
matcher = matchers.get(matcher_code)
if not matcher:
raise InvalidTokenLeakRequestError(
f"Matcher with code {matcher_code} not found. "
f"Available codes are: {', '.join(matchers)}",
reason="invalid_matcher",
)
try:
extracted_token = matcher.extract(record["token"])
except ExtractionFailedError:
raise InvalidTokenLeakRequestError(
"Cannot extract token from received match", reason="extraction"
)
return cls(
token=extracted_token, public_url=record["url"], source=record.get("source")
)
| TokenLeakDisclosureRequest |
python | pdm-project__pdm | src/pdm/installers/installers.py | {
"start": 3143,
"end": 7707
} | class ____(SchemeDictionaryDestination):
def __init__(
self,
*args: Any,
link_method: LinkMethod = "copy",
rename_pth: bool = False,
**kwargs: Any,
) -> None:
super().__init__(*args, **kwargs)
self.link_method = link_method
self.rename_pth = rename_pth
def write_to_fs(self, scheme: Scheme, path: str, stream: BinaryIO, is_executable: bool) -> RecordEntry:
from installer.records import Hash
from installer.utils import copyfileobj_with_hashing, make_file_executable
target_path = os.path.join(self.scheme_dict[scheme], path)
if os.path.exists(target_path):
os.unlink(target_path)
os.makedirs(os.path.dirname(target_path), exist_ok=True)
if self.rename_pth and target_path.endswith(".pth") and "/" not in path:
# Postpone the creation of pth files since it may cause race condition
# when multiple packages are installed at the same time.
target_path += ".pdmtmp"
if self.link_method == "copy" or not hasattr(stream, "name"):
with open(target_path, "wb") as f:
hash_, size = copyfileobj_with_hashing(stream, f, self.hash_algorithm)
else:
src_path = stream.name
# create links, we don't need the stream anymore
stream.close()
if self.link_method == "symlink":
os.symlink(src_path, target_path)
else: # hardlink
os.link(src_path, target_path)
hash_ = ""
size = os.path.getsize(target_path)
if is_executable:
make_file_executable(target_path)
return RecordEntry(path, Hash(self.hash_algorithm, hash_), size)
def _get_link_method(cache_method: str) -> LinkMethod:
from pdm import utils
if "symlink" in cache_method and utils.fs_supports_link_method("symlink"):
return "symlink"
if "link" in cache_method and utils.fs_supports_link_method("link"):
return "hardlink"
return "copy"
def install_wheel(
wheel: Path,
environment: BaseEnvironment,
direct_url: dict[str, Any] | None = None,
install_links: bool = False,
rename_pth: bool = False,
requested: bool = False,
) -> str:
"""Only create .pth files referring to the cached package.
If the cache doesn't exist, create one.
"""
interpreter = str(environment.interpreter.executable)
script_kind = environment.script_kind
# the cache_method can be any of "symlink", "hardlink", "copy" and "pth"
cache_method: str = environment.project.config["install.cache_method"]
dist_name = wheel.name.split("-")[0]
link_method: LinkMethod | None
if not install_links or dist_name == "editables":
link_method = "copy"
else:
link_method = _get_link_method(cache_method)
additional_metadata: dict[str, bytes] = {"INSTALLER": b"pdm"}
if direct_url is not None:
additional_metadata["direct_url.json"] = json.dumps(direct_url, indent=2).encode()
if requested:
additional_metadata["REQUESTED"] = b""
destination = InstallDestination(
scheme_dict=environment.get_paths(dist_name),
interpreter=interpreter,
script_kind=script_kind,
link_method=link_method,
rename_pth=rename_pth,
)
if install_links:
package = environment.project.package_cache.cache_wheel(wheel)
source = PackageWheelSource(package)
if link_method == "symlink":
# Track usage when symlink is used
additional_metadata["REFER_TO"] = package.path.as_posix().encode()
dist_info_dir = install(source, destination=destination, additional_metadata=additional_metadata)
if link_method == "symlink":
package.add_referrer(dist_info_dir)
else:
with WheelFile.open(wheel) as source:
dist_info_dir = install(source, destination=destination, additional_metadata=additional_metadata)
return dist_info_dir
def install(
source: WheelSource, destination: WheelDestination, additional_metadata: dict[str, bytes] | None = None
) -> str:
"""A lower level installation method that is copied from installer
but is controlled by extra parameters.
Return the .dist-info path
"""
_install(source, destination, additional_metadata=additional_metadata or {})
root_scheme = _process_WHEEL_file(source)
return os.path.join(destination.scheme_dict[root_scheme], source.dist_info_dir)
| InstallDestination |
python | indygreg__python-build-standalone | src/github_api_tester.py | {
"start": 4474,
"end": 11163
} | class ____:
release_id: int
tag_name: str
assets: list = dataclasses.field(default_factory=list)
# fault0 and fault1 are called before and after receiving the first
# chunk of a PUT request, respectively. Each is called once per
# release - the first upload that hits it will disarm it.
fault0: Callable[[], None] | None = None
fault1: Callable[[], None] | None = None
def render(self) -> dict:
upload_asset = quart.url_for(
"upload_asset", release=self.release_id, _external=True
)
return {
"url": request.url,
"html_url": "https://github.invalid/unneeded",
"assets_url": "https://github.invalid/unneeded",
"upload_url": upload_asset + "{?name,label}",
"id": self.release_id,
"node_id": "fakenode",
"tag_name": self.tag_name,
"target_commitish": "main",
"draft": False,
"prerelease": True,
"assets": [i.render() for i in self.assets],
}
releases = [
Release(1, "basic"),
Release(11, "early-drop", fault0=drop_connection),
Release(12, "late-drop", fault1=drop_connection),
Release(4011, "early-401", fault0=lambda: quart.abort(401)),
Release(4012, "late-401", fault1=lambda: quart.abort(401)),
Release(4031, "early-403", fault0=lambda: quart.abort(403)),
Release(4032, "late-403", fault1=lambda: quart.abort(403)),
Release(5001, "early-500", fault0=lambda: quart.abort(500)),
Release(5002, "late-500", fault1=lambda: quart.abort(500)),
]
def get_release(*, tag=None, release=None) -> Release:
if tag is not None:
condition = lambda r: r.tag_name == tag
elif release is not None:
condition = lambda r: r.release_id == release
else:
raise TypeError("tag or release must be set")
for r in releases:
if condition(r):
return r
quart.abort(404, response=quart.jsonify({"message": "Not Found", "status": "404"}))
# GitHub API functions
@app.route("/repos/<org>/<repo>/releases/tags/<tag>")
async def get_release_by_tag(org, repo, tag):
return get_release(tag=tag).render()
@app.route("/repos/<org>/<repo>/releases/<int:release>")
async def get_release_by_id(org, repo, release):
return get_release(release=release).render()
@app.put("/upload/<int:release>/assets")
async def upload_asset(release):
filename = request.args["name"]
release = get_release(release=release)
if (fault := release.fault0) is not None:
logging.info(f"{filename}: injecting fault0")
release.fault0 = None
return await fault()
logging.info(f"{filename}: upload begin")
upload = Upload(filename, request.args.get("label"))
async for chunk in request.body:
logging.debug(f"{filename}: {len(chunk)=}")
upload.update(chunk)
if (fault := release.fault1) is not None:
if "SHA256" not in filename:
logging.info(f"{filename}: injecting fault1")
release.fault1 = None
return await fault()
asset = upload.to_asset()
logging.info(f"{filename}: upload complete, {asset.sha256=}")
release.assets.append(asset)
return asset.render()
@app.route("/get_asset/<int:id>")
@app.route("/repos/<org>/<repo>/releases/assets/<int:id>")
async def get_asset(id, org=None, repo=None):
try:
asset = Asset._ASSETS[id]
except IndexError:
quart.abort(
404, response=quart.jsonify({"message": "Not Found", "status": "404"})
)
if "application/octet-stream" in request.accept_mimetypes:
if asset.contents is None:
print(
f"USAGE ERROR: Received request for contents of {asset.filename=} which was not stored"
)
return "Did not store contents", 410
return asset.contents
else:
return asset.render()
# Generic upload function, useful for testing clients in isolation
@app.put("/file/<path:path>")
async def upload_file(path):
logging.info(f"{path}: upload begin")
s = hashlib.sha256()
async for chunk in request.body:
logging.debug(f"{path}: {len(chunk)=}")
if "drop" in request.args:
await drop_connection()
s.update(chunk)
digest = s.hexdigest()
logging.info(f"{path}: {digest=}")
return f"{digest} {path}\n", 500
# Test cases
@pytest.fixture
async def server(nursery):
await nursery.start(app.run_task)
FILENAME = "cpython-3.0.0-x86_64-unknown-linux-gnu-install_only-19700101T1234.tar.gz"
SHA256_20MEG = "9e21c61969cd3e077a1b2b58ddb583b175e13c6479d2d83912eaddc23c0cdd52"
@pytest.fixture(scope="session")
def upload_release_distributions(tmp_path_factory):
dist = tmp_path_factory.mktemp("dist")
filename = dist / FILENAME
filename.touch()
os.truncate(filename, 20_000_000)
async def upload_release_distributions(*args):
return await trio.run_process(
[
"cargo",
"run",
"--",
"upload-release-distributions",
"--github-uri",
"http://localhost:5000",
"--token",
"no-token-needed",
"--dist",
dist,
"--datetime",
"19700101T1234",
"--ignore-missing",
]
+ list(args)
)
return upload_release_distributions
# TODO: test all of [r.tag_name for r in releases]
TAGS_TO_TEST = ["basic", "early-drop", "late-drop", "early-403", "late-403"]
@pytest.mark.parametrize("tag", TAGS_TO_TEST)
async def test_upload(server, upload_release_distributions, tag):
with trio.fail_after(300):
await upload_release_distributions("--tag", tag)
release = get_release(tag=tag)
assets = sorted(release.assets, key=lambda a: a.name)
assert len(assets) == 2
assert assets[0].name == "SHA256SUMS"
filename = FILENAME.replace("3.0.0", f"3.0.0+{tag}").replace("-19700101T1234", "")
assert assets[1].name == filename
assert assets[1].sha256 == SHA256_20MEG
assert assets[0].contents == f"{SHA256_20MEG} {filename}\n".encode()
# Work around https://github.com/pgjones/hypercorn/issues/238 not being in a release
# Without it, test failures are unnecessarily noisy
hypercorn.trio.lifespan.LifespanFailureError = trio.Cancelled
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "serve":
logging.basicConfig(level=logging.INFO)
app.run("0.0.0.0")
else:
pytest.main(["-o", "trio_mode=true", __file__] + sys.argv[1:])
| Release |
python | sympy__sympy | sympy/polys/solvers.py | {
"start": 519,
"end": 625
} | class ____(Exception):
"""Raised by solve_lin_sys for nonlinear equations"""
pass
| PolyNonlinearError |
python | spack__spack | lib/spack/spack/container/writers.py | {
"start": 4079,
"end": 11048
} | class ____(tengine.Context):
"""Generic context used to instantiate templates of recipes that
install software in a common location and make it available
directly via PATH.
"""
# Must be set by derived classes
template_name: Optional[str] = None
def __init__(self, config, last_phase):
self.config = config[ev.TOP_LEVEL_KEY]
self.container_config = self.config["container"]
# Operating system tag as written in the configuration file
self.operating_system_key = self.container_config["images"].get("os")
# Get base images and verify the OS
bootstrap, build, final = _stage_base_images(self.container_config["images"])
self.bootstrap_image = bootstrap
self.build_image = build
self.final_image = final
# Record the last phase
self.last_phase = last_phase
@tengine.context_property
def depfile(self):
return self.container_config.get("depfile", False)
@tengine.context_property
def run(self):
"""Information related to the run image."""
Run = namedtuple("Run", ["image"])
return Run(image=self.final_image)
@tengine.context_property
def build(self):
"""Information related to the build image."""
Build = namedtuple("Build", ["image"])
return Build(image=self.build_image)
@tengine.context_property
def strip(self):
"""Whether or not to strip binaries in the image"""
return self.container_config.get("strip", True)
@tengine.context_property
def paths(self):
"""Important paths in the image"""
Paths = namedtuple("Paths", ["environment", "store", "view_parent", "view", "former_view"])
return Paths(
environment="/opt/spack-environment",
store="/opt/software",
view_parent="/opt/views",
view="/opt/views/view",
former_view="/opt/view", # /opt/view -> /opt/views/view for backward compatibility
)
@tengine.context_property
def manifest(self):
"""The spack.yaml file that should be used in the image"""
# Copy in the part of spack.yaml prescribed in the configuration file
manifest = copy.deepcopy(self.config)
manifest.pop("container")
# Ensure that a few paths are where they need to be
manifest.setdefault("config", syaml.syaml_dict())
manifest["config"]["install_tree"] = {"root": self.paths.store}
manifest["view"] = self.paths.view
manifest = {"spack": manifest}
# Validate the manifest file
spack.vendor.jsonschema.validate(manifest, schema=spack.schema.env.schema)
return syaml.dump(manifest, default_flow_style=False).strip()
@tengine.context_property
def os_packages_final(self):
"""Additional system packages that are needed at run-time."""
try:
return self._os_packages_for_stage("final")
except Exception as e:
msg = f"an error occurred while rendering the 'final' stage of the image: {e}"
raise spack.error.SpackError(msg) from e
@tengine.context_property
def os_packages_build(self):
"""Additional system packages that are needed at build-time."""
try:
return self._os_packages_for_stage("build")
except Exception as e:
msg = f"an error occurred while rendering the 'build' stage of the image: {e}"
raise spack.error.SpackError(msg) from e
@tengine.context_property
def os_package_update(self):
"""Whether or not to update the OS package manager cache."""
os_packages = self.container_config.get("os_packages", {})
return os_packages.get("update", True)
def _os_packages_for_stage(self, stage):
os_packages = self.container_config.get("os_packages", {})
package_list = os_packages.get(stage, None)
return self._package_info_from(package_list)
def _package_info_from(self, package_list):
"""Helper method to pack a list of packages with the additional
information required by the template.
Args:
package_list: list of packages
Returns:
Enough information to know how to update the cache, install
a list of packages, and clean in the end.
"""
if not package_list:
return package_list
image_config = self.container_config["images"]
image = image_config.get("build", None)
if image is None:
os_pkg_manager = os_package_manager_for(image_config["os"])
else:
os_pkg_manager = self._os_pkg_manager()
update, install, clean = commands_for(os_pkg_manager)
Packages = namedtuple("Packages", ["update", "install", "list", "clean"])
return Packages(update=update, install=install, list=package_list, clean=clean)
def _os_pkg_manager(self):
try:
os_pkg_manager = self.container_config["os_packages"]["command"]
except KeyError:
msg = (
"cannot determine the OS package manager to use.\n\n\tPlease add an "
"appropriate 'os_packages:command' entry to the spack.yaml manifest file\n"
)
raise spack.error.SpackError(msg)
return os_pkg_manager
@tengine.context_property
def labels(self):
return self.container_config.get("labels", {})
@tengine.context_property
def bootstrap(self):
"""Information related to the build image."""
images_config = self.container_config["images"]
bootstrap_recipe = None
if self.bootstrap_image:
config_args = _spack_checkout_config(images_config)
command = checkout_command(*config_args)
template_path = bootstrap_template_for(self.operating_system_key)
env = tengine.make_environment()
context = {"bootstrap": {"image": self.bootstrap_image, "spack_checkout": command}}
bootstrap_recipe = env.get_template(template_path).render(**context)
Bootstrap = namedtuple("Bootstrap", ["image", "recipe"])
return Bootstrap(image=self.bootstrap_image, recipe=bootstrap_recipe)
@tengine.context_property
def render_phase(self):
render_bootstrap = bool(self.bootstrap_image)
render_build = not (self.last_phase == "bootstrap")
render_final = self.last_phase in (None, "final")
Render = namedtuple("Render", ["bootstrap", "build", "final"])
return Render(bootstrap=render_bootstrap, build=render_build, final=render_final)
def __call__(self):
"""Returns the recipe as a string"""
env = tengine.make_environment()
template_name = self.container_config.get("template", self.template_name)
t = env.get_template(template_name)
return t.render(**self.to_dict())
@writer("docker")
| PathContext |
python | bokeh__bokeh | src/bokeh/models/widgets/sliders.py | {
"start": 2305,
"end": 4076
} | class ____(Widget):
""" """
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
try:
# synchronize the value of a readonly property `value_throttled`
self.lookup("value_throttled")._set(self, Undefined, self.value)
except UnsetValueError:
pass
except AttributeError:
# TODO Remove this when proper support for property overrides is
# implemented. For now this is required to make defaults' tests
# work, because we depend there on model instances to provide
# "default" values.
pass
# TODO value = Required(GenericType, help="""
# Initial or selected range.
# """)
# TODO value_throttled = Readonly(GenericType, help="""
# Initial or selected value, throttled according to report only on mouseup.
# """)
orientation = Enum("horizontal", "vertical", help="""
Orient the slider either horizontally (default) or vertically.
""")
title = Nullable(String, default="", help="""
The slider's label (supports :ref:`math text <ug_styling_mathtext>`).
""")
show_value = Bool(default=True, help="""
Whether or not show slider's value.
""")
direction = Enum("ltr", "rtl", help="""
""")
tooltips = Bool(default=True, help="""
Display the slider's current value in a tooltip.
""")
bar_color = Color(default="#e6e6e6", help="""
""")
width = Override(default=300)
@error(EQUAL_SLIDER_START_END)
def _check_missing_dimension(self):
if hasattr(self, 'start') and hasattr(self, 'end'):
if self.start == self.end:
return f"{self!s} with title {self.title!s}"
@abstract
| AbstractSlider |
python | pytorch__pytorch | torch/_dynamo/variables/higher_order_ops.py | {
"start": 109265,
"end": 109637
} | class ____(UserFunctionVariable):
def call_function(
self,
tx: "InstructionTranslator",
args: "list[VariableTracker]",
kwargs: "dict[str, VariableTracker]",
) -> "VariableTracker":
return super().call_function(tx, args, kwargs)
def should_allow_nested_graph_breaks(self):
return False
| FunctorchHigherOrderVariable |
python | encode__django-rest-framework | tests/test_permissions.py | {
"start": 12688,
"end": 13191
} | class ____(generics.RetrieveUpdateDestroyAPIView):
serializer_class = BasicPermSerializer
authentication_classes = [authentication.BasicAuthentication]
permission_classes = [ViewObjectPermissions]
def get_queryset(self):
return BasicPermModel.objects.all()
get_queryset_object_permissions_view = GetQuerysetObjectPermissionInstanceView.as_view()
@unittest.skipUnless('guardian' in settings.INSTALLED_APPS, 'django-guardian not installed')
| GetQuerysetObjectPermissionInstanceView |
python | spack__spack | lib/spack/spack/version/version_types.py | {
"start": 34221,
"end": 48415
} | class ____(VersionType):
"""Sorted, non-redundant list of Version and ClosedOpenRange elements."""
versions: List[VersionType]
def __init__(self, vlist: Optional[Union[str, VersionType, Iterable]] = None):
if vlist is None:
self.versions = []
elif isinstance(vlist, str):
vlist = from_string(vlist)
if isinstance(vlist, VersionList):
self.versions = vlist.versions
else:
self.versions = [vlist]
elif isinstance(vlist, (ConcreteVersion, ClosedOpenRange)):
self.versions = [vlist]
elif isinstance(vlist, VersionList):
self.versions = vlist[:]
elif isinstance(vlist, Iterable):
self.versions = []
for v in vlist:
self.add(ver(v))
else:
raise TypeError(f"Cannot construct VersionList from {type(vlist)}")
def add(self, item: VersionType) -> None:
if isinstance(item, (StandardVersion, GitVersion)):
i = bisect_left(self, item)
# Only insert when prev and next are not intersected.
if (i == 0 or not item.intersects(self[i - 1])) and (
i == len(self) or not item.intersects(self[i])
):
self.versions.insert(i, item)
elif isinstance(item, ClosedOpenRange):
i = bisect_left(self, item)
# Note: can span multiple concrete versions to the left (as well as to the right).
# For instance insert 1.2: into [1.2, hash=1.2, 1.3, 1.4:1.5]
# would bisect at i = 1 and merge i = 0 too.
while i > 0:
union = item._union_if_not_disjoint(self[i - 1])
if union is None: # disjoint
break
item = union
del self.versions[i - 1]
i -= 1
while i < len(self):
union = item._union_if_not_disjoint(self[i])
if union is None:
break
item = union
del self.versions[i]
self.versions.insert(i, item)
elif isinstance(item, VersionList):
for v in item:
self.add(v)
else:
raise TypeError("Can't add %s to VersionList" % type(item))
@property
def concrete(self) -> Optional[ConcreteVersion]:
return self[0] if len(self) == 1 and isinstance(self[0], ConcreteVersion) else None
@property
def concrete_range_as_version(self) -> Optional[ConcreteVersion]:
"""Like concrete, but collapses VersionRange(x, x) to Version(x).
This is just for compatibility with old Spack."""
if len(self) != 1:
return None
v = self[0]
if isinstance(v, ConcreteVersion):
return v
if isinstance(v, ClosedOpenRange) and _next_version(v.lo) == v.hi:
return v.lo
return None
def copy(self) -> "VersionList":
return VersionList(self)
def lowest(self) -> Optional[StandardVersion]:
"""Get the lowest version in the list."""
return next((v for v in self.versions if isinstance(v, StandardVersion)), None)
def highest(self) -> Optional[StandardVersion]:
"""Get the highest version in the list."""
return next((v for v in reversed(self.versions) if isinstance(v, StandardVersion)), None)
def highest_numeric(self) -> Optional[StandardVersion]:
"""Get the highest numeric version in the list."""
numeric = (
v
for v in reversed(self.versions)
if isinstance(v, StandardVersion) and not v.isdevelop()
)
return next(numeric, None)
def preferred(self) -> Optional[StandardVersion]:
"""Get the preferred (latest) version in the list."""
return self.highest_numeric() or self.highest()
def satisfies(self, other: VersionType) -> bool:
# This exploits the fact that version lists are "reduced" and normalized, so we can
# never have a list like [1:3, 2:4] since that would be normalized to [1:4]
if isinstance(other, VersionList):
return all(any(lhs.satisfies(rhs) for rhs in other) for lhs in self)
if isinstance(other, (ConcreteVersion, ClosedOpenRange)):
return all(lhs.satisfies(other) for lhs in self)
raise TypeError(f"'satisfies()' not supported for instances of {type(other)}")
def intersects(self, other: VersionType) -> bool:
if isinstance(other, VersionList):
s = o = 0
while s < len(self) and o < len(other):
if self[s].intersects(other[o]):
return True
elif self[s] < other[o]:
s += 1
else:
o += 1
return False
if isinstance(other, (ClosedOpenRange, StandardVersion)):
return any(v.intersects(other) for v in self)
raise TypeError(f"'intersects()' not supported for instances of {type(other)}")
def to_dict(self) -> Dict:
"""Generate human-readable dict for YAML."""
if self.concrete:
return {"version": str(self[0])}
return {"versions": [str(v) for v in self]}
@staticmethod
def from_dict(dictionary) -> "VersionList":
"""Parse dict from to_dict."""
if "versions" in dictionary:
return VersionList(dictionary["versions"])
elif "version" in dictionary:
return VersionList([Version(dictionary["version"])])
raise ValueError("Dict must have 'version' or 'versions' in it.")
def update(self, other: "VersionList") -> None:
self.add(other)
def union(self, other: VersionType) -> VersionType:
result = self.copy()
result.add(other)
return result
def intersection(self, other: VersionType) -> "VersionList":
result = VersionList()
if isinstance(other, VersionList):
for lhs, rhs in ((self, other), (other, self)):
for x in lhs:
i = bisect_left(rhs.versions, x)
if i > 0:
result.add(rhs[i - 1].intersection(x))
if i < len(rhs):
result.add(rhs[i].intersection(x))
return result
else:
return self.intersection(VersionList(other))
def intersect(self, other: VersionType) -> bool:
"""Intersect this spec's list with other.
Return True if the spec changed as a result; False otherwise
"""
isection = self.intersection(other)
changed = isection.versions != self.versions
self.versions = isection.versions
return changed
# typing this and getitem are a pain in Python 3.6
def __contains__(self, other):
if isinstance(other, (ClosedOpenRange, StandardVersion)):
i = bisect_left(self, other)
return (i > 0 and other in self[i - 1]) or (i < len(self) and other in self[i])
if isinstance(other, VersionList):
return all(item in self for item in other)
return False
def __getitem__(self, index):
return self.versions[index]
def __iter__(self) -> Iterator:
return iter(self.versions)
def __reversed__(self) -> Iterator:
return reversed(self.versions)
def __len__(self) -> int:
return len(self.versions)
def __bool__(self) -> bool:
return bool(self.versions)
def __eq__(self, other) -> bool:
if isinstance(other, VersionList):
return self.versions == other.versions
return False
def __ne__(self, other) -> bool:
if isinstance(other, VersionList):
return self.versions != other.versions
return False
def __lt__(self, other) -> bool:
if isinstance(other, VersionList):
return self.versions < other.versions
return NotImplemented
def __le__(self, other) -> bool:
if isinstance(other, VersionList):
return self.versions <= other.versions
return NotImplemented
def __ge__(self, other) -> bool:
if isinstance(other, VersionList):
return self.versions >= other.versions
return NotImplemented
def __gt__(self, other) -> bool:
if isinstance(other, VersionList):
return self.versions > other.versions
return NotImplemented
def __hash__(self) -> int:
return hash(tuple(self.versions))
def __str__(self) -> str:
if not self.versions:
return ""
return ",".join(f"={v}" if type(v) is StandardVersion else str(v) for v in self.versions)
def __repr__(self) -> str:
return str(self.versions)
def _next_str(s: str) -> str:
"""Produce the next string of A-Z and a-z characters"""
return (
(s + "A")
if (len(s) == 0 or s[-1] == "z")
else s[:-1] + ("a" if s[-1] == "Z" else chr(ord(s[-1]) + 1))
)
def _prev_str(s: str) -> str:
"""Produce the previous string of A-Z and a-z characters"""
return (
s[:-1]
if (len(s) == 0 or s[-1] == "A")
else s[:-1] + ("Z" if s[-1] == "a" else chr(ord(s[-1]) - 1))
)
def _next_version_str_component(v: VersionStrComponent) -> VersionStrComponent:
"""
Produce the next VersionStrComponent, where
masteq -> mastes
master -> main
"""
# First deal with the infinity case.
data = v.data
if isinstance(data, int):
return VersionStrComponent(data + 1)
# Find the next non-infinity string.
while True:
data = _next_str(data)
if data not in infinity_versions:
break
return VersionStrComponent(data)
def _prev_version_str_component(v: VersionStrComponent) -> VersionStrComponent:
"""
Produce the previous VersionStrComponent, where
mastes -> masteq
master -> head
"""
# First deal with the infinity case. Allow underflows
data = v.data
if isinstance(data, int):
return VersionStrComponent(data - 1)
# Find the next string.
while True:
data = _prev_str(data)
if data not in infinity_versions:
break
return VersionStrComponent(data)
def _next_version(v: StandardVersion) -> StandardVersion:
release, prerelease = v.version
separators = v.separators
prerelease_type = prerelease[0]
if prerelease_type != FINAL:
prerelease = (prerelease_type, prerelease[1] + 1 if len(prerelease) > 1 else 0)
elif len(release) == 0:
release = (VersionStrComponent("A"),)
separators = ("",)
elif isinstance(release[-1], VersionStrComponent):
release = release[:-1] + (_next_version_str_component(release[-1]),)
else:
release = release[:-1] + (release[-1] + 1,)
# Avoid constructing a string here for performance. Instead, pass "" to
# StandardVersion to lazily stringify.
return StandardVersion("", (release, prerelease), separators)
def _prev_version(v: StandardVersion) -> StandardVersion:
# this function does not deal with underflow, because it's always called as
# _prev_version(_next_version(v)).
release, prerelease = v.version
separators = v.separators
prerelease_type = prerelease[0]
if prerelease_type != FINAL:
prerelease = (
(prerelease_type,) if prerelease[1] == 0 else (prerelease_type, prerelease[1] - 1)
)
elif len(release) == 0:
return v
elif isinstance(release[-1], VersionStrComponent):
release = release[:-1] + (_prev_version_str_component(release[-1]),)
else:
release = release[:-1] + (release[-1] - 1,)
# Avoid constructing a string here for performance. Instead, pass "" to
# StandardVersion to lazily stringify.
return StandardVersion("", (release, prerelease), separators)
def Version(string: Union[str, int]) -> Union[StandardVersion, GitVersion]:
if not isinstance(string, (str, int)):
raise TypeError(f"Cannot construct a version from {type(string)}")
string = str(string)
if is_git_version(string):
return GitVersion(string)
return StandardVersion.from_string(str(string))
def VersionRange(lo: Union[str, StandardVersion], hi: Union[str, StandardVersion]):
lo = lo if isinstance(lo, StandardVersion) else StandardVersion.from_string(lo)
hi = hi if isinstance(hi, StandardVersion) else StandardVersion.from_string(hi)
return ClosedOpenRange.from_version_range(lo, hi)
def from_string(string: str) -> VersionType:
"""Converts a string to a version object. This is private. Client code should use ver()."""
string = string.replace(" ", "")
# VersionList
if "," in string:
return VersionList(list(map(from_string, string.split(","))))
# ClosedOpenRange
elif ":" in string:
s, e = string.split(":")
lo = StandardVersion.typemin() if s == "" else StandardVersion.from_string(s)
hi = StandardVersion.typemax() if e == "" else StandardVersion.from_string(e)
return VersionRange(lo, hi)
# StandardVersion
elif string.startswith("="):
# @=1.2.3 is an exact version
return Version(string[1:])
elif is_git_version(string):
return GitVersion(string)
else:
# @1.2.3 is short for 1.2.3:1.2.3
v = StandardVersion.from_string(string)
return VersionRange(v, v)
def ver(obj: Union[VersionType, str, list, tuple, int, float]) -> VersionType:
"""Returns a :class:`~spack.version.ClosedOpenRange`, :class:`~spack.version.StandardVersion`,
:class:`~spack.version.GitVersion`, or :class:`~spack.version.VersionList` from the argument.
"""
if isinstance(obj, VersionType):
return obj
elif isinstance(obj, str):
return from_string(obj)
elif isinstance(obj, (list, tuple)):
return VersionList(obj)
elif isinstance(obj, (int, float)):
return from_string(str(obj))
else:
raise TypeError("ver() can't convert %s to version!" % type(obj))
| VersionList |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_drypython_returns.py | {
"start": 2496,
"end": 2577
} | class ____(_FirstBase[int, str], _SecondBase[A, B]):
pass
| OneGenericOneConrete1 |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_finetuning_callback.py | {
"start": 12696,
"end": 13011
} | class ____(BaseFinetuning):
def freeze_before_training(self, pl_module):
self.freeze(pl_module.layer[:3])
def finetune_function(self, pl_module, epoch, optimizer):
if epoch >= 1:
self.unfreeze_and_add_param_group(pl_module.layer[epoch - 1], optimizer)
| TestCallbacksRestoreCallback |
python | keras-team__keras | keras/src/quantizers/gptq_core_test.py | {
"start": 3186,
"end": 10539
} | class ____(testing.TestCase):
@parameterized.named_parameters(
[("strided", "strided"), ("linspace", "linspace"), ("random", "random")]
)
def test_shape_and_dtype_strings(self, strategy):
"""Test the shape and dtype of the output for string inputs."""
tok = MockTokenizer()
dataset = ["a b c d e f g", "h i j k"]
seq_len, n = 5, 7
out = get_dataloader(
tok, seq_len, dataset, num_samples=n, strategy=strategy, seed=123
)
self.assertEqual(out.shape, (n, 1, seq_len))
self.assertEqual(out.dtype, np.int32)
@parameterized.named_parameters(
[("strided", "strided"), ("linspace", "linspace"), ("random", "random")]
)
def test_shape_and_dtype_pretokenized(self, strategy):
"""Test the shape and dtype of the output for pre-tokenized inputs."""
tok = MockTokenizer()
# Pre-tokenized inputs; mixed shapes (1, L) and (L,)
seqs = [
np.array([[1, 2, 3, 4]], dtype=np.int64),
np.array([5, 6], dtype=np.int64),
]
tok = MockTokenizer()
seq_len, n = 3, 4
out = get_dataloader(
tok, seq_len, seqs, num_samples=n, strategy=strategy, seed=7
)
self.assertEqual(out.shape, (n, 1, seq_len))
self.assertEqual(out.dtype, np.int32)
def test_strided_is_deterministic_for_same_args(self):
tok = MockTokenizer()
dataset = ["a b c d e", "f g h i j k"]
out1 = get_dataloader(
tok, 4, dataset, num_samples=6, strategy="strided", seed=99
)
out2 = get_dataloader(
tok, 4, dataset, num_samples=6, strategy="strided", seed=99
)
self.assertTrue(ops.all(ops.equal(out1, out2)))
def test_random_reproducibility_by_seed(self):
tok = MockTokenizer()
dataset = ["a b c d e", "f g h i j k"]
a = get_dataloader(
tok, 4, dataset, num_samples=6, strategy="random", seed=123
)
b = get_dataloader(
tok, 4, dataset, num_samples=6, strategy="random", seed=123
)
c = get_dataloader(
tok, 4, dataset, num_samples=6, strategy="random", seed=124
)
self.assertTrue(ops.all(ops.equal(a, b)))
self.assertFalse(ops.all(ops.equal(a, c)))
def test_linspace_windows_match_expected(self):
tok = MockTokenizer()
dataset = ["aa bb cc dd", "ee ff gg"]
seq_len, n = 3, 5
eos_id = None
all_tokens = build_all_tokens_strings(dataset, tok, eos_id=eos_id)
max_start = all_tokens.size - seq_len
expected_starts = np.linspace(0, max_start, n, dtype=np.int64)
expected = sliding_windows(all_tokens, seq_len)[expected_starts]
got = get_dataloader(
tok, seq_len, dataset, num_samples=n, strategy="linspace"
)
self.assertTrue(
ops.all(ops.equal(got[:, 0, :], expected.astype(np.int32)))
)
def test_strided_override_respected(self):
"""Tests that strided windows are disjoint and cover the input."""
tok = MockTokenizer()
# 20 tokens total
# with seq_len=4 and stride=4, we expect disjoint chunks
# in order (modulo offset)
dataset = [" ".join([f"t{i}" for i in range(20)])]
seq_len, n, stride = 4, 5, 4
out = get_dataloader(
tok,
seq_len,
dataset,
num_samples=n,
strategy="strided",
stride=stride,
seed=0,
)
# Validate that each sample is a contiguous run
# of length seq_len from the flattened stream
flat = build_all_tokens_strings(dataset, tok)
for s in out[:, 0, :]:
# Each window should appear as a slice in the flat stream
# (This is a soft check; exact start positions depend on offset.)
joined = " ".join(map(str, s.tolist()))
self.assertIn(joined, " ".join(map(str, flat.tolist())))
def test_eos_insertion_is_present_in_some_window_with_linspace(self):
tok = MockTokenizer()
dataset = ["aa aa", "bb bb"] # len = 5 + 1(EOS) + 5 = 11
eos = 9999
seq_len = 3
n = 3
out = get_dataloader(
tok,
seq_len,
dataset,
num_samples=n,
strategy="linspace",
eos_id=eos,
)
# linspace starts -> [0, 4, 8]; the middle window [4:7]
# includes EOS at 5
windows = out[:, 0, :]
self.assertTrue(
np.any(np.any(windows == eos, axis=1)),
"Expected EOS to appear in at least one sampled window with "
"linspace.",
)
def test_get_dataloader_error_scenarios(self):
"""Tests error cases for get_dataloader."""
with pytest.raises(ValueError, match="Provided dataset is empty"):
get_dataloader(
tokenizer=MockTokenizer(),
sequence_length=10,
dataset=[],
num_samples=10,
)
with self.assertRaisesRegex(
TypeError,
"The `dataset` argument must be an iterable.*Got type: str.*"
"Please pass the loaded dataset directly.",
):
get_dataloader(
tokenizer=MockTokenizer(),
sequence_length=10,
dataset="wikitext2",
num_samples=10,
)
def test_apply_gptq_on_multi_block_model(self):
"""Tests quantization on a model with multiple blocks."""
model = models.Sequential(
[
layers.Embedding(VOCAB_SIZE, 128),
TransformerBlock(),
TransformerBlock(),
]
)
model.build(input_shape=(None, 10))
config = GPTQConfig(
dataset=["test data"], tokenizer=MockTokenizer(), group_size=32
)
model.quantize("gptq", config=config)
@parameterized.named_parameters(
(
"no_embedding_layer",
models.Sequential([layers.Dense(10)]),
"Could not automatically find an embedding layer",
),
(
"no_transformer_blocks",
models.Sequential(
[layers.Embedding(VOCAB_SIZE, 10), layers.Dense(10)]
),
"Could not automatically find any transformer-like blocks",
),
(
"backbone_no_layers",
_get_model_with_backbone(has_transformer_layers=False),
"Could not automatically find any transformer-like blocks",
),
(
"backbone_no_embedding",
_get_model_with_backbone(embedding_name="wrong_name"),
"Could not automatically find an embedding layer in the model",
),
)
def test_apply_gptq_with_unsupported_architectures(
self, model, error_message
):
"""Tests that quantize fails correctly for various unsupported
model architectures."""
if not model.built:
model.build(input_shape=(None, 10))
config = GPTQConfig(dataset=["test"], tokenizer=MockTokenizer())
with self.assertRaisesRegex(ValueError, error_message):
model.quantize("gptq", config=config)
| TestGPTQCore |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_stats_summary.py | {
"start": 427,
"end": 28130
} | class ____(APITestCase, OutcomesSnubaTest):
_now = datetime.now(UTC).replace(hour=12, minute=27, second=28, microsecond=0)
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.org = self.organization
self.org.flags.allow_joinleave = False
self.org.save()
self.org2 = self.create_organization()
self.org3 = self.create_organization()
self.project = self.create_project(
name="bar", teams=[self.create_team(organization=self.org, members=[self.user])]
)
self.project2 = self.create_project(
name="foo", teams=[self.create_team(organization=self.org, members=[self.user])]
)
self.project3 = self.create_project(organization=self.org2)
self.user2 = self.create_user(is_superuser=False)
self.create_member(user=self.user2, organization=self.organization, role="member", teams=[])
self.create_member(user=self.user2, organization=self.org3, role="member", teams=[])
self.project4 = self.create_project(
name="users2sproj",
teams=[self.create_team(organization=self.org, members=[self.user2])],
)
self.store_outcomes(
{
"org_id": self.org.id,
"timestamp": self._now - timedelta(hours=1),
"project_id": self.project.id,
"outcome": Outcome.ACCEPTED,
"reason": "none",
"category": DataCategory.ERROR,
"quantity": 1,
},
5,
)
self.store_outcomes(
{
"org_id": self.org.id,
"timestamp": self._now - timedelta(hours=1),
"project_id": self.project.id,
"outcome": Outcome.ACCEPTED,
"reason": "none",
"category": DataCategory.DEFAULT, # test that this shows up under error
"quantity": 1,
}
)
self.store_outcomes(
{
"org_id": self.org.id,
"timestamp": self._now - timedelta(hours=1),
"project_id": self.project.id,
"outcome": Outcome.RATE_LIMITED,
"reason": "smart_rate_limit",
"category": DataCategory.ATTACHMENT,
"quantity": 1024,
}
)
self.store_outcomes(
{
"org_id": self.org.id,
"timestamp": self._now - timedelta(hours=1),
"project_id": self.project2.id,
"outcome": Outcome.RATE_LIMITED,
"reason": "smart_rate_limit",
"category": DataCategory.TRANSACTION,
"quantity": 1,
}
)
def do_request(self, query, user=None, org=None):
self.login_as(user=user or self.user)
url = reverse(
"sentry-api-0-organization-stats-summary",
kwargs={"organization_id_or_slug": (org or self.organization).slug},
)
return self.client.get(url, query, format="json")
def test_empty_request(self) -> None:
response = self.do_request({})
assert response.status_code == 400, response.content
assert response.data == {"detail": 'At least one "field" is required.'}
def test_inaccessible_project(self) -> None:
response = self.do_request({"project": [self.project3.id]})
assert response.status_code == 403, response.content
assert response.data == {"detail": "You do not have permission to perform this action."}
def test_no_projects_available(self) -> None:
response = self.do_request(
{
"groupBy": ["project"],
"statsPeriod": "1d",
"interval": "1d",
"field": ["sum(quantity)"],
"category": ["error", "transaction"],
},
user=self.user2,
org=self.org3,
)
assert response.status_code == 400, response.content
assert response.data == {
"detail": "No projects available",
}
def test_unknown_field(self) -> None:
response = self.do_request(
{
"field": ["summ(qarntenty)"],
"statsPeriod": "1d",
"interval": "1d",
}
)
assert response.status_code == 400, response.content
assert response.data == {
"detail": 'Invalid field: "summ(qarntenty)"',
}
def test_no_end_param(self) -> None:
response = self.do_request(
{
"field": ["sum(quantity)"],
"interval": "1d",
"start": floor_to_utc_day(self._now).isoformat(),
}
)
assert response.status_code == 400, response.content
assert response.data == {"detail": "start and end are both required"}
@freeze_time(_now)
def test_future_request(self) -> None:
response = self.do_request(
{
"field": ["sum(quantity)"],
"interval": "1h",
"category": ["error"],
"start": self._now.replace(hour=15, minute=30, second=0).isoformat(),
"end": self._now.replace(hour=16, minute=30, second=0).isoformat(),
}
)
assert response.status_code == 200, response.content
assert response.data == {
"start": isoformat_z(self._now.replace(hour=12, minute=0, second=0)),
"end": isoformat_z(self._now.replace(hour=17, minute=0, second=0)),
"projects": [],
}
def test_unknown_category(self) -> None:
response = self.do_request(
{
"field": ["sum(quantity)"],
"statsPeriod": "1d",
"interval": "1d",
"category": "scoobydoo",
}
)
assert response.status_code == 400, response.content
assert response.data == {
"detail": 'Invalid category: "scoobydoo"',
}
def test_unknown_outcome(self) -> None:
response = self.do_request(
{
"field": ["sum(quantity)"],
"statsPeriod": "1d",
"interval": "1d",
"category": "error",
"outcome": "scoobydoo",
}
)
assert response.status_code == 400, response.content
assert response.data == {
"detail": 'Invalid outcome: "scoobydoo"',
}
def test_resolution_invalid(self) -> None:
self.login_as(user=self.user)
make_request = functools.partial(
self.client.get,
reverse("sentry-api-0-organization-stats-summary", args=[self.org.slug]),
)
response = make_request(
{
"statsPeriod": "1d",
"interval": "bad_interval",
}
)
assert response.status_code == 400, response.content
@freeze_time(_now)
def test_attachment_filter_only(self) -> None:
response = self.do_request(
{
"project": [-1],
"statsPeriod": "1d",
"interval": "1d",
"field": ["sum(quantity)"],
"category": ["error", "attachment"],
}
)
assert response.status_code == 400, response.content
assert response.data == {
"detail": "if filtering by attachment no other category may be present"
}
@freeze_time(_now)
def test_user_all_accessible(self) -> None:
response = self.do_request(
{
"project": self.project.id,
"statsPeriod": "1d",
"interval": "1d",
"field": ["sum(quantity)"],
"category": ["error", "transaction"],
},
user=self.user2,
)
assert response.status_code == 403
response = self.do_request(
{
"project": [-1],
"statsPeriod": "1d",
"interval": "1d",
"field": ["sum(quantity)"],
"category": ["error", "transaction"],
},
user=self.user2,
)
assert response.status_code == 200
assert response.data == {
"start": isoformat_z(floor_to_utc_day(self._now) - timedelta(days=1)),
"end": isoformat_z(floor_to_utc_day(self._now) + timedelta(days=1)),
"projects": [],
}
@freeze_time(_now)
def test_no_project_access(self) -> None:
user = self.create_user(is_superuser=False)
self.create_member(user=user, organization=self.organization, role="member", teams=[])
response = self.do_request(
{
"project": [self.project.id],
"statsPeriod": "1d",
"interval": "1d",
"category": ["error", "transaction"],
"field": ["sum(quantity)"],
},
org=self.organization,
user=user,
)
assert response.status_code == 403, response.content
assert response.data == {"detail": "You do not have permission to perform this action."}
@freeze_time(_now)
def test_open_membership_semantics(self) -> None:
self.org.flags.allow_joinleave = True
self.org.save()
response = self.do_request(
{
"project": [-1],
"statsPeriod": "1d",
"interval": "1d",
"field": ["sum(quantity)"],
"category": ["error", "transaction"],
"groupBy": ["project"],
},
user=self.user2,
)
assert response.status_code == 200
assert response.data == {
"start": isoformat_z(floor_to_utc_day(self._now) - timedelta(days=1)),
"end": isoformat_z(floor_to_utc_day(self._now) + timedelta(days=1)),
"projects": [
{
"id": self.project.id,
"slug": self.project.slug,
"stats": [
{
"category": "error",
"outcomes": {
"abuse": 0,
"accepted": 6,
"cardinality_limited": 0,
"client_discard": 0,
"filtered": 0,
"invalid": 0,
"rate_limited": 0,
},
"totals": {"dropped": 0, "sum(quantity)": 6},
}
],
},
{
"id": self.project2.id,
"slug": self.project2.slug,
"stats": [
{
"category": "transaction",
"outcomes": {
"abuse": 0,
"accepted": 0,
"cardinality_limited": 0,
"client_discard": 0,
"filtered": 0,
"invalid": 0,
"rate_limited": 1,
},
"totals": {"dropped": 1, "sum(quantity)": 1},
}
],
},
],
}
@freeze_time(_now)
def test_org_simple(self) -> None:
make_request = functools.partial(
self.client.get,
reverse("sentry-api-0-organization-stats-summary", args=[self.org.slug]),
)
response = make_request(
{
"statsPeriod": "2d",
"interval": "1d",
"field": ["sum(quantity)"],
}
)
assert response.status_code == 200, response.content
assert response.data == {
"start": isoformat_z(floor_to_utc_day(self._now) - timedelta(days=2)),
"end": isoformat_z(floor_to_utc_day(self._now) + timedelta(days=1)),
"projects": [
{
"id": self.project.id,
"slug": self.project.slug,
"stats": [
{
"category": "attachment",
"outcomes": {
"accepted": 0,
"filtered": 0,
"rate_limited": 1024,
"invalid": 0,
"abuse": 0,
"client_discard": 0,
"cardinality_limited": 0,
},
"totals": {"dropped": 1024, "sum(quantity)": 1024},
},
{
"category": "error",
"outcomes": {
"accepted": 6,
"filtered": 0,
"rate_limited": 0,
"invalid": 0,
"abuse": 0,
"client_discard": 0,
"cardinality_limited": 0,
},
"totals": {"dropped": 0, "sum(quantity)": 6},
},
],
},
{
"id": self.project2.id,
"slug": self.project2.slug,
"stats": [
{
"category": "transaction",
"outcomes": {
"accepted": 0,
"filtered": 0,
"rate_limited": 1,
"invalid": 0,
"abuse": 0,
"client_discard": 0,
"cardinality_limited": 0,
},
"totals": {"dropped": 1, "sum(quantity)": 1},
}
],
},
],
}
@freeze_time(_now)
def test_org_multiple_fields(self) -> None:
make_request = functools.partial(
self.client.get,
reverse("sentry-api-0-organization-stats-summary", args=[self.org.slug]),
)
response = make_request(
{
"statsPeriod": "2d",
"interval": "1d",
"field": ["sum(quantity)", "sum(times_seen)"],
}
)
assert response.status_code == 200, response.content
assert response.data == {
"start": isoformat_z(floor_to_utc_day(self._now) - timedelta(days=2)),
"end": isoformat_z(floor_to_utc_day(self._now) + timedelta(days=1)),
"projects": [
{
"id": self.project.id,
"slug": self.project.slug,
"stats": [
{
"category": "attachment",
"outcomes": {
"accepted": 0,
"filtered": 0,
"rate_limited": 1025,
"invalid": 0,
"abuse": 0,
"client_discard": 0,
"cardinality_limited": 0,
},
"totals": {
"dropped": 1025,
"sum(quantity)": 1024,
"sum(times_seen)": 1,
},
},
{
"category": "error",
"outcomes": {
"accepted": 12,
"filtered": 0,
"rate_limited": 0,
"invalid": 0,
"abuse": 0,
"client_discard": 0,
"cardinality_limited": 0,
},
"totals": {"dropped": 0, "sum(quantity)": 6, "sum(times_seen)": 6},
},
],
},
{
"id": self.project2.id,
"slug": self.project2.slug,
"stats": [
{
"category": "transaction",
"outcomes": {
"accepted": 0,
"filtered": 0,
"rate_limited": 2,
"invalid": 0,
"abuse": 0,
"client_discard": 0,
"cardinality_limited": 0,
},
"totals": {"dropped": 2, "sum(quantity)": 1, "sum(times_seen)": 1},
}
],
},
],
}
@freeze_time(_now)
def test_org_project_totals_per_project(self) -> None:
make_request = functools.partial(
self.client.get,
reverse("sentry-api-0-organization-stats-summary", args=[self.org.slug]),
)
response_per_group = make_request(
{
"statsPeriod": "1d",
"interval": "1h",
"field": ["sum(times_seen)"],
"category": ["error", "transaction"],
}
)
assert response_per_group.status_code == 200, response_per_group.content
assert response_per_group.data == {
"start": isoformat_z(
(self._now - timedelta(days=1)).replace(hour=12, minute=0, second=0)
),
"end": isoformat_z(self._now.replace(hour=13, minute=0, second=0)),
"projects": [
{
"id": self.project.id,
"slug": self.project.slug,
"stats": [
{
"category": "error",
"outcomes": {
"abuse": 0,
"accepted": 6,
"cardinality_limited": 0,
"client_discard": 0,
"filtered": 0,
"invalid": 0,
"rate_limited": 0,
},
"totals": {"dropped": 0, "sum(times_seen)": 6},
}
],
},
{
"id": self.project2.id,
"slug": self.project2.slug,
"stats": [
{
"category": "transaction",
"outcomes": {
"abuse": 0,
"accepted": 0,
"cardinality_limited": 0,
"client_discard": 0,
"filtered": 0,
"invalid": 0,
"rate_limited": 1,
},
"totals": {"dropped": 1, "sum(times_seen)": 1},
}
],
},
],
}
@freeze_time(_now)
def test_project_filter(self) -> None:
make_request = functools.partial(
self.client.get,
reverse("sentry-api-0-organization-stats-summary", args=[self.org.slug]),
)
response = make_request(
{
"project": self.project.id,
"statsPeriod": "1d",
"interval": "1d",
"field": ["sum(quantity)"],
"category": ["error", "transaction"],
}
)
assert response.status_code == 200, response.content
assert response.data == {
"start": isoformat_z(floor_to_utc_day(self._now) - timedelta(days=1)),
"end": isoformat_z(floor_to_utc_day(self._now) + timedelta(days=1)),
"projects": [
{
"id": self.project.id,
"slug": self.project.slug,
"stats": [
{
"category": "error",
"outcomes": {
"abuse": 0,
"accepted": 6,
"cardinality_limited": 0,
"client_discard": 0,
"filtered": 0,
"invalid": 0,
"rate_limited": 0,
},
"totals": {"dropped": 0, "sum(quantity)": 6},
},
],
},
],
}
@freeze_time(_now)
def test_reason_filter(self) -> None:
make_request = functools.partial(
self.client.get,
reverse("sentry-api-0-organization-stats-summary", args=[self.org.slug]),
)
response = make_request(
{
"statsPeriod": "1d",
"interval": "1d",
"field": ["sum(times_seen)"],
"reason": ["spike_protection"],
"groupBy": ["category"],
}
)
assert response.status_code == 200, response.content
assert response.data == {
"start": isoformat_z(floor_to_utc_day(self._now) - timedelta(days=1)),
"end": isoformat_z(floor_to_utc_day(self._now) + timedelta(days=1)),
"projects": [
{
"id": self.project.id,
"slug": self.project.slug,
"stats": [
{
"category": "attachment",
"reason": "spike_protection",
"outcomes": {
"accepted": 0,
"filtered": 0,
"rate_limited": 1,
"invalid": 0,
"abuse": 0,
"client_discard": 0,
"cardinality_limited": 0,
},
"totals": {"dropped": 1, "sum(times_seen)": 1},
}
],
},
{
"id": self.project2.id,
"slug": self.project2.slug,
"stats": [
{
"category": "transaction",
"reason": "spike_protection",
"outcomes": {
"accepted": 0,
"filtered": 0,
"rate_limited": 1,
"invalid": 0,
"abuse": 0,
"client_discard": 0,
"cardinality_limited": 0,
},
"totals": {"dropped": 1, "sum(times_seen)": 1},
}
],
},
],
}
@freeze_time(_now)
def test_outcome_filter(self) -> None:
make_request = functools.partial(
self.client.get,
reverse("sentry-api-0-organization-stats-summary", args=[self.org.slug]),
)
response = make_request(
{
"statsPeriod": "1d",
"interval": "1d",
"field": ["sum(quantity)"],
"outcome": "accepted",
"category": ["error", "transaction"],
}
)
assert response.status_code == 200, response.content
assert response.data == {
"start": isoformat_z(floor_to_utc_day(self._now) - timedelta(days=1)),
"end": isoformat_z(floor_to_utc_day(self._now) + timedelta(days=1)),
"projects": [
{
"id": self.project.id,
"slug": self.project.slug,
"stats": [
{
"category": "error",
"outcomes": {
"accepted": 6,
},
"totals": {"sum(quantity)": 6},
}
],
}
],
}
@freeze_time(_now)
def test_category_filter(self) -> None:
make_request = functools.partial(
self.client.get,
reverse("sentry-api-0-organization-stats-summary", args=[self.org.slug]),
)
response = make_request(
{
"statsPeriod": "1d",
"interval": "1d",
"field": ["sum(quantity)"],
"category": "error",
}
)
assert response.status_code == 200, response.content
assert response.data == {
"start": isoformat_z(floor_to_utc_day(self._now) - timedelta(days=1)),
"end": isoformat_z(floor_to_utc_day(self._now) + timedelta(days=1)),
"projects": [
{
"id": self.project.id,
"slug": self.project.slug,
"stats": [
{
"category": "error",
"outcomes": {
"accepted": 6,
"filtered": 0,
"rate_limited": 0,
"invalid": 0,
"abuse": 0,
"client_discard": 0,
"cardinality_limited": 0,
},
"totals": {"dropped": 0, "sum(quantity)": 6},
}
],
}
],
}
def test_download(self) -> None:
req: dict[str, Any] = {
"statsPeriod": "2d",
"interval": "1d",
"field": ["sum(quantity)", "sum(times_seen)"],
"download": True,
}
response = self.client.get(
reverse("sentry-api-0-organization-stats-summary", args=[self.org.slug]), req
)
assert response.headers["Content-Type"] == "text/csv"
assert response.headers["Content-Disposition"] == 'attachment; filename="stats_summary.csv"'
assert response.status_code == 200
| OrganizationStatsSummaryTest |
python | bokeh__bokeh | src/bokeh/util/datatypes.py | {
"start": 1267,
"end": 3814
} | class ____(Generic[K, V]):
''' Store a mapping from keys to multiple values with minimal overhead.
Avoids storing empty collections.
'''
_dict: dict[K, V | set[V]]
def __init__(self) -> None:
'''
'''
self._dict = {}
def add_value(self, key: K, value: V) -> None:
'''
'''
if key is None:
raise ValueError("Key is None")
if value is None:
raise ValueError("Can't put None in this dict")
if isinstance(value, set):
raise ValueError("Can't put sets in this dict")
existing = self._dict.get(key)
if existing is None:
self._dict[key] = value
elif isinstance(existing, set):
cast(set[V], existing).add(value) # XXX: V does not exclude `set[_]`
else:
self._dict[key] = {existing, value}
def get_all(self, k: K) -> list[V]:
'''
'''
existing = self._dict.get(k)
if existing is None:
return []
elif isinstance(existing, set):
return list(cast(set[V], existing))
else:
return [existing]
def get_one(self, k: K, duplicate_error: str) -> V | None:
'''
'''
existing = self._dict.get(k)
if isinstance(existing, set):
existing = cast(set[V], existing)
if len(existing) == 1:
return next(iter(existing))
else:
raise ValueError(f"{duplicate_error}: {existing!r}")
else:
return existing
def remove_value(self, key: K, value: V) -> None:
'''
'''
if key is None:
raise ValueError("Key is None")
existing = self._dict.get(key)
if isinstance(existing, set):
existing = cast(set[V], existing)
existing.discard(value)
if len(existing) == 0:
del self._dict[key]
elif existing == value:
del self._dict[key]
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| MultiValuedDict |
python | astropy__astropy | astropy/tests/runner.py | {
"start": 472,
"end": 1399
} | class ____:
"""
A decorator to mark a method as keyword argument for the ``TestRunner``.
Parameters
----------
default_value : `object`
The default value for the keyword argument. (Default: `None`)
priority : `int`
keyword argument methods are executed in order of descending priority.
"""
def __init__(self, default_value=None, priority=0):
self.default_value = default_value
self.priority = priority
def __call__(self, f):
def keyword(*args, **kwargs):
return f(*args, **kwargs)
keyword._default_value = self.default_value
keyword._priority = self.priority
# Set __doc__ explicitly here rather than using wraps because we want
# to keep the function name as keyword so we can inspect it later.
keyword.__doc__ = f.__doc__
return keyword
@deprecated("8.0", alternative="pytest")
| keyword |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 28557,
"end": 28605
} | class ____(Sum):
reduction_chunk = M.prod
| Prod |
python | kamyu104__LeetCode-Solutions | Python/number-of-different-subsequences-gcds.py | {
"start": 115,
"end": 731
} | class ____(object):
def countDifferentSubsequenceGCDs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_num, nums_set = max(nums), set(nums)
result = 0
for i in xrange(1, max_num+1):
d = 0
for x in xrange(i, max_num+1, i):
if x not in nums_set:
continue
d = fractions.gcd(d, x) # total time: O(log(min(d, x)) = O(logd), where d keeps the same or gets smaller
if d == i:
result += 1
break
return result
| Solution |
python | encode__starlette | starlette/concurrency.py | {
"start": 1017,
"end": 1630
} | class ____(Exception):
pass
def _next(iterator: Iterator[T]) -> T:
# We can't raise `StopIteration` from within the threadpool iterator
# and catch it outside that context, so we coerce them into a different
# exception type.
try:
return next(iterator)
except StopIteration:
raise _StopIteration
async def iterate_in_threadpool(
iterator: Iterable[T],
) -> AsyncIterator[T]:
as_iterator = iter(iterator)
while True:
try:
yield await anyio.to_thread.run_sync(_next, as_iterator)
except _StopIteration:
break
| _StopIteration |
python | ray-project__ray | python/ray/train/v2/_internal/execution/local_mode/utils.py | {
"start": 305,
"end": 1200
} | class ____:
def __init__(
self, experiment_name: str, datasets: Optional[Dict[str, GenDataset]] = None
):
if datasets is not None:
datasets = {k: v() if callable(v) else v for k, v in datasets.items()}
self.datasets = datasets
self.experiment_name = experiment_name
def run(self, train_func: Callable[[], None]) -> Result:
set_train_fn_utils(
LocalTrainFnUtils(
experiment_name=self.experiment_name,
dataset_shards=self.datasets,
)
)
train_func()
train_fn_utils = get_train_fn_utils()
assert isinstance(train_fn_utils, LocalTrainFnUtils)
return Result(
metrics=train_fn_utils._get_last_metrics(),
checkpoint=train_fn_utils.get_checkpoint(),
path=None,
error=None,
)
| LocalController |
python | doocs__leetcode | solution/0900-0999/0976.Largest Perimeter Triangle/Solution.py | {
"start": 0,
"end": 249
} | class ____:
def largestPerimeter(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums) - 1, 1, -1):
if (c := nums[i - 1] + nums[i - 2]) > nums[i]:
return c + nums[i]
return 0
| Solution |
python | scikit-learn__scikit-learn | sklearn/compose/tests/test_column_transformer.py | {
"start": 1860,
"end": 1998
} | class ____(BaseEstimator):
def fit(self, X, y=None):
return self
def transform(self, X, y=None):
return X
| TransNo2D |
python | langchain-ai__langchain | libs/langchain/langchain_classic/retrievers/document_compressors/embeddings_filter.py | {
"start": 693,
"end": 5747
} | class ____(BaseDocumentCompressor):
"""Embeddings Filter.
Document compressor that uses embeddings to drop documents unrelated to the query.
"""
embeddings: Embeddings
"""Embeddings to use for embedding document contents and queries."""
similarity_fn: Callable = Field(default_factory=_get_similarity_function)
"""Similarity function for comparing documents. Function expected to take as input
two matrices (List[List[float]]) and return a matrix of scores where higher values
indicate greater similarity."""
k: int | None = 20
"""The number of relevant documents to return. Can be set to `None`, in which case
`similarity_threshold` must be specified."""
similarity_threshold: float | None = None
"""Threshold for determining when two documents are similar enough
to be considered redundant. Defaults to `None`, must be specified if `k` is set
to None."""
model_config = ConfigDict(
arbitrary_types_allowed=True,
)
@pre_init
def validate_params(cls, values: dict) -> dict:
"""Validate similarity parameters."""
if values["k"] is None and values["similarity_threshold"] is None:
msg = "Must specify one of `k` or `similarity_threshold`."
raise ValueError(msg)
return values
@override
def compress_documents(
self,
documents: Sequence[Document],
query: str,
callbacks: Callbacks | None = None,
) -> Sequence[Document]:
"""Filter documents based on similarity of their embeddings to the query."""
try:
from langchain_community.document_transformers.embeddings_redundant_filter import ( # noqa: E501
_get_embeddings_from_stateful_docs,
get_stateful_documents,
)
except ImportError as e:
msg = (
"To use please install langchain-community "
"with `pip install langchain-community`."
)
raise ImportError(msg) from e
try:
import numpy as np
except ImportError as e:
msg = "Could not import numpy, please install with `pip install numpy`."
raise ImportError(msg) from e
stateful_documents = get_stateful_documents(documents)
embedded_documents = _get_embeddings_from_stateful_docs(
self.embeddings,
stateful_documents,
)
embedded_query = self.embeddings.embed_query(query)
similarity = self.similarity_fn([embedded_query], embedded_documents)[0]
included_idxs: np.ndarray = np.arange(len(embedded_documents))
if self.k is not None:
included_idxs = np.argsort(similarity)[::-1][: self.k]
if self.similarity_threshold is not None:
similar_enough = np.where(
similarity[included_idxs] > self.similarity_threshold,
)
included_idxs = included_idxs[similar_enough]
for i in included_idxs:
stateful_documents[i].state["query_similarity_score"] = similarity[i]
return [stateful_documents[i] for i in included_idxs]
@override
async def acompress_documents(
self,
documents: Sequence[Document],
query: str,
callbacks: Callbacks | None = None,
) -> Sequence[Document]:
"""Filter documents based on similarity of their embeddings to the query."""
try:
from langchain_community.document_transformers.embeddings_redundant_filter import ( # noqa: E501
_aget_embeddings_from_stateful_docs,
get_stateful_documents,
)
except ImportError as e:
msg = (
"To use please install langchain-community "
"with `pip install langchain-community`."
)
raise ImportError(msg) from e
try:
import numpy as np
except ImportError as e:
msg = "Could not import numpy, please install with `pip install numpy`."
raise ImportError(msg) from e
stateful_documents = get_stateful_documents(documents)
embedded_documents = await _aget_embeddings_from_stateful_docs(
self.embeddings,
stateful_documents,
)
embedded_query = await self.embeddings.aembed_query(query)
similarity = self.similarity_fn([embedded_query], embedded_documents)[0]
included_idxs: np.ndarray = np.arange(len(embedded_documents))
if self.k is not None:
included_idxs = np.argsort(similarity)[::-1][: self.k]
if self.similarity_threshold is not None:
similar_enough = np.where(
similarity[included_idxs] > self.similarity_threshold,
)
included_idxs = included_idxs[similar_enough]
for i in included_idxs:
stateful_documents[i].state["query_similarity_score"] = similarity[i]
return [stateful_documents[i] for i in included_idxs]
| EmbeddingsFilter |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster_user_deployments/subschema/user_deployments.py | {
"start": 344,
"end": 1882
} | class ____(BaseModel):
name: str
image: kubernetes.Image
dagsterApiGrpcArgs: Optional[list[str]] = None
codeServerArgs: Optional[list[str]] = None
includeConfigInLaunchedRuns: Optional[UserDeploymentIncludeConfigInLaunchedRuns] = None
deploymentNamespace: Optional[str] = None
port: int
env: Optional[Union[dict[str, str], list[kubernetes.EnvVar]]] = None
envConfigMaps: Optional[list[kubernetes.ConfigMapEnvSource]] = None
envSecrets: Optional[list[kubernetes.SecretEnvSource]] = None
annotations: Optional[kubernetes.Annotations] = None
nodeSelector: Optional[kubernetes.NodeSelector] = None
affinity: Optional[kubernetes.Affinity] = None
tolerations: Optional[kubernetes.Tolerations] = None
podSecurityContext: Optional[kubernetes.PodSecurityContext] = None
securityContext: Optional[kubernetes.SecurityContext] = None
resources: Optional[kubernetes.Resources] = None
livenessProbe: Optional[kubernetes.LivenessProbe] = None
readinessProbe: Optional[ReadinessProbeWithEnabled] = None
startupProbe: Optional[kubernetes.StartupProbe] = None
labels: Optional[dict[str, str]] = None
volumeMounts: Optional[list[kubernetes.VolumeMount]] = None
volumes: Optional[list[kubernetes.Volume]] = None
schedulerName: Optional[str] = None
initContainers: Optional[list[kubernetes.Container]] = None
sidecarContainers: Optional[list[kubernetes.Container]] = None
deploymentStrategy: Optional[kubernetes.DeploymentStrategy] = None
| UserDeployment |
python | kamyu104__LeetCode-Solutions | Python/longest-strictly-increasing-or-strictly-decreasing-subarray.py | {
"start": 958,
"end": 1451
} | class ____(object):
def longestMonotonicSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def f(compare):
result = l = 0
for i in xrange(len(nums)):
l += 1
if i+1 == len(nums) or not compare(nums[i], nums[i+1]):
result = max(result, l)
l = 0
return result
return max(f(lambda x, y: x < y), f(lambda x, y: x > y))
| Solution3 |
python | sympy__sympy | sympy/diffgeom/diffgeom.py | {
"start": 72125,
"end": 72274
} | class ____(_deprecated_container, dict):
pass
# Import at end to avoid cyclic imports
from sympy.simplify.simplify import simplify
| _deprecated_dict |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/Node.py | {
"start": 18675,
"end": 26536
} | class ____(GraphicsObject):
def __init__(self, node):
#QtWidgets.QGraphicsItem.__init__(self)
GraphicsObject.__init__(self)
#QObjectWorkaround.__init__(self)
#self.shadow = QtWidgets.QGraphicsDropShadowEffect()
#self.shadow.setOffset(5,5)
#self.shadow.setBlurRadius(10)
#self.setGraphicsEffect(self.shadow)
self.pen = fn.mkPen(0,0,0)
self.selectPen = fn.mkPen(200,200,200,width=2)
self.brush = fn.mkBrush(200, 200, 200, 150)
self.hoverBrush = fn.mkBrush(200, 200, 200, 200)
self.selectBrush = fn.mkBrush(200, 200, 255, 200)
self.hovered = False
self.node = node
flags = self.GraphicsItemFlag.ItemIsMovable | self.GraphicsItemFlag.ItemIsSelectable | self.GraphicsItemFlag.ItemIsFocusable | self.GraphicsItemFlag.ItemSendsGeometryChanges
#flags = self.ItemIsFocusable |self.ItemSendsGeometryChanges
self.setFlags(flags)
self.bounds = QtCore.QRectF(0, 0, 100, 100)
self.nameItem = TextItem(self.node.name(), self, self.labelChanged)
self.nameItem.setDefaultTextColor(QtGui.QColor(50, 50, 50))
self.nameItem.moveBy(self.bounds.width()/2. - self.nameItem.boundingRect().width()/2., 0)
self._titleOffset = 25
self._nodeOffset = 12
self.updateTerminals()
#self.setZValue(10)
self.menu = None
self.buildMenu()
def setTitleOffset(self, new_offset):
"""
This method sets the rendering offset introduced after the title of the node.
This method automatically updates the terminal labels. The default for this value is 25px.
:param new_offset: The new offset to use in pixels at 100% scale.
"""
self._titleOffset = new_offset
self.updateTerminals()
def titleOffset(self):
"""
This method returns the current title offset in use.
:returns: The offset in px.
"""
return self._titleOffset
def setTerminalOffset(self, new_offset):
"""
This method sets the rendering offset introduced after every terminal of the node.
This method automatically updates the terminal labels. The default for this value is 12px.
:param new_offset: The new offset to use in pixels at 100% scale.
"""
self._nodeOffset = new_offset
self.updateTerminals()
def terminalOffset(self):
"""
This method returns the current terminal offset in use.
:returns: The offset in px.
"""
return self._nodeOffset
#self.node.sigTerminalRenamed.connect(self.updateActionMenu)
#def setZValue(self, z):
#for t, item in self.terminals.values():
#item.setZValue(z+1)
#GraphicsObject.setZValue(self, z)
def labelChanged(self):
newName = self.nameItem.toPlainText()
if newName != self.node.name():
self.node.rename(newName)
### re-center the label
bounds = self.boundingRect()
self.nameItem.setPos(bounds.width()/2. - self.nameItem.boundingRect().width()/2., 0)
def setPen(self, *args, **kwargs):
self.pen = fn.mkPen(*args, **kwargs)
self.update()
def setBrush(self, brush):
self.brush = brush
self.update()
def updateTerminals(self):
self.terminals = {}
inp = self.node.inputs()
out = self.node.outputs()
maxNode = max(len(inp), len(out))
# calculate new height
newHeight = self._titleOffset + maxNode*self._nodeOffset
# if current height is not equal to new height, update
if not self.bounds.height() == newHeight:
self.bounds.setHeight(newHeight)
self.update()
# Populate inputs
y = self._titleOffset
for i, t in inp.items():
item = t.graphicsItem()
item.setParentItem(self)
#item.setZValue(self.zValue()+1)
item.setAnchor(0, y)
self.terminals[i] = (t, item)
y += self._nodeOffset
# Populate inputs
y = self._titleOffset
for i, t in out.items():
item = t.graphicsItem()
item.setParentItem(self)
item.setZValue(self.zValue())
item.setAnchor(self.bounds.width(), y)
self.terminals[i] = (t, item)
y += self._nodeOffset
#self.buildMenu()
def boundingRect(self):
return self.bounds.adjusted(-5, -5, 5, 5)
def paint(self, p, *args):
p.setPen(self.pen)
if self.isSelected():
p.setPen(self.selectPen)
p.setBrush(self.selectBrush)
else:
p.setPen(self.pen)
if self.hovered:
p.setBrush(self.hoverBrush)
else:
p.setBrush(self.brush)
p.drawRect(self.bounds)
def mousePressEvent(self, ev):
ev.ignore()
def mouseClickEvent(self, ev):
if ev.button() == QtCore.Qt.MouseButton.LeftButton:
ev.accept()
sel = self.isSelected()
self.setSelected(True)
if not sel and self.isSelected():
self.update()
elif ev.button() == QtCore.Qt.MouseButton.RightButton:
ev.accept()
self.raiseContextMenu(ev)
def mouseDragEvent(self, ev):
if ev.button() == QtCore.Qt.MouseButton.LeftButton:
ev.accept()
self.setPos(self.pos()+self.mapToParent(ev.pos())-self.mapToParent(ev.lastPos()))
def hoverEvent(self, ev):
if not ev.isExit() and ev.acceptClicks(QtCore.Qt.MouseButton.LeftButton):
ev.acceptDrags(QtCore.Qt.MouseButton.LeftButton)
self.hovered = True
else:
self.hovered = False
self.update()
def keyPressEvent(self, ev):
if ev.key() == QtCore.Qt.Key.Key_Delete or ev.key() == QtCore.Qt.Key.Key_Backspace:
ev.accept()
if not self.node._allowRemove:
return
self.node.close()
else:
ev.ignore()
def itemChange(self, change, val):
if change == self.GraphicsItemChange.ItemPositionHasChanged:
for k, t in self.terminals.items():
t[1].nodeMoved()
return GraphicsObject.itemChange(self, change, val)
def getMenu(self):
return self.menu
def raiseContextMenu(self, ev):
menu = self.scene().addParentContextMenus(self, self.getMenu(), ev)
pos = ev.screenPos()
menu.popup(QtCore.QPoint(int(pos.x()), int(pos.y())))
def buildMenu(self):
self.menu = QtWidgets.QMenu()
self.menu.setTitle(translate("Context Menu", "Node"))
a = self.menu.addAction(translate("Context Menu","Add input"), self.addInputFromMenu)
if not self.node._allowAddInput:
a.setEnabled(False)
a = self.menu.addAction(translate("Context Menu", "Add output"), self.addOutputFromMenu)
if not self.node._allowAddOutput:
a.setEnabled(False)
a = self.menu.addAction(translate("Context Menu", "Remove node"), self.node.close)
if not self.node._allowRemove:
a.setEnabled(False)
def addInputFromMenu(self): ## called when add input is clicked in context menu
self.node.addInput(renamable=True, removable=True, multiable=True)
def addOutputFromMenu(self): ## called when add output is clicked in context menu
self.node.addOutput(renamable=True, removable=True, multiable=False)
| NodeGraphicsItem |
python | oauthlib__oauthlib | tests/openid/connect/core/grant_types/test_dispatchers.py | {
"start": 2083,
"end": 2559
} | class ____(TestCase):
def setUp(self):
self.request = Request('http://a.b/path')
self.request.decoded_body = (
("client_id", "me"),
("code", "code"),
("redirect_url", "https://a.b/cb"),
)
self.request_validator = mock.MagicMock()
self.auth_grant = OAuth2AuthorizationCodeGrant(self.request_validator)
self.openid_connect_auth = AuthorizationCodeGrant(self.request_validator)
| DispatcherTest |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_training.py | {
"start": 1827,
"end": 3100
} | class ____(FSDPTestMultiThread):
@property
def world_size(self) -> int:
return 2
@skip_if_lt_x_gpu(1)
def test_root_move_forward_input_to_device(self):
device = torch.device(device_type.type, 0)
class ParamlessModule(nn.Module):
def forward(self, x: torch.Tensor, ys: tuple[torch.Tensor, ...]):
# Check that FSDP moved the inputs to GPU, including recursing
# into the tuple data structure
assert x.device == device, f"Expects {device} but got {x.device}"
assert ys[0].device == device, (
f"Expects {device} but got {ys[0].device}"
)
assert ys[1].device == device, (
f"Expects {device} but got {ys[1].device}"
)
y = ys[0] + ys[1]
return x + y + 1
model = ParamlessModule().to(device)
fully_shard(model).to(device)
x = torch.randn((3,))
ys = (torch.randn((3,)), torch.randn((3,)))
self.assertEqual(x.device, torch.device("cpu"))
self.assertEqual(ys[0].device, torch.device("cpu"))
self.assertEqual(ys[1].device, torch.device("cpu"))
model(x, ys)
| TestFullyShardForwardInputs |
python | doocs__leetcode | solution/1600-1699/1612.Check If Two Expression Trees are Equivalent/Solution2.py | {
"start": 198,
"end": 742
} | class ____:
def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool:
def dfs(root):
cnt = [0] * 26
if root is None:
return cnt
if root.val in '+-':
l, r = dfs(root.left), dfs(root.right)
k = 1 if root.val == '+' else -1
for i in range(26):
cnt[i] += l[i] + r[i] * k
else:
cnt[ord(root.val) - ord('a')] += 1
return cnt
return dfs(root1) == dfs(root2)
| Solution |
python | getsentry__sentry | src/sentry/testutils/helpers/backups.py | {
"start": 39902,
"end": 40163
} | class ____(TestCase, ExhaustiveFixtures):
"""
Instruments a database state that includes an instance of every Sentry model with every field
set to a non-default, non-null value. This is useful for exhaustive conformance testing.
"""
| BackupTestCase |
python | ansible__ansible | test/units/utils/test_serialization_profiles.py | {
"start": 5768,
"end": 7593
} | class ____:
profile_name: str
value: t.Any
tags: tuple[AnsibleDatatagBase, ...] = ()
lazy: bool = False
def __hash__(self):
return hash((self.profile_name, repr(self.value), self.tags))
def __repr__(self):
fields = ((field, getattr(self, field.name)) for field in dataclasses.fields(self))
args = (f'{f.name}={v!r}' for f, v in fields if v != f.default)
return f"{type(self).__name__}({', '.join(args)})"
def get_test_output(self) -> _TestOutput:
encoder = get_encoder(self.profile_name)
decoder = get_decoder(self.profile_name)
ctx = TemplateContext(
template_value=self.value,
templar=TemplateEngine(),
options=TemplateOptions.DEFAULT,
stop_on_template=False
) if self.lazy else contextlib.nullcontext()
with ctx:
try:
value = AnsibleTagHelper.tag(self.value, self.tags)
except NotTaggableError:
value = self.value
if self.lazy:
value = _AnsibleLazyTemplateMixin._try_create(value)
payload: str | Exception
try:
payload = json.dumps(value, cls=encoder)
except Exception as ex:
payload = ex
round_trip = None
else:
try:
round_trip = json.loads(payload, cls=decoder)
except Exception as ex:
round_trip = ex
return _TestOutput(
payload=payload,
round_trip=AnsibleTagHelper.as_native_type(round_trip),
tags=tuple(sorted(AnsibleTagHelper.tags(round_trip), key=lambda item: type(item).__name__)),
)
@dataclasses.dataclass(frozen=True)
| _TestParameters |
python | apache__airflow | airflow-core/tests/unit/dag_processing/test_collection.py | {
"start": 4695,
"end": 10334
} | class ____:
@staticmethod
def clean_db():
clear_db_dags()
clear_db_assets()
clear_db_triggers()
@pytest.fixture(autouse=True)
def per_test(self) -> Generator:
self.clean_db()
yield
self.clean_db()
@pytest.mark.parametrize(
("is_active", "is_paused", "expected_num_triggers"),
[
(True, True, 0),
(True, False, 1),
(False, True, 0),
(False, False, 0),
],
)
@pytest.mark.usefixtures("testing_dag_bundle")
def test_add_asset_trigger_references(
self, dag_maker, session, is_active, is_paused, expected_num_triggers
):
classpath, kwargs = TimeDeltaTrigger(timedelta(seconds=0)).serialize()
asset = Asset(
"test_add_asset_trigger_references_asset",
watchers=[AssetWatcher(name="test", trigger={"classpath": classpath, "kwargs": kwargs})],
)
with dag_maker(dag_id="test_add_asset_trigger_references_dag", schedule=[asset]) as dag:
EmptyOperator(task_id="mytask")
dags = {dag.dag_id: LazyDeserializedDAG.from_dag(dag)}
orm_dags = DagModelOperation(dags, "testing", None).add_dags(session=session)
# Simulate dag unpause and deletion.
dag_model = orm_dags[dag.dag_id]
dag_model.is_stale = not is_active
dag_model.is_paused = is_paused
asset_op = AssetModelOperation.collect(dags)
orm_assets = asset_op.sync_assets(session=session)
session.flush()
asset_op.add_dag_asset_references(orm_dags, orm_assets, session=session)
asset_op.activate_assets_if_possible(orm_assets.values(), session=session)
asset_op.add_asset_trigger_references(orm_assets, session=session)
session.flush()
asset_model = session.scalars(select(AssetModel)).one()
assert len(asset_model.triggers) == expected_num_triggers
@pytest.mark.parametrize(
("schedule", "model", "columns", "expected"),
[
pytest.param(
Asset.ref(name="name1"),
DagScheduleAssetNameReference,
(DagScheduleAssetNameReference.name, DagScheduleAssetNameReference.dag_id),
[("name1", "test")],
id="name-ref",
),
pytest.param(
Asset.ref(uri="foo://1"),
DagScheduleAssetUriReference,
(DagScheduleAssetUriReference.uri, DagScheduleAssetUriReference.dag_id),
[("foo://1", "test")],
id="uri-ref",
),
],
)
def test_add_dag_asset_name_uri_references(self, dag_maker, session, schedule, model, columns, expected):
with dag_maker(dag_id="test", schedule=schedule, session=session) as dag:
pass
op = AssetModelOperation.collect({dag.dag_id: LazyDeserializedDAG.from_dag(dag)})
op.add_dag_asset_name_uri_references(session=session)
assert session.execute(select(*columns)).all() == expected
def test_change_asset_property_sync_group(self, dag_maker, session):
asset = Asset("myasset", group="old_group")
with dag_maker(schedule=[asset]) as dag:
EmptyOperator(task_id="mytask")
asset_op = AssetModelOperation.collect({dag.dag_id: LazyDeserializedDAG.from_dag(dag)})
orm_assets = asset_op.sync_assets(session=session)
assert len(orm_assets) == 1
assert next(iter(orm_assets.values())).group == "old_group"
# Parser should pick up group change.
asset.group = "new_group"
asset_op = AssetModelOperation.collect({dag.dag_id: LazyDeserializedDAG.from_dag(dag)})
orm_assets = asset_op.sync_assets(session=session)
assert len(orm_assets) == 1
assert next(iter(orm_assets.values())).group == "new_group"
def test_change_asset_property_sync_extra(self, dag_maker, session):
asset = Asset("myasset", extra={"foo": "old"})
with dag_maker(schedule=asset) as dag:
EmptyOperator(task_id="mytask")
asset_op = AssetModelOperation.collect({dag.dag_id: LazyDeserializedDAG.from_dag(dag)})
orm_assets = asset_op.sync_assets(session=session)
assert len(orm_assets) == 1
assert next(iter(orm_assets.values())).extra == {"foo": "old"}
# Parser should pick up extra change.
asset.extra = {"foo": "new"}
asset_op = AssetModelOperation.collect({dag.dag_id: LazyDeserializedDAG.from_dag(dag)})
orm_assets = asset_op.sync_assets(session=session)
assert len(orm_assets) == 1
assert next(iter(orm_assets.values())).extra == {"foo": "new"}
def test_change_asset_alias_property_sync_group(self, dag_maker, session):
alias = AssetAlias("myalias", group="old_group")
with dag_maker(schedule=alias) as dag:
EmptyOperator(task_id="mytask")
asset_op = AssetModelOperation.collect({dag.dag_id: LazyDeserializedDAG.from_dag(dag)})
orm_aliases = asset_op.sync_asset_aliases(session=session)
assert len(orm_aliases) == 1
assert next(iter(orm_aliases.values())).group == "old_group"
# Parser should pick up group change.
alias.group = "new_group"
asset_op = AssetModelOperation.collect({dag.dag_id: LazyDeserializedDAG.from_dag(dag)})
orm_aliases = asset_op.sync_asset_aliases(session=session)
assert len(orm_aliases) == 1
assert next(iter(orm_aliases.values())).group == "new_group"
@pytest.mark.db_test
@pytest.mark.want_activate_assets(False)
| TestAssetModelOperation |
python | gevent__gevent | src/gevent/tests/test__pool.py | {
"start": 4307,
"end": 7940
} | class ____(greentest.TestCase):
klass = gevent.pool.Pool
def test_execute_async(self):
p = self.klass(size=2)
self.assertEqual(p.free_count(), 2)
r = []
first = p.spawn(r.append, 1)
self.assertEqual(p.free_count(), 1)
first.get()
self.assertEqual(r, [1])
gevent.sleep(0)
self.assertEqual(p.free_count(), 2)
#Once the pool is exhausted, calling an execute forces a yield.
p.apply_async(r.append, (2, ))
self.assertEqual(1, p.free_count())
self.assertEqual(r, [1])
p.apply_async(r.append, (3, ))
self.assertEqual(0, p.free_count())
self.assertEqual(r, [1])
p.apply_async(r.append, (4, ))
self.assertEqual(r, [1])
gevent.sleep(0.01)
self.assertEqual(sorted(r), [1, 2, 3, 4])
def test_discard(self):
p = self.klass(size=1)
first = p.spawn(gevent.sleep, 1000)
p.discard(first)
first.kill()
self.assertFalse(first)
self.assertEqual(len(p), 0)
self.assertEqual(p._semaphore.counter, 1)
def test_add_method(self):
p = self.klass(size=1)
first = gevent.spawn(gevent.sleep, 1000)
try:
second = gevent.spawn(gevent.sleep, 1000)
try:
self.assertEqual(p.free_count(), 1)
self.assertEqual(len(p), 0)
p.add(first)
self.assertEqual(p.free_count(), 0)
self.assertEqual(len(p), 1)
with self.assertRaises(gevent.Timeout):
with gevent.Timeout(0.1):
p.add(second)
self.assertEqual(p.free_count(), 0)
self.assertEqual(len(p), 1)
finally:
second.kill()
finally:
first.kill()
@greentest.ignores_leakcheck
def test_add_method_non_blocking(self):
p = self.klass(size=1)
first = gevent.spawn(gevent.sleep, 1000)
try:
second = gevent.spawn(gevent.sleep, 1000)
try:
p.add(first)
with self.assertRaises(gevent.pool.PoolFull):
p.add(second, blocking=False)
finally:
second.kill()
finally:
first.kill()
@greentest.ignores_leakcheck
def test_add_method_timeout(self):
p = self.klass(size=1)
first = gevent.spawn(gevent.sleep, 1000)
try:
second = gevent.spawn(gevent.sleep, 1000)
try:
p.add(first)
with self.assertRaises(gevent.pool.PoolFull):
p.add(second, timeout=0.100)
finally:
second.kill()
finally:
first.kill()
@greentest.ignores_leakcheck
def test_start_method_timeout(self):
p = self.klass(size=1)
first = gevent.spawn(gevent.sleep, 1000)
try:
second = gevent.Greenlet(gevent.sleep, 1000)
try:
p.add(first)
with self.assertRaises(gevent.pool.PoolFull):
p.start(second, timeout=0.100)
finally:
second.kill()
finally:
first.kill()
def test_apply(self):
p = self.klass()
result = p.apply(lambda a: ('foo', a), (1, ))
self.assertEqual(result, ('foo', 1))
def test_init_error(self):
self.switch_expected = False
self.assertRaises(ValueError, self.klass, -1)
#
# tests from standard library test/test_multiprocessing.py
| PoolBasicTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.