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
catalyst-team__catalyst
catalyst/contrib/losses/focal.py
{ "start": 103, "end": 1625 }
class ____(_Loss): """Compute focal loss for binary classification problem. It has been proposed in `Focal Loss for Dense Object Detection`_ paper. .. _Focal Loss for Dense Object Detection: https://arxiv.org/abs/1708.02002 """ def __init__( self, ignore: int = None, reduced: bool = False, gamma: float = 2.0, alpha: float = 0.25, threshold: float = 0.5, reduction: str = "mean", ): """@TODO: Docs. Contribution is welcome.""" super().__init__() self.ignore = ignore if reduced: self.loss_fn = partial( metrics.reduced_focal_loss, gamma=gamma, threshold=threshold, reduction=reduction, ) else: self.loss_fn = partial( metrics.sigmoid_focal_loss, gamma=gamma, alpha=alpha, reduction=reduction ) def forward(self, logits, targets): """ Args: logits: [bs; ...] targets: [bs; ...] Returns: computed loss """ targets = targets.view(-1) logits = logits.view(-1) if self.ignore is not None: # Filter predictions with ignore label from loss computation not_ignored = targets != self.ignore logits = logits[not_ignored] targets = targets[not_ignored] loss = self.loss_fn(logits, targets) return loss
FocalLossBinary
python
getsentry__sentry
tests/sentry/api/endpoints/test_accept_project_transfer.py
{ "start": 840, "end": 7519 }
class ____(APITestCase): def setUp(self) -> None: super().setUp() self.owner = self.create_user(email="example@example.com", is_superuser=False) self.from_organization = self.create_organization(owner=self.owner) self.to_organization = self.create_organization(owner=self.owner) self.from_team = self.create_team(organization=self.from_organization) self.to_team = self.create_team(organization=self.to_organization) user = self.create_user("admin@example.com") self.member = self.create_member( organization=self.from_organization, user=user, role="admin", teams=[self.from_team] ) self.project = self.create_project(name="proj", teams=[self.from_team]) self.transaction_id = uuid4().hex ProjectOption.objects.set_value( self.project, "sentry:project-transfer-transaction-id", self.transaction_id ) self.path = reverse("sentry-api-0-accept-project-transfer") def test_requires_authentication(self) -> None: response = self.client.get(self.path) assert response.status_code == 403 assert response.data == {"detail": "Authentication credentials were not provided."} def test_handle_incorrect_url_data(self) -> None: self.login_as(self.owner) url_data = sign( salt=SALT, actor_id=self.member.id, # This is bad data from_organization_id=9999999, project_id=self.project.id, user_id=self.owner.id, transaction_id=self.transaction_id, ) resp = self.client.get(self.path + "?" + urlencode({"data": url_data})) assert resp.status_code == 400 assert resp.data["detail"] == "Project no longer exists" resp = self.client.get(self.path) assert resp.status_code == 404 def test_handle_incorrect_transaction_id(self) -> None: self.login_as(self.owner) url_data = sign( salt=SALT, actor_id=self.member.id, from_organization_id=self.from_organization.id, project_id=self.project.id, user_id=self.owner.id, transaction_id="fake_or_obsolete_transaction_id", ) resp = self.client.get(self.path + "?" + urlencode({"data": url_data})) assert resp.status_code == 400 assert resp.data["detail"] == "Invalid transaction id" resp = self.client.get(self.path) assert resp.status_code == 404 def test_returns_org_options_with_signed_link(self) -> None: self.login_as(self.owner) url_data = sign( salt=SALT, actor_id=self.member.user_id, from_organization_id=self.from_organization.id, project_id=self.project.id, user_id=self.owner.id, transaction_id=self.transaction_id, ) resp = self.client.get(self.path + "?" + urlencode({"data": url_data})) assert resp.status_code == 200 assert resp.data["project"]["slug"] == self.project.slug assert resp.data["project"]["id"] == self.project.id assert len(resp.data["organizations"]) == 2 org_slugs = {o["slug"] for o in resp.data["organizations"]} assert self.from_organization.slug in org_slugs assert self.to_organization.slug in org_slugs def test_transfers_project_to_team_deprecated(self) -> None: self.login_as(self.owner) url_data = sign( salt=SALT, actor_id=self.member.user_id, from_organization_id=self.from_organization.id, project_id=self.project.id, user_id=self.owner.id, transaction_id=self.transaction_id, ) resp = self.client.post( self.path, data={"team": self.to_team.id, "organization": None, "data": url_data} ) assert resp.status_code == 400 assert resp.data == {"detail": "Cannot transfer projects to a team."} def test_non_owner_cannot_transfer_project(self) -> None: rando_user = self.create_user(email="blipp@bloop.com", is_superuser=False) rando_org = self.create_organization(name="supreme beans") self.login_as(rando_user) url_data = sign( salt=SALT, actor_id=self.member.user_id, from_organization_id=rando_org.id, project_id=self.project.id, user_id=rando_user.id, transaction_id=self.transaction_id, ) resp = self.client.post( self.path, data={"organization": self.to_organization.slug, "data": url_data} ) assert resp.status_code == 400 p = Project.objects.get(id=self.project.id) assert p.organization_id == self.from_organization.id assert p.organization_id != rando_org.id @patch("sentry.signals.project_transferred.send_robust") def test_transfers_project_to_correct_organization(self, send_robust: MagicMock) -> None: self.login_as(self.owner) url_data = sign( salt=SALT, actor_id=self.member.user_id, from_organization_id=self.from_organization.id, project_id=self.project.id, user_id=self.owner.id, transaction_id=self.transaction_id, ) resp = self.client.post( self.path, data={"organization": self.to_organization.slug, "data": url_data} ) assert resp.status_code == 204 p = Project.objects.get(id=self.project.id) assert p.organization_id == self.to_organization.id assert ProjectOption.objects.get_value(p, "sentry:project-transfer-transaction-id") is None assert send_robust.called @patch("sentry.signals.project_transferred.send_robust") def test_use_org_when_team_and_org_provided(self, send_robust: MagicMock) -> None: self.login_as(self.owner) url_data = sign( salt=SALT, actor_id=self.member.user_id, from_organization_id=self.from_organization.id, project_id=self.project.id, user_id=self.owner.id, transaction_id=self.transaction_id, ) resp = self.client.post( self.path, data={ "organization": self.to_organization.slug, "team": self.to_team.id, "data": url_data, }, ) assert resp.status_code == 204 p = Project.objects.get(id=self.project.id) assert p.organization_id == self.to_organization.id assert send_robust.called
AcceptTransferProjectTest
python
keras-team__keras
keras/src/backend/tensorflow/name_scope_test.py
{ "start": 123, "end": 1624 }
class ____(TestCase): def test_stacking(self): self.assertEqual(tf.Variable(0, name="x").name, "x:0") with name_scope("outer") as outer: self.assertEqual(outer.name, "outer") self.assertEqual(tf.Variable(0, name="x").name, "outer/x:0") with name_scope("middle") as middle: self.assertEqual(middle.name, "middle") self.assertEqual( tf.Variable(0, name="x").name, "outer/middle/x:0" ) with name_scope("inner") as inner: self.assertEqual(inner.name, "inner") self.assertEqual( tf.Variable(0, name="x").name, "outer/middle/inner/x:0" ) self.assertEqual( tf.Variable(0, name="x").name, "outer/middle/x:0" ) self.assertEqual(tf.Variable(0, name="x").name, "outer/x:0") self.assertEqual(tf.Variable(0, name="x").name, "x:0") def test_deduplicate(self): self.assertEqual(tf.Variable(0, name="x").name, "x:0") with name_scope("name", caller=1): with name_scope("name", caller=1): self.assertEqual(tf.Variable(0, name="x").name, "name/x:0") self.assertEqual(tf.Variable(0, name="x").name, "x:0") with name_scope("name"): with name_scope("name"): self.assertEqual(tf.Variable(0, name="x").name, "name/name/x:0")
TFNameScopeTest
python
pydantic__pydantic
pydantic/v1/env_settings.py
{ "start": 11232, "end": 14105 }
class ____: __slots__ = ('secrets_dir',) def __init__(self, secrets_dir: Optional[StrPath]): self.secrets_dir: Optional[StrPath] = secrets_dir def __call__(self, settings: BaseSettings) -> Dict[str, Any]: """ Build fields from "secrets" files. """ secrets: Dict[str, Optional[str]] = {} if self.secrets_dir is None: return secrets secrets_path = Path(self.secrets_dir).expanduser() if not secrets_path.exists(): warnings.warn(f'directory "{secrets_path}" does not exist') return secrets if not secrets_path.is_dir(): raise SettingsError(f'secrets_dir must reference a directory, not a {path_type(secrets_path)}') for field in settings.__fields__.values(): for env_name in field.field_info.extra['env_names']: path = find_case_path(secrets_path, env_name, settings.__config__.case_sensitive) if not path: # path does not exist, we currently don't return a warning for this continue if path.is_file(): secret_value = path.read_text().strip() if field.is_complex(): try: secret_value = settings.__config__.parse_env_var(field.name, secret_value) except ValueError as e: raise SettingsError(f'error parsing env var "{env_name}"') from e secrets[field.alias] = secret_value else: warnings.warn( f'attempted to load secret file "{path}" but found a {path_type(path)} instead.', stacklevel=4, ) return secrets def __repr__(self) -> str: return f'SecretsSettingsSource(secrets_dir={self.secrets_dir!r})' def read_env_file( file_path: StrPath, *, encoding: str = None, case_sensitive: bool = False ) -> Dict[str, Optional[str]]: try: from dotenv import dotenv_values except ImportError as e: raise ImportError('python-dotenv is not installed, run `pip install pydantic[dotenv]`') from e file_vars: Dict[str, Optional[str]] = dotenv_values(file_path, encoding=encoding or 'utf8') if not case_sensitive: return {k.lower(): v for k, v in file_vars.items()} else: return file_vars def find_case_path(dir_path: Path, file_name: str, case_sensitive: bool) -> Optional[Path]: """ Find a file within path's directory matching filename, optionally ignoring case. """ for f in dir_path.iterdir(): if f.name == file_name: return f elif not case_sensitive and f.name.lower() == file_name.lower(): return f return None
SecretsSettingsSource
python
neetcode-gh__leetcode
python/0217-contains-duplicate.py
{ "start": 0, "end": 227 }
class ____: def containsDuplicate(self, nums: List[int]) -> bool: hashset = set() for n in nums: if n in hashset: return True hashset.add(n) return False
Solution
python
huggingface__transformers
src/transformers/models/aria/modular_aria.py
{ "start": 54104, "end": 54583 }
class ____(LlamaPreTrainedModel): config: AriaConfig base_model_prefix = "model" _can_compile_fullgraph = False # MoE models don't work with torch.compile (dynamic slicing) _supports_attention_backend = True @torch.no_grad() def _init_weights(self, module): PreTrainedModel._init_weights(self, module) if isinstance(module, AriaProjector): init.trunc_normal_(module.query, std=self.config.initializer_range)
AriaPreTrainedModel
python
pyca__cryptography
src/cryptography/hazmat/primitives/hashes.py
{ "start": 3787, "end": 4263 }
class ____(HashAlgorithm, ExtendableOutputFunction): name = "shake256" block_size = None def __init__(self, digest_size: int): if not isinstance(digest_size, int): raise TypeError("digest_size must be an integer") if digest_size < 1: raise ValueError("digest_size must be a positive integer") self._digest_size = digest_size @property def digest_size(self) -> int: return self._digest_size
SHAKE256
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/batchtospace_op_test.py
{ "start": 1315, "end": 1454 }
class ____(object): @staticmethod def batch_to_space(*args, **kwargs): return array_ops.batch_to_space(*args, **kwargs)
PythonOpImpl
python
getsentry__sentry
src/sentry/sentry_metrics/indexer/limiters/writes.py
{ "start": 2319, "end": 3039 }
class ____: _writes_limiter: WritesLimiter _namespace: str _requests: Sequence[RequestedQuota] _grants: Sequence[GrantedQuota] _timestamp: Timestamp accepted_keys: UseCaseKeyCollection dropped_strings: Sequence[DroppedString] def __enter__(self) -> RateLimitState: return self @metrics.wraps("sentry_metrics.indexer.writes_limiter.exit") def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: """ Consumes the rate limits returned by `check_write_limits`. """ if exc_type is not None: return self._writes_limiter.rate_limiter.use_quotas(self._requests, self._grants, self._timestamp)
RateLimitState
python
getsentry__sentry
tests/sentry/tasks/test_process_buffer.py
{ "start": 258, "end": 960 }
class ____(TestCase): def test_constraints_model_name(self) -> None: with pytest.raises(AssertionError) as err: process_incr(model_name="group", columns={"times_seen": 1}, filters={"pk": 1}) assert "model_name must be in form" in str(err) @mock.patch("sentry.buffer.backend.process") def test_calls_process_with_model_name(self, process: mock.MagicMock) -> None: columns = {"times_seen": 1} filters = {"pk": 1} process_incr(model_name="sentry.Group", columns=columns, filters=filters) process.assert_called_once_with( model=Group, columns=columns, filters=filters, extra=None, signal_only=None )
ProcessIncrTest
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_map_metrics/column_values_match_like_pattern.py
{ "start": 440, "end": 1081 }
class ____(ColumnMapMetricProvider): condition_metric_name = "column_values.match_like_pattern" condition_value_keys = ("like_pattern",) @column_condition_partial(engine=SqlAlchemyExecutionEngine) def _sqlalchemy(cls, column, like_pattern, _dialect, **kwargs): like_pattern_expression = get_dialect_like_pattern_expression( column, _dialect, like_pattern ) if like_pattern_expression is None: logger.warning(f"Like patterns are not supported for dialect {_dialect.name!s}") raise NotImplementedError return like_pattern_expression
ColumnValuesMatchLikePattern
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_datasync.py
{ "start": 35121, "end": 39275 }
class ____(DataSyncTestCaseBase): def set_up_operator(self, task_id="test_datasync_delete_task_operator", task_arn="self"): if task_arn == "self": task_arn = self.task_arn # Create operator self.datasync = DataSyncOperator( task_id=task_id, dag=self.dag, task_arn=task_arn, delete_task_after_execution=True, wait_interval_seconds=0, ) def test_init(self, mock_get_conn): self.set_up_operator() # Airflow built-ins assert self.datasync.task_id == MOCK_DATA["delete_task_id"] # Defaults assert self.datasync.aws_conn_id == "aws_default" # Assignments assert self.datasync.task_arn == self.task_arn # ### Check mocks: mock_get_conn.assert_not_called() def test_init_fails(self, mock_get_conn): # ### Set up mocks: mock_get_conn.return_value = self.client # ### Begin tests: with pytest.raises(AirflowException): self.set_up_operator(task_arn=None) # ### Check mocks: mock_get_conn.assert_not_called() def test_delete_task(self, mock_get_conn): # ### Set up mocks: mock_get_conn.return_value = self.client # ### Begin tests: self.set_up_operator() # Check how many tasks and locations we have tasks = self.client.list_tasks() assert len(tasks["Tasks"]) == 1 locations = self.client.list_locations() assert len(locations["Locations"]) == 2 # Execute the task result = self.datasync.execute(None) assert result is not None assert result["TaskArn"] == self.task_arn # Assert -1 additional task and 0 additional locations tasks = self.client.list_tasks() assert len(tasks["Tasks"]) == 0 locations = self.client.list_locations() assert len(locations["Locations"]) == 2 # ### Check mocks: mock_get_conn.assert_called() def test_execute_specific_task(self, mock_get_conn): # ### Set up mocks: mock_get_conn.return_value = self.client # ### Begin tests: task_arn = self.client.create_task( SourceLocationArn=self.source_location_arn, DestinationLocationArn=self.destination_location_arn, )["TaskArn"] self.set_up_operator(task_arn=task_arn) result = self.datasync.execute(None) assert result["TaskArn"] == task_arn assert self.datasync.task_arn == task_arn # ### Check mocks: mock_get_conn.assert_called() @pytest.mark.db_test def test_return_value( self, mock_get_conn, session, clean_dags_dagruns_and_dagbundles, testing_dag_bundle ): """Test we return the right value -- that will get put in to XCom by the execution engine""" # ### Set up mocks: mock_get_conn.return_value = self.client # ### Begin tests: self.set_up_operator() if AIRFLOW_V_3_0_PLUS: from airflow.models.dag_version import DagVersion sync_dag_to_db(self.dag) dag_version = DagVersion.get_latest_version(self.dag.dag_id) ti = TaskInstance(task=self.datasync, dag_version_id=dag_version.id) dag_run = DagRun( dag_id=self.dag.dag_id, logical_date=timezone.utcnow(), run_id="test", run_type=DagRunType.MANUAL, state=DagRunState.RUNNING, ) else: dag_run = DagRun( dag_id=self.dag.dag_id, execution_date=timezone.utcnow(), run_id="test", run_type=DagRunType.MANUAL, state=DagRunState.RUNNING, ) ti = TaskInstance(task=self.datasync) ti.dag_run = dag_run session.add(ti) session.commit() result = self.datasync.execute(ti.get_template_context()) assert result["TaskArn"] == self.task_arn # ### Check mocks: mock_get_conn.assert_called()
TestDataSyncOperatorDelete
python
tensorflow__tensorflow
tensorflow/python/framework/type_spec_test.py
{ "start": 3237, "end": 3742 }
class ____(TwoTensorsSpec): def _serialize(self): if self.color == "smaller_tuple": return (self.x_shape, self.x_dtype, self.y_shape, self.y_dtype) elif self.color == "different_order": return (self.y_shape, self.x_shape, self.y_dtype, self.color, self.x_dtype) return (self.x_shape, self.x_dtype, self.y_shape, self.y_dtype, self.color) type_spec.register_type_spec_from_value_converter( TwoTensors, TwoTensorsSpec.from_value)
TwoTensorsSpecVariableSerialize
python
viewflow__viewflow
viewflow/workflow/fields.py
{ "start": 3806, "end": 4698 }
class ____(models.CharField): def __init__(self, *args, **kwargs): kwargs.setdefault("max_length", 255) super(TaskReferenceField, self).__init__(*args, **kwargs) def to_python(self, value): if value: return import_task_by_ref(value) # TODO Raise ValidationError return value def from_db_value(self, value, expression, connection): if value is None: return value try: return import_task_by_ref(value) except ImportError: return None def get_prep_value(self, value): # noqa D102 if value and not isinstance(value, str): return get_task_ref(value) return value def value_to_string(self, obj): # noqa D102 value = super(TaskReferenceField, self).value_from_object(obj) return self.get_prep_value(value)
TaskReferenceField
python
getsentry__sentry
tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py
{ "start": 7000, "end": 7250 }
class ____(BaseSafeMigrationTest): app = "good_flow_safe_run_sql_with_run_sql_disabled_app" migrate_from = "0001_initial" migrate_to = "0001_initial" def test(self) -> None: self.run_migration()
SafeRunSqlWithRunSqlDisabledTest
python
huggingface__transformers
src/transformers/models/reformer/modeling_reformer.py
{ "start": 48346, "end": 57829 }
class ____(nn.Module, EfficientAttentionMixin): def __init__(self, config, layer_idx=None): super().__init__() self.num_attention_heads = config.num_attention_heads self.chunk_length = config.local_attn_chunk_length self.num_chunks_before = config.local_num_chunks_before self.num_chunks_after = config.local_num_chunks_after self.is_decoder = config.is_decoder self.pad_token_id = config.pad_token_id self.attention_head_size = config.attention_head_size self.all_head_size = self.num_attention_heads * self.attention_head_size self.hidden_size = config.hidden_size self.layer_idx = layer_idx # projection matrices self.query = nn.Linear(self.hidden_size, self.all_head_size, bias=False) self.key = nn.Linear(self.hidden_size, self.all_head_size, bias=False) self.value = nn.Linear(self.hidden_size, self.all_head_size, bias=False) self.dropout = config.local_attention_probs_dropout_prob # save mask value here self.register_buffer("mask_value_float16", torch.tensor(-1e4), persistent=False) self.register_buffer("mask_value_float32", torch.tensor(-1e9), persistent=False) def forward( self, hidden_states, attention_mask=None, past_buckets_states=None, use_cache=False, output_attentions=False, **kwargs, ): sequence_length = hidden_states.shape[1] batch_size = hidden_states.shape[0] # check if cache shall be used and that hidden states are already cached if past_buckets_states is not None and len(past_buckets_states) > self.layer_idx: past_buckets = past_buckets_states.buckets_cache[self.layer_idx] past_states = past_buckets_states.states_cache[self.layer_idx] assert past_buckets.numel() == 0, ( "LocalSelfAttention should not make use of `buckets`. There seems to be an error when caching" " hidden_states_and_buckets." ) key_value_hidden_states = self._retrieve_relevant_hidden_states( past_states, self.chunk_length, self.num_chunks_before ) key_value_hidden_states = torch.cat([key_value_hidden_states, hidden_states], dim=1) # only query vector for last token query_vectors = self.query(hidden_states) # compute key and value for relevant chunk key_vectors = self.key(key_value_hidden_states) value_vectors = self.value(key_value_hidden_states) # free memory del key_value_hidden_states else: # project hidden_states to query, key and value query_vectors = self.query(hidden_states) key_vectors = self.key(hidden_states) value_vectors = self.value(hidden_states) # split last dim into `config.num_attention_heads` and `config.attention_head_size` query_vectors = self._split_hidden_size_dim(query_vectors, self.num_attention_heads, self.attention_head_size) key_vectors = self._split_hidden_size_dim(key_vectors, self.num_attention_heads, self.attention_head_size) value_vectors = self._split_hidden_size_dim(value_vectors, self.num_attention_heads, self.attention_head_size) assert query_vectors.shape[-1] == self.attention_head_size, ( f"last dim of query_key_vectors is {query_vectors.shape[-1]} but should be {self.attention_head_size}." ) assert key_vectors.shape[-1] == self.attention_head_size, ( f"last dim of query_key_vectors is {key_vectors.shape[-1]} but should be {self.attention_head_size}." ) assert value_vectors.shape[-1] == self.attention_head_size, ( f"last dim of query_key_vectors is {value_vectors.shape[-1]} but should be {self.attention_head_size}." ) if self.chunk_length is None: assert self.num_chunks_before == 0 and self.num_chunks_after == 0, ( "If `config.chunk_length` is `None`, make sure `config.num_chunks_after` and" " `config.num_chunks_before` are set to 0." ) # normalize key vectors key_vectors = key_vectors / np.sqrt(self.attention_head_size) # get sequence length indices indices = torch.arange(sequence_length, device=query_vectors.device).repeat( batch_size, self.num_attention_heads, 1 ) # if one should do normal n^2 self-attention do_standard_self_attention = sequence_length <= self.chunk_length # if input should be chunked if not do_standard_self_attention: # chunk vectors # B x Num_Attn_Head x Seq_Len // chunk_len x chunk_len x attn_head_size query_vectors = self._split_seq_length_dim_to( query_vectors, -1, self.chunk_length, self.num_attention_heads, self.attention_head_size, ) key_vectors = self._split_seq_length_dim_to( key_vectors, -1, self.chunk_length, self.num_attention_heads, self.attention_head_size, ) value_vectors = self._split_seq_length_dim_to( value_vectors, -1, self.chunk_length, self.num_attention_heads, self.attention_head_size, ) # chunk indices query_indices = self._split_seq_length_dim_to(indices, -1, self.chunk_length, self.num_attention_heads) key_indices = self._split_seq_length_dim_to(indices, -1, self.chunk_length, self.num_attention_heads) # append chunks before and after key_vectors = self._look_adjacent(key_vectors, self.num_chunks_before, self.num_chunks_after) value_vectors = self._look_adjacent(value_vectors, self.num_chunks_before, self.num_chunks_after) key_indices = self._look_adjacent(key_indices, self.num_chunks_before, self.num_chunks_after) else: query_indices = key_indices = indices # query-key matmul: QK^T query_key_dots = torch.matmul(query_vectors, key_vectors.transpose(-1, -2)) # free memory del query_vectors, key_vectors mask = self._compute_attn_mask( query_indices, key_indices, attention_mask, query_key_dots.shape, do_standard_self_attention ) if mask is not None: # get mask tensor depending on half precision or not if query_key_dots.dtype == torch.float16: mask_value = self.mask_value_float16.half() else: mask_value = self.mask_value_float32 query_key_dots = torch.where(mask, query_key_dots, mask_value) # free memory del mask # softmax logits = torch.logsumexp(query_key_dots, dim=-1, keepdim=True) attention_probs = torch.exp(query_key_dots - logits) # free memory del logits # dropout attention_probs = nn.functional.dropout(attention_probs, p=self.dropout, training=self.training) # attend values out_vectors = torch.matmul(attention_probs, value_vectors) # free memory del value_vectors # merge chunk length if not do_standard_self_attention: out_vectors = out_vectors.flatten(start_dim=2, end_dim=3) assert out_vectors.shape == ( batch_size, self.num_attention_heads, sequence_length, self.attention_head_size, ) out_vectors = self._merge_hidden_size_dims(out_vectors, self.num_attention_heads, self.attention_head_size) if output_attentions is False: attention_probs = () return LocalSelfAttentionOutput(hidden_states=out_vectors, attention_probs=attention_probs) def _compute_attn_mask( self, query_indices, key_indices, attention_mask, query_key_dots_shape, do_standard_self_attention ): # chunk attention mask and look before and after if attention_mask is not None: attention_mask = attention_mask.to(torch.bool)[:, None, :] if not do_standard_self_attention: attention_mask = self._split_seq_length_dim_to(attention_mask, -1, self.chunk_length, 1) attention_mask = self._look_adjacent(attention_mask, self.num_chunks_before, self.num_chunks_after) # create attn_mask attention_mask = attention_mask.unsqueeze(-2).expand(query_key_dots_shape) # Causal mask if self.is_decoder is True: causal_mask = torch.ge(query_indices.unsqueeze(-1), key_indices.unsqueeze(-2)).to(query_indices.device) # add attention mask if not None if attention_mask is not None: attention_mask = causal_mask * attention_mask else: attention_mask = causal_mask return attention_mask @staticmethod def _retrieve_relevant_hidden_states(previous_hidden_states, chunk_length, num_chunks_before): start_position = ((previous_hidden_states.shape[1] // chunk_length) - num_chunks_before) * chunk_length return previous_hidden_states[:, start_position:]
LocalSelfAttention
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_execute_pipeline.py
{ "start": 1858, "end": 28745 }
class ____(ExecutingGraphQLContextTestMatrix): def test_start_pipeline_execution(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "csv_hello_world") result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, "runConfigData": csv_hello_world_ops_config(), } }, ) assert not result.errors assert result.data # just test existence assert result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess" assert uuid.UUID(result.data["launchPipelineExecution"]["run"]["runId"]) assert ( result.data["launchPipelineExecution"]["run"]["pipeline"]["name"] == "csv_hello_world" ) def test_start_pipeline_execution_serialized_config( self, graphql_context: WorkspaceRequestContext ): selector = infer_job_selector(graphql_context, "csv_hello_world") result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, "runConfigData": json.dumps(csv_hello_world_ops_config()), } }, ) assert not result.errors assert result.data # just test existence assert result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess" assert uuid.UUID(result.data["launchPipelineExecution"]["run"]["runId"]) assert ( result.data["launchPipelineExecution"]["run"]["pipeline"]["name"] == "csv_hello_world" ) def test_start_pipeline_execution_malformed_config( self, graphql_context: WorkspaceRequestContext ): selector = infer_job_selector(graphql_context, "csv_hello_world") result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, "runConfigData": '{"foo": {{{{', } }, ) assert not result.errors assert result.data assert result.data["launchPipelineExecution"]["__typename"] == "PythonError" assert "yaml.parser.ParserError" in result.data["launchPipelineExecution"]["message"] def test_basic_start_pipeline_execution_with_pipeline_def_tags( self, graphql_context: WorkspaceRequestContext ): selector = infer_job_selector(graphql_context, "hello_world_with_tags") result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, }, }, ) assert not result.errors tags_by_key = { tag["key"]: tag["value"] for tag in result.data["launchPipelineExecution"]["run"]["tags"] } assert tags_by_key["tag_key"] == "tag_value" # just test existence assert result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess" assert uuid.UUID(result.data["launchPipelineExecution"]["run"]["runId"]) assert ( result.data["launchPipelineExecution"]["run"]["pipeline"]["name"] == "hello_world_with_tags" ) # ensure provided tags override def tags result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, "executionMetadata": { "tags": [{"key": "tag_key", "value": "new_tag_value"}], }, }, }, ) assert not result.errors tags_by_key = { tag["key"]: tag["value"] for tag in result.data["launchPipelineExecution"]["run"]["tags"] } assert tags_by_key["tag_key"] == "new_tag_value" def test_basic_start_pipeline_execution_with_non_existent_preset( self, graphql_context: WorkspaceRequestContext ): selector = infer_job_selector(graphql_context, "csv_hello_world") result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, "preset": "undefined_preset", } }, ) assert not result.errors assert result.data assert result.data["launchPipelineExecution"]["__typename"] == "PresetNotFoundError" assert ( result.data["launchPipelineExecution"]["message"] == "Preset undefined_preset not found in pipeline csv_hello_world." ) def test_basic_start_pipeline_execution_config_failure( self, graphql_context: WorkspaceRequestContext ): selector = infer_job_selector(graphql_context, "csv_hello_world") result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, "runConfigData": {"ops": {"sum_op": {"inputs": {"num": 384938439}}}}, } }, ) assert not result.errors assert result.data assert result.data["launchPipelineExecution"]["__typename"] == "RunConfigValidationInvalid" def test_basis_start_pipeline_not_found_error(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "sjkdfkdjkf") result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, "runConfigData": {"ops": {"sum_op": {"inputs": {"num": "test.csv"}}}}, } }, ) assert not result.errors assert result.data # just test existence assert result.data["launchPipelineExecution"]["__typename"] == "PipelineNotFoundError" assert result.data["launchPipelineExecution"]["pipelineName"] == "sjkdfkdjkf" def _csv_hello_world_event_sequence(self): # expected non engine event sequence from executing csv_hello_world pipeline return [ "RunStartingEvent", "RunStartEvent", "ResourceInitStartedEvent", "ResourceInitSuccessEvent", "LogsCapturedEvent", "ExecutionStepStartEvent", "ExecutionStepInputEvent", "ExecutionStepOutputEvent", "LogMessageEvent", "HandledOutputEvent", "ExecutionStepSuccessEvent", "ExecutionStepStartEvent", "LogMessageEvent", "LoadedInputEvent", "ExecutionStepInputEvent", "ExecutionStepOutputEvent", "LogMessageEvent", "HandledOutputEvent", "ExecutionStepSuccessEvent", "RunSuccessEvent", ] def _legacy_csv_hello_world_event_sequence(self): # same as above, but matching when the instance has a legacy compute log manager which emits # event for every step return [ "RunStartingEvent", "RunStartEvent", "ResourceInitStartedEvent", "ResourceInitSuccessEvent", "LogsCapturedEvent", "ExecutionStepStartEvent", "ExecutionStepInputEvent", "ExecutionStepOutputEvent", "LogMessageEvent", "HandledOutputEvent", "ExecutionStepSuccessEvent", "LogsCapturedEvent", "ExecutionStepStartEvent", "LogMessageEvent", "LoadedInputEvent", "ExecutionStepInputEvent", "ExecutionStepOutputEvent", "LogMessageEvent", "HandledOutputEvent", "ExecutionStepSuccessEvent", "RunSuccessEvent", ] def test_basic_start_pipeline_execution_and_subscribe( self, graphql_context: WorkspaceRequestContext ): selector = infer_job_selector(graphql_context, "csv_hello_world") run_logs = sync_execute_get_run_log_data( context=graphql_context, variables={ "executionParams": { "selector": selector, "runConfigData": { "ops": { "sum_op": { "inputs": {"num": file_relative_path(__file__, "../data/num.csv")} } } }, } }, ) assert run_logs["__typename"] == "PipelineRunLogsSubscriptionSuccess" non_engine_event_types = [ message["__typename"] for message in run_logs["messages"] if message["__typename"] not in ("EngineEvent", "RunEnqueuedEvent", "RunDequeuedEvent") ] assert ( non_engine_event_types == self._csv_hello_world_event_sequence() or non_engine_event_types == self._legacy_csv_hello_world_event_sequence() ) def test_basic_start_pipeline_and_fetch(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "csv_hello_world") exc_result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, "runConfigData": { "ops": { "sum_op": { "inputs": {"num": file_relative_path(__file__, "../data/num.csv")} } } }, } }, ) assert not exc_result.errors assert exc_result.data assert exc_result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess" # block until run finishes wait_for_runs_to_finish(graphql_context.instance) events_result = execute_dagster_graphql( graphql_context, RUN_EVENTS_QUERY, variables={"runId": exc_result.data["launchPipelineExecution"]["run"]["runId"]}, ) assert not events_result.errors assert events_result.data assert events_result.data["logsForRun"]["__typename"] == "EventConnection" non_engine_event_types = [ message["__typename"] for message in events_result.data["logsForRun"]["events"] if message["__typename"] not in ("EngineEvent", "RunEnqueuedEvent", "RunDequeuedEvent") ] assert ( non_engine_event_types == self._csv_hello_world_event_sequence() or non_engine_event_types == self._legacy_csv_hello_world_event_sequence() ) with mock.patch.object( type(graphql_context), "records_for_run_default_limit", new_callable=mock.PropertyMock, ) as mock_records_for_run_default_limit: mock_records_for_run_default_limit.return_value = 5 events_result = execute_dagster_graphql( graphql_context, RUN_EVENTS_QUERY, variables={"runId": exc_result.data["launchPipelineExecution"]["run"]["runId"]}, ) assert not events_result.errors assert events_result.data assert events_result.data["logsForRun"]["__typename"] == "EventConnection" assert len(events_result.data["logsForRun"]["events"]) == 5 # exceeding default limit results in an error assert events_result.data["logsForRun"]["cursor"] events_result = execute_dagster_graphql( graphql_context, RUN_EVENTS_QUERY, variables={ "limit": 10, "runId": exc_result.data["launchPipelineExecution"]["run"]["runId"], }, ) assert not events_result.errors assert events_result.data assert events_result.data["logsForRun"]["__typename"] == "PythonError" assert ( "Limit of 10 is too large. Max is 5" in events_result.data["logsForRun"]["message"] ) # passing in a lower value than max chunk size is respected events_result = execute_dagster_graphql( graphql_context, RUN_EVENTS_QUERY, variables={ "limit": 4, "runId": exc_result.data["launchPipelineExecution"]["run"]["runId"], }, ) assert not events_result.errors assert events_result.data assert events_result.data["logsForRun"]["__typename"] == "EventConnection" assert len(events_result.data["logsForRun"]["events"]) == 4 assert events_result.data["logsForRun"]["cursor"] def test_basic_start_pipeline_and_poll(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "csv_hello_world") exc_result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, "runConfigData": { "ops": { "sum_op": { "inputs": {"num": file_relative_path(__file__, "../data/num.csv")} } } }, } }, ) assert not exc_result.errors assert exc_result.data assert exc_result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess" def _fetch_events(cursor): events_result = execute_dagster_graphql( graphql_context, RUN_EVENTS_QUERY, variables={ "runId": exc_result.data["launchPipelineExecution"]["run"]["runId"], "cursor": cursor, }, ) assert not events_result.errors assert events_result.data assert events_result.data["logsForRun"]["__typename"] == "EventConnection" return ( events_result.data["logsForRun"]["events"], events_result.data["logsForRun"]["cursor"], ) full_logs = [] cursor = None iters = 0 # do 3 polls, then fetch after waiting for execution to finish while iters < 3: _events, _cursor = _fetch_events(cursor) full_logs.extend(_events) cursor = _cursor iters += 1 time.sleep(0.05) # 50ms # block until run finishes wait_for_runs_to_finish(graphql_context.instance) _events, _cursor = _fetch_events(cursor) full_logs.extend(_events) non_engine_event_types = [ message["__typename"] for message in full_logs if message["__typename"] not in ("EngineEvent", "RunEnqueuedEvent", "RunDequeuedEvent") ] assert ( non_engine_event_types == self._csv_hello_world_event_sequence() or non_engine_event_types == self._legacy_csv_hello_world_event_sequence() ) def test_step_failure(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "naughty_programmer_job") result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, } }, ) assert result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess", str( result.data ) run_id = result.data["launchPipelineExecution"]["run"]["runId"] wait_for_runs_to_finish(graphql_context.instance) logs_result = execute_dagster_graphql( graphql_context, STEP_FAILURE_EVENTS_QUERY, variables={ "runId": run_id, }, ) assert not logs_result.errors assert logs_result.data assert logs_result.data["logsForRun"]["__typename"] == "EventConnection" run_logs = logs_result.data["logsForRun"]["events"] step_run_log_entry = _get_step_run_log_entry( run_logs, "throw_a_thing", "ExecutionStepFailureEvent" ) assert step_run_log_entry assert step_run_log_entry["message"] == 'Execution of step "throw_a_thing" failed.' assert step_run_log_entry["error"] assert step_run_log_entry["level"] == "ERROR" assert step_run_log_entry["failureMetadata"] assert step_run_log_entry["failureMetadata"]["metadataEntries"] == [ { "__typename": "BoolMetadataEntry", "label": "top_level", "description": None, "boolValue": True, } ] causes = step_run_log_entry["error"]["causes"] assert len(causes) == 2 assert [cause["message"] for cause in causes] == [ "Exception: Outer exception\n", "Exception: bad programmer, bad\n", ] assert all([len(cause["stack"]) > 0 for cause in causes]) error_chain = step_run_log_entry["error"]["errorChain"] assert len(error_chain) == 3 assert [ (chain_link["error"]["message"], chain_link["isExplicitLink"]) for chain_link in error_chain ] == [ ("Exception: Outer exception\n", True), ("Exception: bad programmer, bad\n", True), ("Exception: The inner sanctum\n", False), ] def test_subscribe_bad_run_id(self, graphql_context: WorkspaceRequestContext): run_id = make_new_run_id() subscribe_results = execute_dagster_graphql_subscription( graphql_context, SUBSCRIPTION_QUERY, variables={"runId": run_id} ) assert len(subscribe_results) == 1 subscribe_result = subscribe_results[0] assert ( subscribe_result.data["pipelineRunLogs"]["__typename"] == "PipelineRunLogsSubscriptionFailure" ) assert subscribe_result.data["pipelineRunLogs"]["missingRunId"] == run_id def test_basic_sync_execution_no_config(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "no_config_job") result = sync_execute_get_run_log_data( context=graphql_context, variables={ "executionParams": { "selector": selector, "runConfigData": None, } }, ) logs = result["messages"] assert isinstance(logs, list) assert has_event_of_type(logs, "RunStartEvent") assert has_event_of_type(logs, "RunSuccessEvent") assert not has_event_of_type(logs, "RunFailureEvent") def test_basic_filesystem_sync_execution(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "csv_hello_world") result = sync_execute_get_run_log_data( context=graphql_context, variables={ "executionParams": { "selector": selector, "runConfigData": csv_hello_world_ops_config(), } }, ) logs = result["messages"] assert isinstance(logs, list) assert has_event_of_type(logs, "RunStartEvent") assert has_event_of_type(logs, "RunSuccessEvent") assert not has_event_of_type(logs, "RunFailureEvent") run_start_event = first_event_of_type(logs, "RunStartEvent") assert run_start_event and run_start_event["level"] == "DEBUG" sum_op_output = get_step_output_event(logs, "sum_op") assert sum_op_output assert sum_op_output["stepKey"] == "sum_op" assert sum_op_output["outputName"] == "result" def test_basic_start_pipeline_execution_with_tags( self, graphql_context: WorkspaceRequestContext ): selector = infer_job_selector(graphql_context, "csv_hello_world") result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, "runConfigData": csv_hello_world_ops_config(), "executionMetadata": { "tags": [{"key": "dagster/test_key", "value": "test_value"}] }, } }, ) assert not result.errors assert result.data assert result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess" run = result.data["launchPipelineExecution"]["run"] run_id = run["runId"] assert len(run["tags"]) > 0 assert any( [x["key"] == "dagster/test_key" and x["value"] == "test_value" for x in run["tags"]] ) # Check run storage runs_with_tag = graphql_context.instance.get_runs( filters=RunsFilter(tags={"dagster/test_key": "test_value"}) ) assert len(runs_with_tag) == 1 assert runs_with_tag[0].run_id == run_id def test_start_job_execution_with_default_config( self, graphql_context: WorkspaceRequestContext ): selector = infer_job_selector(graphql_context, "job_with_default_config") result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, } }, ) # should succeed for this job, even when not providing config because it should # pick up the job default run_config assert not result.errors assert result.data assert result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess" def test_two_ins_job_subset_and_config(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "two_ins_job", ["op_1", "op_with_2_ins"]) run_config = { "ops": {"op_with_2_ins": {"inputs": {"in_2": {"value": 2}}}}, } result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUTATION, variables={ "executionParams": { "selector": selector, "runConfigData": run_config, } }, ) assert not result.errors assert result.data assert result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess" assert set(result.data["launchPipelineExecution"]["run"]["resolvedOpSelection"]) == set( [ "op_1", "op_with_2_ins", ] ) def test_nested_graph_op_selection_and_config(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector( graphql_context, "nested_job", ["subgraph.adder", "subgraph.op_1"] ) run_config = {"ops": {"subgraph": {"ops": {"adder": {"inputs": {"num2": 20}}}}}} result = sync_execute_get_run_log_data( context=graphql_context, variables={ "executionParams": { "selector": selector, "runConfigData": run_config, } }, ) logs = result["messages"] assert isinstance(logs, list) assert step_did_succeed(logs, "subgraph.adder") assert step_did_succeed(logs, "subgraph.op_1") assert step_did_not_run(logs, "plus_one") assert step_did_not_run(logs, "subgraph.op_2") def test_nested_graph_op_selection_and_config_with_non_null_asset_and_check_selection( self, graphql_context: WorkspaceRequestContext ): selector = infer_job_selector( graphql_context, "nested_job", ["subgraph.adder", "subgraph.op_1"], asset_selection=[], asset_check_selection=[], ) run_config = {"ops": {"subgraph": {"ops": {"adder": {"inputs": {"num2": 20}}}}}} result = sync_execute_get_run_log_data( context=graphql_context, variables={ "executionParams": { "selector": selector, "runConfigData": run_config, } }, ) logs = result["messages"] assert isinstance(logs, list) assert step_did_succeed(logs, "subgraph.adder") assert step_did_succeed(logs, "subgraph.op_1") assert step_did_not_run(logs, "plus_one") assert step_did_not_run(logs, "subgraph.op_2") def _get_step_run_log_entry(pipeline_run_logs, step_key, typename): for message_data in pipeline_run_logs: if message_data["__typename"] == typename: if message_data["stepKey"] == step_key: return message_data def first_event_of_type(logs, message_type) -> Optional[dict[str, Any]]: for log in logs: if log["__typename"] == message_type: return log return None def has_event_of_type(logs, message_type): return first_event_of_type(logs, message_type) is not None def get_step_output_event(logs, step_key, output_name="result"): for log in logs: if ( log["__typename"] == "ExecutionStepOutputEvent" and log["stepKey"] == step_key and log["outputName"] == output_name ): return log return None
TestExecutePipeline
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_relationship.py
{ "start": 1889, "end": 5001 }
class ____(fixtures.MappedTest): run_setup_mappers = "once" @classmethod def define_tables(cls, metadata): Table( "people", metadata, Column( "person_id", Integer, primary_key=True, test_needs_autoincrement=True, ), Column("name", String(50)), Column("type", String(30)), ) Table( "engineers", metadata, Column( "person_id", Integer, ForeignKey("people.person_id"), primary_key=True, ), Column("primary_language", String(50)), Column("reports_to_id", Integer, ForeignKey("people.person_id")), ) @classmethod def setup_mappers(cls): engineers, people = cls.tables.engineers, cls.tables.people cls.mapper_registry.map_imperatively( Person, people, polymorphic_on=people.c.type, polymorphic_identity="person", ) cls.mapper_registry.map_imperatively( Engineer, engineers, inherits=Person, inherit_condition=engineers.c.person_id == people.c.person_id, polymorphic_identity="engineer", properties={ "reports_to": relationship( Person, primaryjoin=( people.c.person_id == engineers.c.reports_to_id ), ) }, ) def test_has(self): p1 = Person(name="dogbert") e1 = Engineer(name="dilbert", primary_language="java", reports_to=p1) sess = fixture_session() sess.add(p1) sess.add(e1) sess.flush() sess.expunge_all() eq_( sess.query(Engineer) .filter(Engineer.reports_to.has(Person.name == "dogbert")) .first(), Engineer(name="dilbert"), ) def test_oftype_aliases_in_exists(self): e1 = Engineer(name="dilbert", primary_language="java") e2 = Engineer(name="wally", primary_language="c++", reports_to=e1) sess = fixture_session() sess.add_all([e1, e2]) sess.flush() eq_( sess.query(Engineer) .filter( Engineer.reports_to.of_type(Engineer).has( Engineer.name == "dilbert" ) ) .first(), e2, ) def test_join(self): p1 = Person(name="dogbert") e1 = Engineer(name="dilbert", primary_language="java", reports_to=p1) sess = fixture_session() sess.add(p1) sess.add(e1) sess.flush() sess.expunge_all() pa = aliased(Person) eq_( sess.query(Engineer) .join(pa, Engineer.reports_to) .filter(pa.name == "dogbert") .first(), Engineer(name="dilbert"), )
SelfReferentialTestJoinedToBase
python
pandas-dev__pandas
pandas/tests/frame/indexing/test_indexing.py
{ "start": 52559, "end": 54702 }
class ____: def test_setitem(self): df = DataFrame( {"A": np.arange(3), "B": [2**63, 2**63 + 5, 2**63 + 10]}, dtype=np.uint64, ) idx = df["A"].rename("foo") # setitem assert "C" not in df.columns df["C"] = idx tm.assert_series_equal(df["C"], Series(idx, name="C")) assert "D" not in df.columns df["D"] = "foo" df["D"] = idx tm.assert_series_equal(df["D"], Series(idx, name="D")) del df["D"] # With NaN: because uint64 has no NaN element, # the column should be cast to object. df2 = df.copy() with pytest.raises(TypeError, match="Invalid value"): df2.iloc[1, 1] = pd.NaT df2.iloc[1, 2] = pd.NaT def test_object_casting_indexing_wraps_datetimelike(): # GH#31649, check the indexing methods all the way down the stack df = DataFrame( { "A": [1, 2], "B": date_range("2000", periods=2, unit="ns"), "C": pd.timedelta_range("1 Day", periods=2), } ) ser = df.loc[0] assert isinstance(ser.values[1], Timestamp) assert isinstance(ser.values[2], pd.Timedelta) ser = df.iloc[0] assert isinstance(ser.values[1], Timestamp) assert isinstance(ser.values[2], pd.Timedelta) ser = df.xs(0, axis=0) assert isinstance(ser.values[1], Timestamp) assert isinstance(ser.values[2], pd.Timedelta) mgr = df._mgr mgr._rebuild_blknos_and_blklocs() arr = mgr.fast_xs(0).array assert isinstance(arr[1], Timestamp) assert isinstance(arr[2], pd.Timedelta) blk = mgr.blocks[mgr.blknos[1]] assert blk.dtype == "M8[ns]" # we got the right block val = blk.iget((0, 0)) assert isinstance(val, Timestamp) blk = mgr.blocks[mgr.blknos[2]] assert blk.dtype == "m8[ns]" # we got the right block val = blk.iget((0, 0)) assert isinstance(val, pd.Timedelta) msg1 = r"Cannot setitem on a Categorical with a new category( \(.*\))?, set the" msg2 = "Cannot set a Categorical with another, without identical categories"
TestDataFrameIndexingUInt64
python
openai__openai-python
src/openai/types/conversations/item_create_params.py
{ "start": 378, "end": 874 }
class ____(TypedDict, total=False): items: Required[Iterable[ResponseInputItemParam]] """The items to add to the conversation. You may add up to 20 items at a time.""" include: List[ResponseIncludable] """Additional fields to include in the response. See the `include` parameter for [listing Conversation items above](https://platform.openai.com/docs/api-reference/conversations/list-items#conversations_list_items-include) for more information. """
ItemCreateParams
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py
{ "start": 3291, "end": 3489 }
class ____: def method(self): if True: def function(): pass # end # no error @decorator async def function(data: None) -> None: ... # end # no error
Class
python
tornadoweb__tornado
tornado/web.py
{ "start": 126074, "end": 126784 }
class ____: """A transform modifies the result of an HTTP request (e.g., GZip encoding) Applications are not expected to create their own OutputTransforms or interact with them directly; the framework chooses which transforms (if any) to apply. """ def __init__(self, request: httputil.HTTPServerRequest) -> None: pass def transform_first_chunk( self, status_code: int, headers: httputil.HTTPHeaders, chunk: bytes, finishing: bool, ) -> Tuple[int, httputil.HTTPHeaders, bytes]: return status_code, headers, chunk def transform_chunk(self, chunk: bytes, finishing: bool) -> bytes: return chunk
OutputTransform
python
numba__numba
numba/cuda/cudamath.py
{ "start": 3249, "end": 3512 }
class ____(ConcreteTemplate): cases = [ signature(types.float32, types.float32, types.int32), signature(types.float64, types.float64, types.int32), ] @infer_global(math.isinf) @infer_global(math.isnan) @infer_global(math.isfinite)
Math_ldexp
python
kamyu104__LeetCode-Solutions
Python/string-compression-ii.py
{ "start": 39, "end": 985 }
class ____(object): def getLengthOfOptimalCompression(self, s, k): """ :type s: str :type k: int :rtype: int """ def length(cnt): l = 2 if cnt >= 2 else 1 while cnt >= 10: l += 1 cnt //= 10 return l dp = [[len(s)]*(k+1) for _ in xrange(len(s)+1)] dp[0][0] = 0 for i in xrange(1, len(s)+1): for j in xrange(k+1): if i-1 >= 0 and j-1 >= 0: dp[i][j] = min(dp[i][j], dp[i-1][j-1]) keep = delete = 0 for m in xrange(i, len(s)+1): if s[i-1] == s[m-1]: keep += 1 else: delete += 1 if j+delete <= k: dp[m][j+delete] = min(dp[m][j+delete], dp[i-1][j]+length(keep)) return dp[len(s)][k]
Solution
python
tiangolo__fastapi
fastapi/background.py
{ "start": 214, "end": 1793 }
class ____(StarletteBackgroundTasks): """ A collection of background tasks that will be called after a response has been sent to the client. Read more about it in the [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). ## Example ```python from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f"notification for {email}: {message}" email_file.write(content) @app.post("/send-notification/{email}") async def send_notification(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_notification, email, message="some notification") return {"message": "Notification sent in the background"} ``` """ def add_task( self, func: Annotated[ Callable[P, Any], Doc( """ The function to call after the response is sent. It can be a regular `def` function or an `async def` function. """ ), ], *args: P.args, **kwargs: P.kwargs, ) -> None: """ Add a function to be called in the background after the response is sent. Read more about it in the [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). """ return super().add_task(func, *args, **kwargs)
BackgroundTasks
python
keras-team__keras
keras/src/ops/math.py
{ "start": 9104, "end": 11293 }
class ____(Operation): def __init__(self, sequence_length, sequence_stride, *, name=None): super().__init__(name=name) self.sequence_length = sequence_length self.sequence_stride = sequence_stride def compute_output_spec(self, x): if len(x.shape) < 1: raise ValueError( f"Input should have rank >= 1. " f"Received: input.shape = {x.shape}" ) if x.shape[-1] is not None: num_sequences = ( 1 + (x.shape[-1] - self.sequence_length) // self.sequence_stride ) else: num_sequences = None new_shape = x.shape[:-1] + (num_sequences, self.sequence_length) return KerasTensor(shape=new_shape, dtype=x.dtype) def call(self, x): return backend.math.extract_sequences( x, sequence_length=self.sequence_length, sequence_stride=self.sequence_stride, ) @keras_export("keras.ops.extract_sequences") def extract_sequences(x, sequence_length, sequence_stride): """Expands the dimension of last axis into sequences of `sequence_length`. Slides a window of size `sequence_length` over the last axis of the input with a stride of `sequence_stride`, replacing the last axis with `[num_sequences, sequence_length]` sequences. If the dimension along the last axis is N, the number of sequences can be computed by: `num_sequences = 1 + (N - sequence_length) // sequence_stride` Args: x: Input tensor. sequence_length: An integer representing the sequences length. sequence_stride: An integer representing the sequences hop size. Returns: A tensor of sequences with shape [..., num_sequences, sequence_length]. Example: >>> x = keras.ops.convert_to_tensor([1, 2, 3, 4, 5, 6]) >>> extract_sequences(x, 3, 2) array([[1, 2, 3], [3, 4, 5]]) """ if any_symbolic_tensors((x,)): return ExtractSequences(sequence_length, sequence_stride).symbolic_call( x ) return backend.math.extract_sequences(x, sequence_length, sequence_stride)
ExtractSequences
python
PyCQA__pylint
pylint/pyreverse/inspector.py
{ "start": 1280, "end": 1719 }
class ____: """Mixin adding the ability to generate integer uid.""" def __init__(self, start_value: int = 0) -> None: self.id_count = start_value def init_counter(self, start_value: int = 0) -> None: """Init the id counter.""" self.id_count = start_value def generate_id(self) -> int: """Generate a new identifier.""" self.id_count += 1 return self.id_count
IdGeneratorMixIn
python
pandas-dev__pandas
asv_bench/benchmarks/series_methods.py
{ "start": 5502, "end": 5782 }
class ____: params = [10**3, 10**4, 10**5] param_names = ["N"] def setup(self, N): self.s = Series(np.random.randint(0, N, size=10 * N)).astype("object") def time_value_counts(self, N): self.s.value_counts(dropna=False)
ValueCountsObjectDropNAFalse
python
dask__distributed
distributed/shuffle/_exceptions.py
{ "start": 200, "end": 294 }
class ____(Exception): """Raised when data is not available in the buffer"""
DataUnavailable
python
scipy__scipy
scipy/stats/_discrete_distns.py
{ "start": 3548, "end": 5167 }
class ____(binom_gen): r"""A Bernoulli discrete random variable. %(before_notes)s Notes ----- The probability mass function for `bernoulli` is: .. math:: f(k) = \begin{cases}1-p &\text{if } k = 0\\ p &\text{if } k = 1\end{cases} for :math:`k` in :math:`\{0, 1\}`, :math:`0 \leq p \leq 1` `bernoulli` takes :math:`p` as shape parameter, where :math:`p` is the probability of a single success and :math:`1-p` is the probability of a single failure. %(after_notes)s %(example)s """ def _shape_info(self): return [_ShapeInfo("p", False, (0, 1), (True, True))] def _rvs(self, p, size=None, random_state=None): return binom_gen._rvs(self, 1, p, size=size, random_state=random_state) def _argcheck(self, p): return (p >= 0) & (p <= 1) def _get_support(self, p): # Overrides binom_gen._get_support!x return self.a, self.b def _logpmf(self, x, p): return binom._logpmf(x, 1, p) def _pmf(self, x, p): # bernoulli.pmf(k) = 1-p if k = 0 # = p if k = 1 return binom._pmf(x, 1, p) def _cdf(self, x, p): return binom._cdf(x, 1, p) def _sf(self, x, p): return binom._sf(x, 1, p) def _isf(self, x, p): return binom._isf(x, 1, p) def _ppf(self, q, p): return binom._ppf(q, 1, p) def _stats(self, p): return binom._stats(1, p) def _entropy(self, p): return entr(p) + entr(1-p) bernoulli = bernoulli_gen(b=1, name='bernoulli')
bernoulli_gen
python
pypa__setuptools
setuptools/_vendor/typeguard/_importhook.py
{ "start": 4575, "end": 6387 }
class ____: """ A handle that can be used to uninstall the Typeguard import hook. """ def __init__(self, hook: MetaPathFinder): self.hook = hook def __enter__(self) -> None: pass def __exit__( self, exc_type: type[BaseException], exc_val: BaseException, exc_tb: TracebackType, ) -> None: self.uninstall() def uninstall(self) -> None: """Uninstall the import hook.""" try: sys.meta_path.remove(self.hook) except ValueError: pass # already removed def install_import_hook( packages: Iterable[str] | None = None, *, cls: type[TypeguardFinder] = TypeguardFinder, ) -> ImportHookManager: """ Install an import hook that instruments functions for automatic type checking. This only affects modules loaded **after** this hook has been installed. :param packages: an iterable of package names to instrument, or ``None`` to instrument all packages :param cls: a custom meta path finder class :return: a context manager that uninstalls the hook on exit (or when you call ``.uninstall()``) .. versionadded:: 2.6 """ if packages is None: target_packages: list[str] | None = None elif isinstance(packages, str): target_packages = [packages] else: target_packages = list(packages) for finder in sys.meta_path: if ( isclass(finder) and finder.__name__ == "PathFinder" and hasattr(finder, "find_spec") ): break else: raise RuntimeError("Cannot find a PathFinder in sys.meta_path") hook = cls(target_packages, finder) sys.meta_path.insert(0, hook) return ImportHookManager(hook)
ImportHookManager
python
pypa__warehouse
tests/unit/email/ses/test_views.py
{ "start": 2422, "end": 4004 }
class ____: def test_raises_when_invalid_type(self): request = pretend.stub(json_body={"Type": "Notification"}) with pytest.raises(HTTPBadRequest): views.confirm_subscription(request) def test_confirms(self, monkeypatch): data = { "Type": "SubscriptionConfirmation", "TopicArn": "This is a Topic!", "Token": "This is My Token", } aws_client = pretend.stub( confirm_subscription=pretend.call_recorder(lambda *a, **kw: None) ) aws_session = pretend.stub( client=pretend.call_recorder(lambda c, region_name: aws_client) ) request = pretend.stub( json_body=data, find_service=lambda name: {"aws.session": aws_session}[name], registry=pretend.stub(settings={"mail.region": "us-west-2"}), ) verify_sns_message = pretend.call_recorder(lambda *a, **kw: None) monkeypatch.setattr(views, "_verify_sns_message", verify_sns_message) response = views.confirm_subscription(request) assert response.status_code == 200 assert verify_sns_message.calls == [pretend.call(request, data)] assert aws_session.client.calls == [ pretend.call("sns", region_name="us-west-2") ] assert aws_client.confirm_subscription.calls == [ pretend.call( TopicArn=data["TopicArn"], Token=data["Token"], AuthenticateOnUnsubscribe="true", ) ]
TestConfirmSubscription
python
huggingface__transformers
src/transformers/models/clvp/modeling_clvp.py
{ "start": 43764, "end": 50549 }
class ____(ClvpPreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ClvpDecoderLayer`] """ def __init__(self, config): super().__init__(config) self.config = config self.input_embeds_layer = nn.Embedding(self.config.vocab_size, self.config.hidden_size) self.position_embeds_layer = nn.Embedding(self.config.max_position_embeddings, self.config.hidden_size) self.drop = nn.Dropout(self.config.embd_pdrop) self.layers = nn.ModuleList( [ClvpDecoderLayer(self.config, layer_idx=i) for i in range(self.config.num_hidden_layers)] ) self.layer_norm = nn.LayerNorm(self.config.hidden_size, eps=self.config.layer_norm_epsilon) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.input_embeds_layer def set_input_embeddings(self, new_embeddings): self.input_embeds_layer = new_embeddings @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.Tensor] = None, ) -> Union[tuple, BaseModelOutputWithPastAndCrossAttentions]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask) input_shape = input_ids.size() input_ids = input_ids.view(-1, input_shape[-1]) input_ids.shape[0] elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] inputs_embeds.shape[0] else: raise ValueError("You have to specify either input_ids or inputs_embeds") device = input_ids.device if input_ids is not None else inputs_embeds.device if token_type_ids is not None: token_type_ids = token_type_ids.view(-1, input_shape[-1]) if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config) past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0 if position_ids is None: position_ids = torch.arange( past_key_values_length, input_shape[-1] + past_key_values_length, dtype=torch.long, device=device ) position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1]) if inputs_embeds is None: inputs_embeds = self.input_embeds_layer(input_ids) position_embeds = self.position_embeds_layer(position_ids) inputs_embeds = inputs_embeds + position_embeds attention_mask = _prepare_4d_causal_attention_mask( attention_mask, input_shape, inputs_embeds, past_key_values_length ) hidden_states = inputs_embeds if token_type_ids is not None: token_type_embeds = self.input_embeds_layer(token_type_ids) hidden_states = hidden_states + token_type_embeds hidden_states = self.drop(hidden_states) output_shape = (-1,) + input_shape[1:] + (hidden_states.size(-1),) all_self_attentions = () if output_attentions else None all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None all_hidden_states = () if output_hidden_states else None for i, block in enumerate(self.layers): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if self.gradient_checkpointing and self.training: outputs = torch.utils.checkpoint.checkpoint( block.__call__, hidden_states, None, attention_mask, position_ids, cache_position, ) else: outputs = block( hidden_states, past_key_values=past_key_values, attention_mask=attention_mask, position_ids=position_ids, use_cache=use_cache, output_attentions=output_attentions, cache_position=cache_position, ) hidden_states = outputs[0] if output_attentions: all_self_attentions = all_self_attentions + (outputs[1],) if self.config.add_cross_attention: all_cross_attentions = all_cross_attentions + (outputs[2],) hidden_states = self.layer_norm(hidden_states) hidden_states = hidden_states.view(output_shape) # Add last hidden state if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple( v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attentions, all_cross_attentions] if v is not None ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attentions, cross_attentions=all_cross_attentions, ) @auto_docstring
ClvpDecoder
python
python-openxml__python-docx
src/docx/oxml/shape.py
{ "start": 1327, "end": 1570 }
class ____(BaseOxmlElement): """``<a:graphic>`` element, container for a DrawingML object.""" graphicData: CT_GraphicalObjectData = OneAndOnlyOne( # pyright: ignore[reportAssignmentType] "a:graphicData" )
CT_GraphicalObject
python
huggingface__transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
{ "start": 20140, "end": 22739 }
class ____(GradientCheckpointingLayer): """Conformer block based on https://huggingface.co/papers/2005.08100.""" # Copied from transformers.models.wav2vec2_conformer.modeling_wav2vec2_conformer.Wav2Vec2ConformerEncoderLayer.__init__ with Wav2Vec2->SeamlessM4Tv2, attention_dropout->speech_encoder_dropout, torch.nn->nn def __init__(self, config): super().__init__() embed_dim = config.hidden_size dropout = config.speech_encoder_dropout # Feed-forward 1 self.ffn1_layer_norm = nn.LayerNorm(embed_dim) self.ffn1 = SeamlessM4Tv2ConformerFeedForward(config) # Self-Attention self.self_attn_layer_norm = nn.LayerNorm(embed_dim) self.self_attn_dropout = nn.Dropout(dropout) self.self_attn = SeamlessM4Tv2ConformerSelfAttention(config) # Conformer Convolution self.conv_module = SeamlessM4Tv2ConformerConvolutionModule(config) # Feed-forward 2 self.ffn2_layer_norm = nn.LayerNorm(embed_dim) self.ffn2 = SeamlessM4Tv2ConformerFeedForward(config) self.final_layer_norm = nn.LayerNorm(embed_dim) def forward( self, hidden_states, attention_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, conv_attention_mask: Optional[torch.Tensor] = None, ): # 1. Feed-Forward 1 layer residual = hidden_states hidden_states = self.ffn1_layer_norm(hidden_states) hidden_states = self.ffn1(hidden_states) hidden_states = hidden_states * 0.5 + residual residual = hidden_states # 2. Self-Attention layer hidden_states = self.self_attn_layer_norm(hidden_states) hidden_states, attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, output_attentions=output_attentions, ) hidden_states = self.self_attn_dropout(hidden_states) hidden_states = hidden_states + residual # 3. Convolutional Layer residual = hidden_states hidden_states = self.conv_module(hidden_states, attention_mask=conv_attention_mask) hidden_states = residual + hidden_states # 4. Feed-Forward 2 Layer residual = hidden_states hidden_states = self.ffn2_layer_norm(hidden_states) hidden_states = self.ffn2(hidden_states) hidden_states = hidden_states * 0.5 + residual hidden_states = self.final_layer_norm(hidden_states) return hidden_states, attn_weights
SeamlessM4Tv2ConformerEncoderLayer
python
django__django
django/db/backends/mysql/operations.py
{ "start": 420, "end": 17396 }
class ____(BaseDatabaseOperations): compiler_module = "django.db.backends.mysql.compiler" # MySQL stores positive fields as UNSIGNED ints. integer_field_ranges = { **BaseDatabaseOperations.integer_field_ranges, "PositiveSmallIntegerField": (0, 65535), "PositiveIntegerField": (0, 4294967295), "PositiveBigIntegerField": (0, 18446744073709551615), } cast_data_types = { "AutoField": "signed integer", "BigAutoField": "signed integer", "SmallAutoField": "signed integer", "CharField": "char(%(max_length)s)", "DecimalField": "decimal(%(max_digits)s, %(decimal_places)s)", "TextField": "char", "IntegerField": "signed integer", "BigIntegerField": "signed integer", "SmallIntegerField": "signed integer", "PositiveBigIntegerField": "unsigned integer", "PositiveIntegerField": "unsigned integer", "PositiveSmallIntegerField": "unsigned integer", "DurationField": "signed integer", } cast_char_field_without_max_length = "char" explain_prefix = "EXPLAIN" # EXTRACT format cannot be passed in parameters. _extract_format_re = _lazy_re_compile(r"[A-Z_]+") def date_extract_sql(self, lookup_type, sql, params): # https://dev.mysql.com/doc/mysql/en/date-and-time-functions.html if lookup_type == "week_day": # DAYOFWEEK() returns an integer, 1-7, Sunday=1. return f"DAYOFWEEK({sql})", params elif lookup_type == "iso_week_day": # WEEKDAY() returns an integer, 0-6, Monday=0. return f"WEEKDAY({sql}) + 1", params elif lookup_type == "week": # Override the value of default_week_format for consistency with # other database backends. # Mode 3: Monday, 1-53, with 4 or more days this year. return f"WEEK({sql}, 3)", params elif lookup_type == "iso_year": # Get the year part from the YEARWEEK function, which returns a # number as year * 100 + week. return f"TRUNCATE(YEARWEEK({sql}, 3), -2) / 100", params else: # EXTRACT returns 1-53 based on ISO-8601 for the week number. lookup_type = lookup_type.upper() if not self._extract_format_re.fullmatch(lookup_type): raise ValueError(f"Invalid loookup type: {lookup_type!r}") return f"EXTRACT({lookup_type} FROM {sql})", params def date_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) fields = { "year": "%Y-01-01", "month": "%Y-%m-01", } if lookup_type in fields: format_str = fields[lookup_type] return f"CAST(DATE_FORMAT({sql}, %s) AS DATE)", (*params, format_str) elif lookup_type == "quarter": return ( f"MAKEDATE(YEAR({sql}), 1) + " f"INTERVAL QUARTER({sql}) QUARTER - INTERVAL 1 QUARTER", (*params, *params), ) elif lookup_type == "week": return f"DATE_SUB({sql}, INTERVAL WEEKDAY({sql}) DAY)", (*params, *params) else: return f"DATE({sql})", params def _prepare_tzname_delta(self, tzname): tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_sql_to_tz(self, sql, params, tzname): if tzname and settings.USE_TZ and self.connection.timezone_name != tzname: return f"CONVERT_TZ({sql}, %s, %s)", ( *params, self.connection.timezone_name, self._prepare_tzname_delta(tzname), ) return sql, params def datetime_cast_date_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"DATE({sql})", params def datetime_cast_time_sql(self, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return f"TIME({sql})", params def datetime_extract_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) return self.date_extract_sql(lookup_type, sql, params) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): sql, params = self._convert_sql_to_tz(sql, params, tzname) fields = ["year", "month", "day", "hour", "minute", "second"] format = ("%Y-", "%m", "-%d", " %H:", "%i", ":%s") format_def = ("0000-", "01", "-01", " 00:", "00", ":00") if lookup_type == "quarter": return ( f"CAST(DATE_FORMAT(MAKEDATE(YEAR({sql}), 1) + " f"INTERVAL QUARTER({sql}) QUARTER - " f"INTERVAL 1 QUARTER, %s) AS DATETIME)" ), (*params, *params, "%Y-%m-01 00:00:00") if lookup_type == "week": return ( f"CAST(DATE_FORMAT(" f"DATE_SUB({sql}, INTERVAL WEEKDAY({sql}) DAY), %s) AS DATETIME)" ), (*params, *params, "%Y-%m-%d 00:00:00") try: i = fields.index(lookup_type) + 1 except ValueError: pass else: format_str = "".join(format[:i] + format_def[i:]) return f"CAST(DATE_FORMAT({sql}, %s) AS DATETIME)", (*params, format_str) return sql, params def time_trunc_sql(self, lookup_type, sql, params, tzname=None): sql, params = self._convert_sql_to_tz(sql, params, tzname) fields = { "hour": "%H:00:00", "minute": "%H:%i:00", "second": "%H:%i:%s", } if lookup_type in fields: format_str = fields[lookup_type] return f"CAST(DATE_FORMAT({sql}, %s) AS TIME)", (*params, format_str) else: return f"TIME({sql})", params def format_for_duration_arithmetic(self, sql): return "INTERVAL %s MICROSECOND" % sql def force_no_ordering(self): """ "ORDER BY NULL" prevents MySQL from implicitly ordering by grouped columns. If no ordering would otherwise be applied, we don't want any implicit sorting going on. """ return [(None, ("NULL", [], False))] def last_executed_query(self, cursor, sql, params): # With MySQLdb, cursor objects have an (undocumented) "_executed" # attribute where the exact query sent to the database is saved. # See MySQLdb/cursors.py in the source distribution. # MySQLdb returns string, PyMySQL bytes. return force_str(getattr(cursor, "_executed", None), errors="replace") def no_limit_value(self): # 2**64 - 1, as recommended by the MySQL documentation return 18446744073709551615 def quote_name(self, name): if name.startswith("`") and name.endswith("`"): return name # Quoting once is enough. return "`%s`" % name def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): if not tables: return [] sql = ["SET FOREIGN_KEY_CHECKS = 0;"] if reset_sequences: # It's faster to TRUNCATE tables that require a sequence reset # since ALTER TABLE AUTO_INCREMENT is slower than TRUNCATE. sql.extend( "%s %s;" % ( style.SQL_KEYWORD("TRUNCATE"), style.SQL_FIELD(self.quote_name(table_name)), ) for table_name in tables ) else: # Otherwise issue a simple DELETE since it's faster than TRUNCATE # and preserves sequences. sql.extend( "%s %s %s;" % ( style.SQL_KEYWORD("DELETE"), style.SQL_KEYWORD("FROM"), style.SQL_FIELD(self.quote_name(table_name)), ) for table_name in tables ) sql.append("SET FOREIGN_KEY_CHECKS = 1;") return sql def sequence_reset_by_name_sql(self, style, sequences): return [ "%s %s %s %s = 1;" % ( style.SQL_KEYWORD("ALTER"), style.SQL_KEYWORD("TABLE"), style.SQL_FIELD(self.quote_name(sequence_info["table"])), style.SQL_FIELD("AUTO_INCREMENT"), ) for sequence_info in sequences ] def validate_autopk_value(self, value): # Zero in AUTO_INCREMENT field does not work without the # NO_AUTO_VALUE_ON_ZERO SQL mode. if value == 0 and not self.connection.features.allows_auto_pk_0: raise ValueError( "The database backend does not accept 0 as a value for AutoField." ) return value def adapt_datetimefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # MySQL doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError( "MySQL backend does not support timezone-aware datetimes when " "USE_TZ is False." ) return str(value) def adapt_timefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # MySQL doesn't support tz-aware times if timezone.is_aware(value): raise ValueError("MySQL backend does not support timezone-aware times.") return value.isoformat(timespec="microseconds") def max_name_length(self): return 64 def pk_default_value(self): return "NULL" def combine_expression(self, connector, sub_expressions): if connector == "^": return "POW(%s)" % ",".join(sub_expressions) # Convert the result to a signed integer since MySQL's binary operators # return an unsigned integer. elif connector in ("&", "|", "<<", "#"): connector = "^" if connector == "#" else connector return "CONVERT(%s, SIGNED)" % connector.join(sub_expressions) elif connector == ">>": lhs, rhs = sub_expressions return "FLOOR(%(lhs)s / POW(2, %(rhs)s))" % {"lhs": lhs, "rhs": rhs} return super().combine_expression(connector, sub_expressions) def get_db_converters(self, expression): converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() if internal_type == "BooleanField": converters.append(self.convert_booleanfield_value) elif internal_type == "DateTimeField": if settings.USE_TZ: converters.append(self.convert_datetimefield_value) elif internal_type == "UUIDField": converters.append(self.convert_uuidfield_value) return converters def convert_booleanfield_value(self, value, expression, connection): if value in (0, 1): value = bool(value) return value def convert_datetimefield_value(self, value, expression, connection): if value is not None: value = timezone.make_aware(value, self.connection.timezone) return value def convert_uuidfield_value(self, value, expression, connection): if value is not None: value = uuid.UUID(value) return value def binary_placeholder_sql(self, value): return ( "_binary %s" if value is not None and not hasattr(value, "as_sql") else "%s" ) def subtract_temporals(self, internal_type, lhs, rhs): lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs if internal_type == "TimeField": if self.connection.mysql_is_mariadb: # MariaDB includes the microsecond component in TIME_TO_SEC as # a decimal. MySQL returns an integer without microseconds. return ( "CAST((TIME_TO_SEC(%(lhs)s) - TIME_TO_SEC(%(rhs)s)) " "* 1000000 AS SIGNED)" ) % { "lhs": lhs_sql, "rhs": rhs_sql, }, ( *lhs_params, *rhs_params, ) return ( "((TIME_TO_SEC(%(lhs)s) * 1000000 + MICROSECOND(%(lhs)s)) -" " (TIME_TO_SEC(%(rhs)s) * 1000000 + MICROSECOND(%(rhs)s)))" ) % {"lhs": lhs_sql, "rhs": rhs_sql}, tuple(lhs_params) * 2 + tuple( rhs_params ) * 2 params = (*rhs_params, *lhs_params) return "TIMESTAMPDIFF(MICROSECOND, %s, %s)" % (rhs_sql, lhs_sql), params def explain_query_prefix(self, format=None, **options): # Alias MySQL's TRADITIONAL to TEXT for consistency with other # backends. if format and format.upper() == "TEXT": format = "TRADITIONAL" elif ( not format and "TREE" in self.connection.features.supported_explain_formats ): # Use TREE by default (if supported) as it's more informative. format = "TREE" analyze = options.pop("analyze", False) prefix = super().explain_query_prefix(format, **options) if analyze: # MariaDB uses ANALYZE instead of EXPLAIN ANALYZE. prefix = ( "ANALYZE" if self.connection.mysql_is_mariadb else prefix + " ANALYZE" ) if format and not (analyze and not self.connection.mysql_is_mariadb): # Only MariaDB supports the analyze option with formats. prefix += " FORMAT=%s" % format return prefix def regex_lookup(self, lookup_type): # REGEXP_LIKE doesn't exist in MariaDB. if self.connection.mysql_is_mariadb: if lookup_type == "regex": return "%s REGEXP BINARY %s" return "%s REGEXP %s" match_option = "c" if lookup_type == "regex" else "i" return "REGEXP_LIKE(%%s, %%s, '%s')" % match_option def insert_statement(self, on_conflict=None): if on_conflict == OnConflict.IGNORE: return "INSERT IGNORE INTO" return super().insert_statement(on_conflict=on_conflict) def lookup_cast(self, lookup_type, internal_type=None): lookup = "%s" if internal_type == "JSONField": if self.connection.mysql_is_mariadb or lookup_type in ( "iexact", "contains", "icontains", "startswith", "istartswith", "endswith", "iendswith", "regex", "iregex", ): lookup = "JSON_UNQUOTE(%s)" return lookup def conditional_expression_supported_in_where_clause(self, expression): # MySQL ignores indexes with boolean fields unless they're compared # directly to a boolean value. if isinstance(expression, (Exists, Lookup)): return True if isinstance(expression, ExpressionWrapper) and expression.conditional: return self.conditional_expression_supported_in_where_clause( expression.expression ) if getattr(expression, "conditional", False): return False return super().conditional_expression_supported_in_where_clause(expression) def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields): if on_conflict == OnConflict.UPDATE: conflict_suffix_sql = "ON DUPLICATE KEY UPDATE %(fields)s" # The use of VALUES() is not supported in MySQL. Instead, use # aliases for the new row and its columns. if not self.connection.mysql_is_mariadb: conflict_suffix_sql = f"AS new {conflict_suffix_sql}" field_sql = "%(field)s = new.%(field)s" # Use VALUE() on MariaDB. else: field_sql = "%(field)s = VALUE(%(field)s)" fields = ", ".join( [ field_sql % {"field": field} for field in map(self.quote_name, update_fields) ] ) return conflict_suffix_sql % {"fields": fields} return super().on_conflict_suffix_sql( fields, on_conflict, update_fields, unique_fields, )
DatabaseOperations
python
gevent__gevent
src/gevent/tests/test__pywsgi.py
{ "start": 6582, "end": 11643 }
class ____(greentest.TestCase): server = None validator = staticmethod(validator) application = None # Bind to default address, which should give us ipv6 (when available) # and ipv4. (see self.connect()) listen_addr = greentest.DEFAULT_BIND_ADDR # connect on ipv4, even though we bound to ipv6 too # to prove ipv4 works...except on Windows, it apparently doesn't. # So use the hostname. connect_addr = greentest.DEFAULT_LOCAL_HOST_ADDR class handler_class(pywsgi.WSGIHandler): ApplicationError = ExpectedAssertionError def init_logger(self): import logging logger = logging.getLogger('gevent.tests.pywsgi') logger.setLevel(logging.CRITICAL) return logger def init_server(self, application): logger = self.logger = self.init_logger() self.server = pywsgi.WSGIServer( (self.listen_addr, 0), application, log=logger, error_log=logger, handler_class=self.handler_class, ) def setUp(self): application = self.application if self.validator is not None: application = self.validator(application) self.init_server(application) self.server.start() while not self.server.server_port: print("Waiting on server port") self.port = self.server.server_port assert self.port greentest.TestCase.setUp(self) if greentest.CPYTHON and greentest.PY2: # Keeping raw sockets alive keeps SSL sockets # from being closed too, at least on CPython2, so we # need to use weakrefs. # In contrast, on PyPy, *only* having a weakref lets the # original socket die and leak def _close_on_teardown(self, resource): self.close_on_teardown.append(weakref.ref(resource)) return resource def _tearDownCloseOnTearDown(self): self.close_on_teardown = [r() for r in self.close_on_teardown if r() is not None] super(TestCase, self)._tearDownCloseOnTearDown() def tearDown(self): greentest.TestCase.tearDown(self) if self.server is not None: with gevent.Timeout.start_new(0.5): self.server.stop() self.server = None if greentest.PYPY: import gc gc.collect() gc.collect() @contextmanager def connect(self): conn = socket.create_connection((self.connect_addr, self.port)) result = conn if PY3: conn_makefile = conn.makefile def makefile(*args, **kwargs): if 'bufsize' in kwargs: kwargs['buffering'] = kwargs.pop('bufsize') if 'mode' in kwargs: return conn_makefile(*args, **kwargs) # Under Python3, you can't read and write to the same # makefile() opened in (default) r, and r+ is not allowed kwargs['mode'] = 'rwb' rconn = conn_makefile(*args, **kwargs) _rconn_write = rconn.write def write(data): if isinstance(data, str): data = data.encode('ascii') return _rconn_write(data) rconn.write = write self._close_on_teardown(rconn) return rconn class proxy(object): def __getattribute__(self, name): if name == 'makefile': return makefile return getattr(conn, name) result = proxy() try: yield result finally: result.close() @contextmanager def makefile(self): with self.connect() as sock: try: result = sock.makefile(bufsize=1) # pylint:disable=unexpected-keyword-arg yield result finally: result.close() def urlopen(self, *args, **kwargs): with self.connect() as sock: with sock.makefile(bufsize=1) as fd: # pylint:disable=unexpected-keyword-arg fd.write('GET / HTTP/1.1\r\nHost: localhost\r\n\r\n') return read_http(fd, *args, **kwargs) HTTP_CLIENT_VERSION = '1.1' DEFAULT_EXTRA_CLIENT_HEADERS = {} def format_request(self, method='GET', path='/', **headers): def_headers = self.DEFAULT_EXTRA_CLIENT_HEADERS.copy() def_headers.update(headers) headers = def_headers headers = '\r\n'.join('%s: %s' % item for item in headers.items()) headers = headers + '\r\n' if headers else headers result = ( '%(method)s %(path)s HTTP/%(http_ver)s\r\n' 'Host: localhost\r\n' '%(headers)s' '\r\n' ) result = result % dict( method=method, path=path, http_ver=self.HTTP_CLIENT_VERSION, headers=headers ) return result
TestCase
python
vyperlang__vyper
vyper/venom/basicblock.py
{ "start": 3979, "end": 5447 }
class ____(IROperand): """ operand representing an offset into an alloca'ed memory segment which has not be concretized (allocated) yet. """ _id: int # size of the memory segment size: int # offset inside of a memory segment offset: int _curr_id: ClassVar[int] = 0 FREE_VAR1: ClassVar[IRAbstractMemLoc] FREE_VAR2: ClassVar[IRAbstractMemLoc] def __init__(self, size: int, offset: int = 0, force_id=None): if force_id is None: self._id = IRAbstractMemLoc._curr_id IRAbstractMemLoc._curr_id += 1 else: self._id = force_id super().__init__(self._id) self.size = size self.offset = offset def __hash__(self) -> int: return self._id def __eq__(self, other) -> bool: if type(self) is not type(other): return False return self._id == other._id and self.offset == other.offset def __repr__(self) -> str: return f"[{self._id},{self.size} + {self.offset}]" def without_offset(self) -> IRAbstractMemLoc: return IRAbstractMemLoc(self.size, force_id=self._id) def with_offset(self, offset: int) -> IRAbstractMemLoc: return IRAbstractMemLoc(self.size, offset=offset, force_id=self._id) # cannot assign in class since it is not defined in that place IRAbstractMemLoc.FREE_VAR1 = IRAbstractMemLoc(32) IRAbstractMemLoc.FREE_VAR2 = IRAbstractMemLoc(32)
IRAbstractMemLoc
python
kamyu104__LeetCode-Solutions
Python/count-prefix-and-suffix-pairs-i.py
{ "start": 61, "end": 631 }
class ____(object): def countPrefixSuffixPairs(self, words): """ :type words: List[str] :rtype: int """ _trie = lambda: collections.defaultdict(_trie) trie = _trie() result = 0 for w in words: curr = trie for i in xrange(len(w)): curr = curr[w[i], w[~i]] result += curr["_cnt"] if "_cnt" in curr else 0 curr["_cnt"] = curr["_cnt"]+1 if "_cnt" in curr else 1 return result # Time: O(n^2 * l) # Space: O(1) # brute force
Solution
python
pexpect__pexpect
tests/test_pickling.py
{ "start": 91, "end": 338 }
class ____(unittest.TestCase): def test_picking(self): e = ExceptionPexpect('Oh noes!') clone = pickle.loads(pickle.dumps(e)) self.assertEqual(e.value, clone.value) if __name__ == '__main__': unittest.main()
PickleTest
python
scrapy__scrapy
tests/mockserver/http_resources.py
{ "start": 7881, "end": 8190 }
class ____(resource.Resource): """ A testing resource which renders itself as the value of request body without content-type header in response. """ def render(self, request): request.setHeader("content-type", "") return request.content.read()
EmptyContentTypeHeaderResource
python
ray-project__ray
python/ray/autoscaler/v2/tests/util.py
{ "start": 4101, "end": 4516 }
class ____(Check): def __init__(self, count: int): self.count = count def check(self, status: ClusterStatus): healthy_nodes = len(status.active_nodes) + len(status.idle_nodes) if healthy_nodes != self.count: raise CheckFailure(f"Expected {self.count} nodes, got {healthy_nodes}") def __str__(self) -> str: return f"NodeCountCheck: {self.count}"
NodeCountCheck
python
mlflow__mlflow
mlflow/pyfunc/loaders/chat_agent.py
{ "start": 671, "end": 4436 }
class ____: """ Wrapper class that converts dict inputs to pydantic objects accepted by :class:`~ChatAgent`. """ def __init__(self, chat_agent): """ Args: chat_agent: An instance of a subclass of :class:`~ChatAgent`. """ self.chat_agent = chat_agent def get_raw_model(self): """ Returns the underlying model. """ return self.chat_agent def _convert_input( self, model_input ) -> tuple[list[ChatAgentMessage], ChatContext | None, dict[str, Any] | None]: import pandas if isinstance(model_input, dict): dict_input = model_input elif isinstance(model_input, pandas.DataFrame): dict_input = { k: _convert_llm_ndarray_to_list(v[0]) for k, v in model_input.to_dict(orient="list").items() } else: raise MlflowException( "Unsupported model input type. Expected a dict or pandas.DataFrame, but got " f"{type(model_input)} instead.", error_code=INTERNAL_ERROR, ) messages = [ChatAgentMessage(**message) for message in dict_input.get("messages", [])] context = ChatContext(**dict_input["context"]) if "context" in dict_input else None custom_inputs = dict_input.get("custom_inputs") return messages, context, custom_inputs def _response_to_dict(self, response, pydantic_class) -> dict[str, Any]: if isinstance(response, pydantic_class): return response.model_dump(exclude_none=True) try: model_validate(pydantic_class, response) except pydantic.ValidationError as e: raise MlflowException( message=( f"Model returned an invalid response. Expected a {pydantic_class.__name__} " f"object or dictionary with the same schema. Pydantic validation error: {e}" ), error_code=INTERNAL_ERROR, ) from e return response def predict(self, model_input: dict[str, Any], params=None) -> dict[str, Any]: """ Args: model_input: A dict with the :py:class:`ChatAgentRequest <mlflow.types.agent.ChatAgentRequest>` schema. params: Unused in this function, but required in the signature because `load_model_and_predict` in `utils/_capture_modules.py` expects a params field Returns: A dict with the (:py:class:`ChatAgentResponse <mlflow.types.agent.ChatAgentResponse>`) schema. """ messages, context, custom_inputs = self._convert_input(model_input) response = self.chat_agent.predict(messages, context, custom_inputs) return self._response_to_dict(response, ChatAgentResponse) def predict_stream( self, model_input: dict[str, Any], params=None ) -> Generator[dict[str, Any], None, None]: """ Args: model_input: A dict with the :py:class:`ChatAgentRequest <mlflow.types.agent.ChatAgentRequest>` schema. params: Unused in this function, but required in the signature because `load_model_and_predict` in `utils/_capture_modules.py` expects a params field Returns: A generator over dicts with the (:py:class:`ChatAgentChunk <mlflow.types.agent.ChatAgentChunk>`) schema. """ messages, context, custom_inputs = self._convert_input(model_input) for response in self.chat_agent.predict_stream(messages, context, custom_inputs): yield self._response_to_dict(response, ChatAgentChunk)
_ChatAgentPyfuncWrapper
python
matplotlib__matplotlib
lib/matplotlib/testing/compare.py
{ "start": 4558, "end": 8399 }
class ____(_Converter): def __call__(self, orig, dest): old_inkscape = mpl._get_executable_info("inkscape").version.major < 1 terminator = b"\n>" if old_inkscape else b"> " if not hasattr(self, "_tmpdir"): self._tmpdir = TemporaryDirectory() # On Windows, we must make sure that self._proc has terminated # (which __del__ does) before clearing _tmpdir. weakref.finalize(self._tmpdir, self.__del__) if (not self._proc # First run. or self._proc.poll() is not None): # Inkscape terminated. if self._proc is not None and self._proc.poll() is not None: for stream in filter(None, [self._proc.stdin, self._proc.stdout, self._proc.stderr]): stream.close() env = { **os.environ, # If one passes e.g. a png file to Inkscape, it will try to # query the user for conversion options via a GUI (even with # `--without-gui`). Unsetting `DISPLAY` prevents this (and # causes GTK to crash and Inkscape to terminate, but that'll # just be reported as a regular exception below). "DISPLAY": "", # Do not load any user options. "INKSCAPE_PROFILE_DIR": self._tmpdir.name, } # Old versions of Inkscape (e.g. 0.48.3.1) seem to sometimes # deadlock when stderr is redirected to a pipe, so we redirect it # to a temporary file instead. This is not necessary anymore as of # Inkscape 0.92.1. stderr = TemporaryFile() self._proc = subprocess.Popen( ["inkscape", "--without-gui", "--shell"] if old_inkscape else ["inkscape", "--shell"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, env=env, cwd=self._tmpdir.name) # Slight abuse, but makes shutdown handling easier. self._proc.stderr = stderr try: self._read_until(terminator) except _ConverterError as err: raise OSError( "Failed to start Inkscape in interactive mode:\n\n" + err.args[0]) from err # Inkscape's shell mode does not support escaping metacharacters in the # filename ("\n", and ":;" for inkscape>=1). Avoid any problems by # running from a temporary directory and using fixed filenames. inkscape_orig = Path(self._tmpdir.name, os.fsdecode(b"f.svg")) inkscape_dest = Path(self._tmpdir.name, os.fsdecode(b"f.png")) try: inkscape_orig.symlink_to(Path(orig).resolve()) except OSError: shutil.copyfile(orig, inkscape_orig) self._proc.stdin.write( b"f.svg --export-png=f.png\n" if old_inkscape else b"file-open:f.svg;export-filename:f.png;export-do;file-close\n") self._proc.stdin.flush() try: self._read_until(terminator) except _ConverterError as err: # Inkscape's output is not localized but gtk's is, so the output # stream probably has a mixed encoding. Using the filesystem # encoding should at least get the filenames right... self._proc.stderr.seek(0) raise ImageComparisonFailure( self._proc.stderr.read().decode( sys.getfilesystemencoding(), "replace")) from err os.remove(inkscape_orig) shutil.move(inkscape_dest, dest) def __del__(self): super().__del__() if hasattr(self, "_tmpdir"): self._tmpdir.cleanup()
_SVGConverter
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/triggers/cloud_composer.py
{ "start": 1332, "end": 3392 }
class ____(BaseTrigger): """The trigger handles the async communication with the Google Cloud Composer.""" def __init__( self, project_id: str, region: str, operation_name: str, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, pooling_period_seconds: int = 30, ): super().__init__() self.project_id = project_id self.region = region self.operation_name = operation_name self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain self.pooling_period_seconds = pooling_period_seconds def serialize(self) -> tuple[str, dict[str, Any]]: return ( "airflow.providers.google.cloud.triggers.cloud_composer.CloudComposerExecutionTrigger", { "project_id": self.project_id, "region": self.region, "operation_name": self.operation_name, "gcp_conn_id": self.gcp_conn_id, "impersonation_chain": self.impersonation_chain, "pooling_period_seconds": self.pooling_period_seconds, }, ) def _get_async_hook(self) -> CloudComposerAsyncHook: return CloudComposerAsyncHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) async def run(self): self.gcp_hook = self._get_async_hook() while True: operation = await self.gcp_hook.get_operation(operation_name=self.operation_name) if operation.done: break elif operation.error.message: raise AirflowException(f"Cloud Composer Environment error: {operation.error.message}") await asyncio.sleep(self.pooling_period_seconds) yield TriggerEvent( { "operation_name": operation.name, "operation_done": operation.done, } )
CloudComposerExecutionTrigger
python
sqlalchemy__sqlalchemy
examples/sharding/asyncio.py
{ "start": 1876, "end": 3190 }
class ____(DeclarativeBase): pass # we need a way to create identifiers which are unique across all databases. # one easy way would be to just use a composite primary key, where one value # is the shard id. but here, we'll show something more "generic", an id # generation function. we'll use a simplistic "id table" stored in database # #1. Any other method will do just as well; UUID, hilo, application-specific, # etc. ids = Table("ids", Base.metadata, Column("nextid", Integer, nullable=False)) def id_generator(ctx): # id_generator is run within a "synchronous" context, where # we use an implicit-await API that will convert back to explicit await # calls when it reaches the driver. with db1.sync_engine.begin() as conn: nextid = conn.scalar(ids.select().with_for_update()) conn.execute(ids.update().values({ids.c.nextid: ids.c.nextid + 1})) return nextid # table setup. we'll store a lead table of continents/cities, and a secondary # table storing locations. a particular row will be placed in the database # whose shard id corresponds to the 'continent'. in this setup, secondary rows # in 'weather_reports' will be placed in the same DB as that of the parent, but # this can be changed if you're willing to write more complex sharding # functions.
Base
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/check_ops_test.py
{ "start": 24380, "end": 27355 }
class ____(test.TestCase): @test_util.run_in_graph_and_eager_modes def test_doesnt_raise_when_equal(self): small = constant_op.constant([1, 2], name="small") with ops.control_dependencies( [check_ops.assert_less_equal(small, small)]): out = array_ops.identity(small) self.evaluate(out) @test_util.run_in_graph_and_eager_modes @test_util.run_deprecated_v1 def test_raises_when_greater(self): small = constant_op.constant([1, 2], name="small") big = constant_op.constant([3, 4], name="big") with self.assertRaisesOpError( # pylint:disable=g-error-prone-assert-raises "fail"): with ops.control_dependencies( [check_ops.assert_less_equal( big, small, message="fail")]): out = array_ops.identity(small) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_doesnt_raise_when_less_equal(self): small = constant_op.constant([1, 2], name="small") big = constant_op.constant([3, 2], name="big") with ops.control_dependencies([check_ops.assert_less_equal(small, big)]): out = array_ops.identity(small) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_doesnt_raise_when_less_equal_and_broadcastable_shapes(self): small = constant_op.constant([1], name="small") big = constant_op.constant([3, 1], name="big") with ops.control_dependencies([check_ops.assert_less_equal(small, big)]): out = array_ops.identity(small) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_raises_when_less_equal_but_non_broadcastable_shapes(self): small = constant_op.constant([3, 1], name="small") big = constant_op.constant([1, 1, 1], name="big") # The exception in eager and non-eager mode is different because # eager mode relies on shape check done as part of the C++ op, while # graph mode does shape checks when creating the `Operation` instance. with self.assertRaisesRegex( # pylint:disable=g-error-prone-assert-raises (errors.InvalidArgumentError, ValueError), (r"Incompatible shapes: \[2\] vs. \[3\]|" r"Dimensions must be equal, but are 2 and 3")): with ops.control_dependencies( [check_ops.assert_less_equal(small, big)]): out = array_ops.identity(small) self.evaluate(out) @test_util.run_in_graph_and_eager_modes def test_doesnt_raise_when_both_empty(self): larry = constant_op.constant([]) curly = constant_op.constant([]) with ops.control_dependencies( [check_ops.assert_less_equal(larry, curly)]): out = array_ops.identity(larry) self.evaluate(out) def test_static_check_in_graph_mode(self): with ops.Graph().as_default(): with self.assertRaisesRegex( # pylint:disable=g-error-prone-assert-raises errors.InvalidArgumentError, "Custom error message"): check_ops.assert_less_equal(1, 0, message="Custom error message")
AssertLessEqualTest
python
has2k1__plotnine
plotnine/themes/theme_matplotlib.py
{ "start": 188, "end": 4248 }
class ____(theme): """ The default matplotlib look and feel. The theme can be used (and has the same parameter to customize) like a [](`matplotlib.rc_context`) manager. Parameters ---------- rc : dict rcParams which should be applied on top of mathplotlib default. fname : str Filename to a matplotlibrc file use_defaults : bool If `True` (the default) resets the plot setting to the (current) `matplotlib.rcParams` values """ def __init__(self, rc=None, fname=None, use_defaults=True): import matplotlib as mpl m = get_option("base_margin") base_size = mpl.rcParams.get("font.size", 11) linewidth = mpl.rcParams.get("grid.linewidth", 0.8) half_line = base_size / 2 super().__init__( line=element_line(size=linewidth), rect=element_rect(size=linewidth), text=element_text( size=base_size, linespacing=1, rotation=0, margin={}, ), aspect_ratio=get_option("aspect_ratio"), axis_text=element_text(margin=margin(t=2.4, r=2.4, unit="pt")), axis_title_x=element_text( va="bottom", ha="center", margin=margin(t=m, unit="fig") ), axis_line=element_blank(), axis_title_y=element_text( angle=90, va="center", ha="left", margin=margin(r=m, unit="fig"), ), dpi=get_option("dpi"), figure_size=get_option("figure_size"), legend_background=element_rect(color="none"), legend_box_margin=0, legend_box_spacing=m * 3, legend_key_spacing_x=6, legend_key_spacing_y=2, legend_frame=element_rect(color="black"), legend_key_size=16, legend_ticks_length=0.2, legend_margin=0, legend_position="right", legend_spacing=10, legend_text=element_text(margin=margin_auto(m / 2, unit="fig")), legend_ticks=element_line(color="black"), legend_title=element_text( ha="left", margin=margin(t=m, l=m * 2, b=m / 2, r=m * 2, unit="fig"), ), panel_border=element_rect(color="black"), panel_grid=element_blank(), panel_spacing=m, plot_caption=element_text( ha="right", va="bottom", ma="left", margin=margin(t=m, unit="fig"), ), plot_margin=m, plot_subtitle=element_text( size=base_size * 0.9, va="top", ma="left", margin=margin(b=m, unit="fig"), ), plot_title=element_text( va="top", ma="left", margin=margin(b=m, unit="fig"), ), plot_tag=element_text( size=base_size * 1.2, va="center", ha="center", ), plot_title_position="panel", plot_caption_position="panel", plot_tag_location="margin", plot_tag_position="topleft", strip_align=0, strip_background=element_rect( fill="#D9D9D9", color="black", size=linewidth ), strip_text=element_text( linespacing=1.5, margin=margin_auto(half_line * 0.8), ), strip_text_y=element_text(rotation=-90), complete=True, ) if use_defaults: _copy = mpl.rcParams.copy() if "tk.pythoninspect" in _copy: del _copy["tk.pythoninspect"] self._rcParams.update(_copy) if fname: self._rcParams.update(mpl.rc_params_from_file(fname)) if rc: self._rcParams.update(rc)
theme_matplotlib
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/overloadOverlap1.py
{ "start": 5471, "end": 6555 }
class ____(Protocol): def __radd__(self: _T1, other: Any, /) -> _T1: ... @overload def func19(a: Any, b: DProto2) -> DProto2: ... @overload def func19(a: Any, b: DProto1) -> Any: ... def func19(a: Any, b: Any) -> Any: return a + b AllStr = bytes | str @overload def func20(choices: AnyStr) -> AnyStr: ... @overload def func20(choices: AllStr) -> AllStr: ... def func20(choices: AllStr) -> AllStr: ... # This should generate an overlapping overload error. @overload def func21(self, p1: int | set[int], /) -> str: ... @overload def func21(self, p1: int | list[int], /) -> int: ... def func21(self, p1: int | set[int] | list[int], /) -> str | int: return "" @overload def func22(self, p1: str | set[int], /) -> str: ... @overload def func22(self, p1: int | list[int], /) -> int: ... def func22(self, p1: str | int | set[int] | list[int], /) -> str | int: return "" @overload def func23(f: Callable[Concatenate[_T1, _P], _T2]) -> int: ... @overload def func23(f: Callable[_P, _T2]) -> int: ... def func23(f: Any) -> int: return 1
DProto2
python
realpython__materials
hangman-pysimplegui/source_code_final/hangman.py
{ "start": 112, "end": 8029 }
class ____: def __init__(self): layout = [ [ self._build_canvas_frame(), self._build_letters_frame(), ], [ self._build_guessed_word_frame(), ], [ self._build_action_buttons_frame(), ], ] self._window = sg.Window(title="Hangman", layout=layout, finalize=True) self._canvas = self._window["-CANVAS-"] self._new_game() self.quit = False self._played_games = 0 self._won_games = 0 def _build_canvas_frame(self): return sg.Frame( "Hangman", [ [ sg.Graph( key="-CANVAS-", canvas_size=(200, 400), graph_bottom_left=(0, 0), graph_top_right=(200, 400), ) ] ], font="Any 20", ) def _build_letters_frame(self): letter_groups = [ ascii_uppercase[i : i + 4] for i in range(0, len(ascii_uppercase), 4) ] letter_buttons = [ [ sg.Button( button_text=f" {letter} ", font="Courier 20", border_width=0, button_color=(None, sg.theme_background_color()), key=f"-letter-{letter}-", enable_events=True, ) for letter in letter_group ] for letter_group in letter_groups ] return sg.Column( [ [ sg.Frame( "Letters", letter_buttons, font="Any 20", ), sg.Sizer(), ] ] ) def _build_guessed_word_frame(self): return sg.Frame( "", [ [ sg.Text( key="-DISPLAY-WORD-", font="Courier 20", ) ] ], element_justification="center", ) def _build_action_buttons_frame(self): return sg.Frame( "", [ [ sg.Sizer(h_pixels=90), sg.Button( button_text="New", key="-NEW-", font="Any 20", ), sg.Sizer(h_pixels=60), sg.Button( button_text="Restart", key="-RESTART-", font="Any 20", ), sg.Sizer(h_pixels=60), sg.Button( button_text="Quit", key="-QUIT-", font="Any 20", ), sg.Sizer(h_pixels=90), ] ], font="Any 20", ) def _draw_scaffold(self): lines = [ ((40, 55), (180, 55), 10), ((165, 60), (165, 365), 10), ((160, 360), (100, 360), 10), ((100, 365), (100, 330), 10), ((100, 330), (100, 310), 1), ] for *points, width in lines: self._canvas.DrawLine(*points, color="black", width=width) def _draw_hanged_man(self): head = (100, 290) torso = [((100, 270), (100, 170))] left_arm = [ ((100, 250), (80, 250)), ((80, 250), (60, 210)), ((60, 210), (60, 190)), ] right_arm = [ ((100, 250), (120, 250)), ((120, 250), (140, 210)), ((140, 210), (140, 190)), ] left_leg = [ ((100, 170), (80, 170)), ((80, 170), (70, 140)), ((70, 140), (70, 80)), ((70, 80), (60, 80)), ] right_leg = [ ((100, 170), (120, 170)), ((120, 170), (130, 140)), ((130, 140), (130, 80)), ((130, 80), (140, 80)), ] body = [ torso, left_arm, right_arm, left_leg, right_leg, ] if self._wrong_guesses == 1: self._canvas.DrawCircle(head, 20, line_color="red", line_width=2) elif self._wrong_guesses > 1: for part in body[self._wrong_guesses - 2]: self._canvas.DrawLine(*part, color="red", width=2) def _select_word(self): with open("words.txt", mode="r", encoding="utf-8") as words: word_list = words.readlines() return choice(word_list).strip().upper() def _build_guessed_word(self): current_letters = [] for letter in self._target_word: if letter in self._guessed_letters: current_letters.append(letter) else: current_letters.append("_") return " ".join(current_letters) def _new_game(self): self._target_word = self._select_word() self._restart_game() def _restart_game(self): self._guessed_letters = set() self._wrong_guesses = 0 self._guessed_word = self._build_guessed_word() # Restart GUI self._canvas.erase() self._draw_scaffold() for letter in ascii_uppercase: self._window[f"-letter-{letter}-"].update(disabled=False) self._window["-DISPLAY-WORD-"].update(self._guessed_word) def _play(self, letter): if letter not in self._target_word: self._wrong_guesses += 1 self._guessed_letters.add(letter) self._guessed_word = self._build_guessed_word() # Update GUI self._window[f"-letter-{letter}-"].update(disabled=True) self._window["-DISPLAY-WORD-"].update(self._guessed_word) self._draw_hanged_man() def read_event(self): event = self._window.read() event_id = event[0] if event is not None else None return event_id def process_event(self, event): if event[:8] == "-letter-": self._play(letter=event[8]) elif event == "-RESTART-": self._restart_game() elif event == "-NEW-": self._new_game() def is_over(self): return any( [ self._wrong_guesses == MAX_WRONG_GUESSES, set(self._target_word) <= self._guessed_letters, ] ) def check_winner(self): self._played_games += 1 if self._wrong_guesses < MAX_WRONG_GUESSES: self._won_games += 1 answer = sg.PopupYesNo( "You've won! Congratulations!\n" f"That's {self._won_games} out of {self._played_games}!\n" "Another round?", title="Winner!", ) else: answer = sg.PopupYesNo( f"You've lost! The word was '{self._target_word}'.\n" f"That's {self._won_games} out of {self._played_games}!\n" "Another round?", title="Sorry!", ) self.quit = answer == "No" if not self.quit: self._new_game() def close(self): self._window.close() if __name__ == "__main__": game = Hangman() # Rounds while not game.quit: # Event loop while not game.is_over(): event_id = game.read_event() if event_id in {sg.WIN_CLOSED, "-QUIT-"}: game.quit = True break game.process_event(event_id) if not game.quit: game.check_winner() game.close()
Hangman
python
getsentry__sentry
tests/sentry/releases/endpoints/test_organization_release_file_details.py
{ "start": 5580, "end": 6846 }
class ____(APITestCase): def test_simple(self) -> None: self.login_as(user=self.user) project = self.create_project(name="foo") release = Release.objects.create(organization_id=project.organization_id, version="1") release.add_project(project) assert release.count_artifacts() == 0 releasefile = ReleaseFile.objects.create( organization_id=project.organization_id, release_id=release.id, file=File.objects.create(name="application.js", type="release.file"), name="http://example.com/application.js", ) assert release.count_artifacts() == 1 url = reverse( "sentry-api-0-organization-release-file-details", kwargs={ "organization_id_or_slug": project.organization.slug, "version": release.version, "file_id": releasefile.id, }, ) response = self.client.delete(url) assert response.status_code == 204, response.content assert not ReleaseFile.objects.filter(id=releasefile.id).exists() assert not File.objects.filter(id=releasefile.file.id).exists() assert release.count_artifacts() == 0
ReleaseFileDeleteTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclass17.py
{ "start": 168, "end": 586 }
class ____: a: Final[int] b: Final[str] = "" c: ClassVar[Final[int]] = 0 d: ClassVar[Final] = 0 e: Final[ClassVar[int]] = 0 a = A(1) # This should generate an error. a.a = 0 # This should generate an error. a.b = "" # This should generate an error. a.c = 0 # This should generate an error. A.c = 0 # This should generate an error. A.d = 0 # This should generate an error. A.e = 0 @dataclass
A
python
PyCQA__pylint
doc/data/messages/l/lost-exception/good.py
{ "start": 0, "end": 346 }
class ____(ZeroDivisionError): def __init__(self): super().__init__("You can't go faster than the speed of light !") def calculate_speed(distance: float, time: float) -> float: try: return distance / time except ZeroDivisionError as e: raise FasterThanTheSpeedOfLightError() from e
FasterThanTheSpeedOfLightError
python
sqlalchemy__sqlalchemy
test/typing/plain_files/ext/asyncio/async_sessionmaker.py
{ "start": 894, "end": 2649 }
class ____(Base): __tablename__ = "b" id: Mapped[int] = mapped_column(primary_key=True) a_id = mapped_column(ForeignKey("a.id")) data: Mapped[str] def work_with_a_session_one(sess: Session) -> Any: pass def work_with_a_session_two(sess: Session, param: Optional[str] = None) -> Any: pass def work_with_wrong_parameter(session: Session, foo: int) -> Any: pass async def async_main() -> None: """Main program function.""" engine = create_async_engine( "postgresql+asyncpg://scott:tiger@localhost/test", echo=True, ) async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async_session = async_sessionmaker(engine, expire_on_commit=False) async with async_session.begin() as session: await session.run_sync(work_with_a_session_one) await session.run_sync(work_with_a_session_two, param="foo") # EXPECTED_MYPY: Missing positional argument "foo" in call to "run_sync" of "AsyncSession" await session.run_sync(work_with_wrong_parameter) session.add_all( [ A(bs=[B(), B()], data="a1"), A(bs=[B()], data="a2"), A(bs=[B(), B()], data="a3"), ] ) async with async_session() as session: result = await session.execute(select(A).order_by(A.id)) r: ScalarResult[A] = result.scalars() a1 = r.one() a1.data = "new data" await session.commit() trans_ctx = engine.begin() async with trans_ctx as connection: await connection.execute(select(A)) asyncio.run(async_main())
B
python
getsentry__sentry
src/sentry/api/serializers/rest_framework/environment.py
{ "start": 139, "end": 637 }
class ____(serializers.Field): def to_representation(self, value): return value def to_internal_value(self, data): if data is None: return None try: environment = Environment.objects.get( organization_id=self.context["organization"].id, name=data ) except Environment.DoesNotExist: raise ValidationError("Environment is not part of this organization") return environment
EnvironmentField
python
sphinx-doc__sphinx
doc/usage/extensions/example_numpy.py
{ "start": 4941, "end": 5806 }
class ____(Exception): """Exceptions are documented in the same way as classes. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. Note ---- Do not include the `self` parameter in the ``Parameters`` section. Parameters ---------- msg : str Human readable string describing the exception. code : :obj:`int`, optional Numeric error code. Attributes ---------- msg : str Human readable string describing the exception. code : int Numeric error code. """ def __init__(self, msg, code): self.msg = msg self.code = code
ExampleError
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 489547, "end": 490189 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("PackageVersionEdge"), graphql_name="edges" ) nodes = sgqlc.types.Field( sgqlc.types.list_of("PackageVersion"), graphql_name="nodes" ) page_info = sgqlc.types.Field( sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
PackageVersionConnection
python
modin-project__modin
modin/config/envvars.py
{ "start": 38962, "end": 39167 }
class ____(EnvironmentVariable, type=str): """Set to AWS_ACCESS_KEY_ID when running mock S3 tests for Modin in GitHub CI.""" varname = "AWS_ACCESS_KEY_ID" default = "foobar_key"
CIAWSAccessKeyID
python
automl__auto-sklearn
test/test_pipeline/test_classification.py
{ "start": 2724, "end": 3548 }
class ____(AutoSklearnPreprocessingAlgorithm): def __init__(*args, **kwargs): pass @staticmethod def get_properties(dataset_properties=None): return { "shortname": "AB", "name": "AdaBoost Classifier", "handles_regression": False, "handles_classification": True, "handles_multiclass": True, "handles_multilabel": True, "handles_multioutput": False, "is_deterministic": True, "input": (DENSE, SPARSE, UNSIGNED_DATA), "output": (INPUT,), } def fit(self, X, y): raise ValueError("Make sure fit is called") @staticmethod def get_hyperparameter_search_space(dataset_properties=None): cs = ConfigurationSpace() return cs
CrashPreprocessor
python
instagram__MonkeyType
demo/models.py
{ "start": 1980, "end": 2290 }
class ____(InboxEvent): type = EventType.FOLLOWED def __init__( self, id: InboxEventId, user_id: UserId, published: datetime, follower_id: UserId, ) -> None: super().__init__(id, user_id, published) self.follower_id = follower_id
FollowedEvent
python
airbytehq__airbyte
airbyte-integrations/connectors/source-salesforce/source_salesforce/streams.py
{ "start": 2875, "end": 7097 }
class ____(HttpStream, ABC): state_converter = IsoMillisConcurrentStreamStateConverter(is_sequential_state=False) page_size = 2000 transformer = TypeTransformer(TransformConfig.DefaultSchemaNormalization) encoding = DEFAULT_ENCODING def __init__( self, sf_api: Salesforce, pk: str, stream_name: str, job_tracker: JobTracker, message_repository: MessageRepository, sobject_options: Mapping[str, Any] = None, schema: dict = None, start_date=None, **kwargs, ): self.stream_name = stream_name self.pk = pk self.sf_api = sf_api super().__init__(**kwargs) self.schema: Mapping[str, Any] = schema # type: ignore[assignment] self.sobject_options = sobject_options self.start_date = self.format_start_date(start_date) self._job_tracker = job_tracker self._message_repository = message_repository self._http_client = HttpClient( self.stream_name, self.logger, session=self._http_client._session, # no need to specific api_budget and authenticator as HttpStream sets them in self._session error_handler=SalesforceErrorHandler(stream_name=self.stream_name, sobject_options=self.sobject_options), ) def read_records( self, sync_mode: SyncMode, cursor_field: Optional[List[str]] = None, stream_slice: Optional[Mapping[str, Any]] = None, stream_state: Optional[Mapping[str, Any]] = None, ) -> Iterable[StreamData]: """ In order to avoid RFR which does uses `_read_single_page` instead of `_read_pages` """ yield from super().read_records(sync_mode, cursor_field, stream_slice, stream_state) @staticmethod def format_start_date(start_date: Optional[str]) -> Optional[str]: """Transform the format `2021-07-25` into the format `2021-07-25T00:00:00Z`""" if start_date: return pendulum.parse(start_date).strftime("%Y-%m-%dT%H:%M:%SZ") # type: ignore[attr-defined,no-any-return] return None @property def max_properties_length(self) -> int: return Salesforce.REQUEST_SIZE_LIMITS - len(self.url_base) - 2000 @property def name(self) -> str: return self.stream_name @property def primary_key(self) -> Optional[Union[str, List[str], List[List[str]]]]: return self.pk @property def url_base(self) -> str: return self.sf_api.instance_url @property def too_many_properties(self): selected_properties = self.get_json_schema().get("properties", {}) properties_length = len(urllib.parse.quote(",".join(p for p in selected_properties))) return properties_length > self.max_properties_length def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]: yield from response.json()["records"] def get_json_schema(self) -> Mapping[str, Any]: if not self.schema: self.schema = self.sf_api.generate_schema(self.name) return self.schema def get_error_display_message(self, exception: BaseException) -> Optional[str]: if isinstance(exception, exceptions.ConnectionError): return f"After {self.max_retries} retries the connector has failed with a network error. It looks like Salesforce API experienced temporary instability, please try again later." return super().get_error_display_message(exception) def get_start_date_from_state(self, stream_state: Mapping[str, Any] = None) -> pendulum.DateTime: if self.state_converter.is_state_message_compatible(stream_state): # stream_state is in the concurrent format if stream_state.get("slices", []): return stream_state["slices"][0]["end"] elif stream_state and not self.state_converter.is_state_message_compatible(stream_state): # stream_state has not been converted to the concurrent format; this is not expected return pendulum.parse(stream_state.get(self.cursor_field), tz="UTC") return pendulum.parse(self.start_date, tz="UTC")
SalesforceStream
python
doocs__leetcode
solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.py
{ "start": 0, "end": 368 }
class ____: def equalSubstring(self, s: str, t: str, maxCost: int) -> int: n = len(s) ans = cost = l = 0 for r in range(n): cost += abs(ord(s[r]) - ord(t[r])) while cost > maxCost: cost -= abs(ord(s[l]) - ord(t[l])) l += 1 ans = max(ans, r - l + 1) return ans
Solution
python
PrefectHQ__prefect
tests/blocks/test_abstract.py
{ "start": 3875, "end": 7592 }
class ____: def test_database_block_is_abstract(self): with pytest.raises( TypeError, match="Can't instantiate abstract class DatabaseBlock" ): DatabaseBlock() async def test_database_block_implementation(self, caplog): class ADatabaseBlock(DatabaseBlock): def __init__(self): super().__init__() self._results = tuple( zip(["apple", "banana", "cherry"], [1, 2, 3], [True, False, True]) ) self._engine = None def fetch_one(self, operation, parameters=None, **execution_kwargs): self.logger.info(f"Fetching one result using {parameters}.") return self._results[0] def fetch_many( self, operation, parameters=None, size=None, **execution_kwargs ): self.logger.info(f"Fetching {size} results using {parameters}.") return self._results[:size] def fetch_all(self, operation, parameters=None, **execution_kwargs): self.logger.info(f"Fetching all results using {parameters}.") return self._results def execute(self, operation, parameters=None, **execution_kwargs) -> None: self.logger.info(f"Executing operation using {parameters}.") def execute_many( self, operation, seq_of_parameters, **execution_kwargs ) -> None: self.logger.info( f"Executing many operations using {seq_of_parameters}." ) def __enter__(self): self._engine = True return self def __exit__(self, *args): self._engine = None a_database_block = ADatabaseBlock() parameters = {"a": "b"} assert a_database_block.fetch_one( "SELECT * FROM table", parameters=parameters ) == ("apple", 1, True) assert a_database_block.fetch_many( "SELECT * FROM table", size=2, parameters=parameters ) == (("apple", 1, True), ("banana", 2, False)) assert a_database_block.fetch_all( "SELECT * FROM table", parameters=parameters ) == (("apple", 1, True), ("banana", 2, False), ("cherry", 3, True)) assert ( a_database_block.execute( "INSERT INTO table VALUES (1, 2, 3)", parameters=parameters ) is None ) assert ( a_database_block.execute_many( "INSERT INTO table VALUES (1, 2, 3)", seq_of_parameters=[parameters, parameters], parameters=parameters, ) is None ) records = caplog.records for record in records: assert record.name == "prefect.ADatabaseBlock" assert records[0].message == "Fetching one result using {'a': 'b'}." assert records[1].message == "Fetching 2 results using {'a': 'b'}." assert records[2].message == "Fetching all results using {'a': 'b'}." assert records[3].message == "Executing operation using {'a': 'b'}." assert ( records[4].message == "Executing many operations using [{'a': 'b'}, {'a': 'b'}]." ) # test context manager with a_database_block as db: assert db._engine is True assert a_database_block._engine is None match = "ADatabaseBlock does not support async context management." with pytest.raises(NotImplementedError, match=match): async with a_database_block: pass
TestDatabaseBlock
python
altair-viz__altair
altair/vegalite/v6/schema/_config.py
{ "start": 180626, "end": 201767 }
class ____(TypedDict, total=False): """ :class:`altair.OverlayMarkDef` ``TypedDict`` wrapper. Parameters ---------- align The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). One of ``"left"``, ``"right"``, ``"center"``. **Note:** Expression reference is *not* supported for range marks. angle The rotation angle of the text, in degrees. aria A boolean flag indicating if `ARIA attributes <https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA>`__ should be included (SVG output only). If ``false``, the "aria-hidden" attribute will be set on the output SVG element, removing the mark item from the ARIA accessibility tree. ariaRole Sets the type of user interface element of the mark item for `ARIA accessibility <https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA>`__ (SVG output only). If specified, this property determines the "role" attribute. Warning: this property is experimental and may be changed in the future. ariaRoleDescription A human-readable, author-localized description for the role of the mark item for `ARIA accessibility <https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA>`__ (SVG output only). If specified, this property determines the "aria-roledescription" attribute. Warning: this property is experimental and may be changed in the future. aspect Whether to keep aspect ratio of image marks. baseline For text marks, the vertical text baseline. One of ``"alphabetic"`` (default), ``"top"``, ``"middle"``, ``"bottom"``, ``"line-top"``, ``"line-bottom"``, or an expression reference that provides one of the valid values. The ``"line-top"`` and ``"line-bottom"`` values operate similarly to ``"top"`` and ``"bottom"``, but are calculated relative to the ``lineHeight`` rather than ``fontSize`` alone. For range marks, the vertical alignment of the marks. One of ``"top"``, ``"middle"``, ``"bottom"``. **Note:** Expression reference is *not* supported for range marks. blend The color blend mode for drawing an item on its current background. Any valid `CSS mix-blend-mode <https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode>`__ value can be used. **Default value:** ``"source-over"`` clip Whether a mark be clipped to the enclosing group's width and height. color Default color. **Default value:** ``"#4682b4"`` **Note:** * This property cannot be used in a `style config <https://vega.github.io/vega-lite/docs/mark.html#style-config>`__. * The ``fill`` and ``stroke`` properties have higher precedence than ``color`` and will override ``color``. cornerRadius The radius in pixels of rounded rectangles or arcs' corners. **Default value:** ``0`` cornerRadiusBottomLeft The radius in pixels of rounded rectangles' bottom left corner. **Default value:** ``0`` cornerRadiusBottomRight The radius in pixels of rounded rectangles' bottom right corner. **Default value:** ``0`` cornerRadiusTopLeft The radius in pixels of rounded rectangles' top right corner. **Default value:** ``0`` cornerRadiusTopRight The radius in pixels of rounded rectangles' top left corner. **Default value:** ``0`` cursor The mouse cursor used over the mark. Any valid `CSS cursor type <https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#Values>`__ can be used. description A text description of the mark item for `ARIA accessibility <https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA>`__ (SVG output only). If specified, this property determines the `"aria-label" attribute <https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute>`__. dir The direction of the text. One of ``"ltr"`` (left-to-right) or ``"rtl"`` (right-to-left). This property determines on which side is truncated in response to the limit parameter. **Default value:** ``"ltr"`` dx The horizontal offset, in pixels, between the text label and its anchor point. The offset is applied after rotation by the *angle* property. dy The vertical offset, in pixels, between the text label and its anchor point. The offset is applied after rotation by the *angle* property. ellipsis The ellipsis string for text truncated in response to the limit parameter. **Default value:** ``"…"`` endAngle The end angle in radians for arc marks. A value of ``0`` indicates up (north), increasing values proceed clockwise. fill Default fill color. This property has higher precedence than ``config.color``. Set to ``null`` to remove fill. **Default value:** (None) fillOpacity The fill opacity (value between [0,1]). **Default value:** ``1`` filled Whether the mark's color should be used as fill color instead of stroke color. **Default value:** ``false`` for all ``point``, ``line``, and ``rule`` marks as well as ``geoshape`` marks for `graticule <https://vega.github.io/vega-lite/docs/data.html#graticule>`__ data sources; otherwise, ``true``. **Note:** This property cannot be used in a `style config <https://vega.github.io/vega-lite/docs/mark.html#style-config>`__. font The typeface to set the text in (e.g., ``"Helvetica Neue"``). fontSize The font size, in pixels. **Default value:** ``11`` fontStyle The font style (e.g., ``"italic"``). fontWeight The font weight. This can be either a string (e.g ``"bold"``, ``"normal"``) or a number (``100``, ``200``, ``300``, ..., ``900`` where ``"normal"`` = ``400`` and ``"bold"`` = ``700``). height Height of the marks. href A URL to load upon mouse click. If defined, the mark acts as a hyperlink. innerRadius The inner radius in pixels of arc marks. ``innerRadius`` is an alias for ``radius2``. **Default value:** ``0`` interpolate The line interpolation method to use for line and area marks. One of the following: * ``"linear"``: piecewise linear segments, as in a polyline. * ``"linear-closed"``: close the linear segments to form a polygon. * ``"step"``: alternate between horizontal and vertical segments, as in a step function. * ``"step-before"``: alternate between vertical and horizontal segments, as in a step function. * ``"step-after"``: alternate between horizontal and vertical segments, as in a step function. * ``"basis"``: a B-spline, with control point duplication on the ends. * ``"basis-open"``: an open B-spline; may not intersect the start or end. * ``"basis-closed"``: a closed B-spline, as in a loop. * ``"cardinal"``: a Cardinal spline, with control point duplication on the ends. * ``"cardinal-open"``: an open Cardinal spline; may not intersect the start or end, but will intersect other control points. * ``"cardinal-closed"``: a closed Cardinal spline, as in a loop. * ``"bundle"``: equivalent to basis, except the tension parameter is used to straighten the spline. * ``"monotone"``: cubic interpolation that preserves monotonicity in y. invalid Invalid data mode, which defines how the marks and corresponding scales should represent invalid values (``null`` and ``NaN`` in continuous scales *without* defined output for invalid values). * ``"filter"`` — *Exclude* all invalid values from the visualization's *marks* and *scales*. For path marks (for line, area, trail), this option will create paths that connect valid points, as if the data rows with invalid values do not exist. * ``"break-paths-filter-domains"`` — Break path marks (for line, area, trail) at invalid values. For non-path marks, this is equivalent to ``"filter"``. All *scale* domains will *exclude* these filtered data points. * ``"break-paths-show-domains"`` — Break paths (for line, area, trail) at invalid values. Hide invalid values for non-path marks. All *scale* domains will *include* these filtered data points (for both path and non-path marks). * ``"show"`` or ``null`` — Show all data points in the marks and scale domains. Each scale will use the output for invalid values defined in ``config.scale.invalid`` or, if unspecified, by default invalid values will produce the same visual values as zero (if the scale includes zero) or the minimum value (if the scale does not include zero). * ``"break-paths-show-path-domains"`` (default) — This is equivalent to ``"break-paths-show-domains"`` for path-based marks (line/area/trail) and ``"filter"`` for non-path marks. **Note**: If any channel's scale has an output for invalid values defined in ``config.scale.invalid``, all values for the scales will be considered "valid" since they can produce a reasonable output for the scales. Thus, fields for such channels will not be filtered and will not cause path breaks. limit The maximum length of the text mark in pixels. The text value will be automatically truncated if the rendered size exceeds the limit. **Default value:** ``0`` -- indicating no limit lineBreak A delimiter, such as a newline character, upon which to break text strings into multiple lines. This property is ignored if the text is array-valued. lineHeight The line height in pixels (the spacing between subsequent lines of text) for multi-line text marks. opacity The overall opacity (value between [0,1]). **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. order For line and trail marks, this ``order`` property can be set to ``null`` or ``false`` to make the lines use the original order in the data sources. orient The orientation of a non-stacked bar, tick, area, and line charts. The value is either horizontal (default) or vertical. * For bar, rule and tick, this determines whether the size of the bar and tick should be applied to x or y dimension. * For area, this property determines the orient property of the Vega output. * For line and trail marks, this property determines the sort order of the points in the line if ``config.sortLineBy`` is not specified. For stacked charts, this is always determined by the orientation of the stack; therefore explicitly specified value will be ignored. outerRadius The outer radius in pixels of arc marks. ``outerRadius`` is an alias for ``radius``. **Default value:** ``0`` padAngle The angular padding applied to sides of the arc, in radians. radius For arc mark, the primary (outer) radius in pixels. For text marks, polar coordinate radial offset, in pixels, of the text from the origin determined by the ``x`` and ``y`` properties. **Default value:** ``min(plot_width, plot_height)/2`` radius2 The secondary (inner) radius in pixels of arc marks. **Default value:** ``0`` radius2Offset Offset for radius2. radiusOffset Offset for radius. shape Shape of the point marks. Supported values include: * plotting shapes: ``"circle"``, ``"square"``, ``"cross"``, ``"diamond"``, ``"triangle-up"``, ``"triangle-down"``, ``"triangle-right"``, or ``"triangle-left"``. * the line symbol ``"stroke"`` * centered directional shapes ``"arrow"``, ``"wedge"``, or ``"triangle"`` * a custom `SVG path string <https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths>`__ (For correct sizing, custom shape paths should be defined within a square bounding box with coordinates ranging from -1 to 1 along both the x and y dimensions.) **Default value:** ``"circle"`` size Default size for marks. * For ``point``/``circle``/``square``, this represents the pixel area of the marks. Note that this value sets the area of the symbol; the side lengths will increase with the square root of this value. * For ``bar``, this represents the band size of the bar, in pixels. * For ``text``, this represents the font size, in pixels. **Default value:** * ``30`` for point, circle, square marks; width/height's ``step`` * ``2`` for bar marks with discrete dimensions; * ``5`` for bar marks with continuous dimensions; * ``11`` for text marks. smooth A boolean flag (default true) indicating if the image should be smoothed when resized. If false, individual pixels should be scaled directly rather than interpolated with smoothing. For SVG rendering, this option may not work in some browsers due to lack of standardization. startAngle The start angle in radians for arc marks. A value of ``0`` indicates up (north), increasing values proceed clockwise. stroke Default stroke color. This property has higher precedence than ``config.color``. Set to ``null`` to remove stroke. **Default value:** (None) strokeCap The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or ``"square"``. **Default value:** ``"butt"`` strokeDash An array of alternating stroke, space lengths for creating dashed or dotted lines. strokeDashOffset The offset (in pixels) into which to begin drawing with the stroke dash array. strokeJoin The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. **Default value:** ``"miter"`` strokeMiterLimit The miter limit at which to bevel a line join. strokeOffset The offset in pixels at which to draw the group stroke and fill. If unspecified, the default behavior is to dynamically offset stroked groups such that 1 pixel stroke widths align with the pixel grid. strokeOpacity The stroke opacity (value between [0,1]). **Default value:** ``1`` strokeWidth The stroke width, in pixels. style A string or array of strings indicating the name of custom styles to apply to the mark. A style is a named collection of mark property defaults defined within the `style configuration <https://vega.github.io/vega-lite/docs/mark.html#style-config>`__. If style is an array, later styles will override earlier styles. Any `mark properties <https://vega.github.io/vega-lite/docs/encoding.html#mark-prop>`__ explicitly defined within the ``encoding`` will override a style default. **Default value:** The mark's name. For example, a bar mark will have style ``"bar"`` by default. **Note:** Any specified style will augment the default style. For example, a bar mark with ``"style": "foo"`` will receive from ``config.style.bar`` and ``config.style.foo`` (the specified style ``"foo"`` has higher precedence). tension Depending on the interpolation type, sets the tension parameter (for line and area marks). text Placeholder text if the ``text`` channel is not specified theta * For arc marks, the arc length in radians if theta2 is not specified, otherwise the start arc angle. (A value of 0 indicates up or “north”, increasing values proceed clockwise.) * For text marks, polar coordinate angle in radians. theta2 The end angle of arc marks in radians. A value of 0 indicates up or “north”, increasing values proceed clockwise. theta2Offset Offset for theta2. thetaOffset Offset for theta. time timeUnitBandPosition Default relative band position for a time unit. If set to ``0``, the marks will be positioned at the beginning of the time unit band step. If set to ``0.5``, the marks will be positioned in the middle of the time unit band step. timeUnitBandSize Default relative band size for a time unit. If set to ``1``, the bandwidth of the marks will be equal to the time unit band step. If set to ``0.5``, bandwidth of the marks will be half of the time unit band step. tooltip The tooltip text string to show upon mouse hover or an object defining which fields should the tooltip be derived from. * If ``tooltip`` is ``true`` or ``{"content": "encoding"}``, then all fields from ``encoding`` will be used. * If ``tooltip`` is ``{"content": "data"}``, then all fields that appear in the highlighted data point will be used. * If set to ``null`` or ``false``, then no tooltip will be used. See the `tooltip <https://vega.github.io/vega-lite/docs/tooltip.html>`__ documentation for a detailed discussion about tooltip in Vega-Lite. **Default value:** ``null`` url The URL of the image file for image marks. width Width of the marks. x X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without specified ``x2`` or ``width``. The ``value`` of this channel can be a number or a string ``"width"`` for the width of the plot. x2 X2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. The ``value`` of this channel can be a number or a string ``"width"`` for the width of the plot. x2Offset Offset for x2-position. xOffset Offset for x-position. y Y coordinates of the marks, or height of vertical ``"bar"`` and ``"area"`` without specified ``y2`` or ``height``. The ``value`` of this channel can be a number or a string ``"height"`` for the height of the plot. y2 Y2 coordinates for ranged ``"area"``, ``"bar"``, ``"rect"``, and ``"rule"``. The ``value`` of this channel can be a number or a string ``"height"`` for the height of the plot. y2Offset Offset for y2-position. yOffset Offset for y-position. """ align: Align_T angle: float aria: bool ariaRole: str ariaRoleDescription: str aspect: bool baseline: TextBaseline_T blend: Blend_T clip: bool color: ColorHex | LinearGradientKwds | RadialGradientKwds | ColorName_T cornerRadius: float cornerRadiusBottomLeft: float cornerRadiusBottomRight: float cornerRadiusTopLeft: float cornerRadiusTopRight: float cursor: Cursor_T description: str dir: TextDirection_T dx: float dy: float ellipsis: str endAngle: float fill: ColorHex | LinearGradientKwds | RadialGradientKwds | ColorName_T | None fillOpacity: float filled: bool font: str fontSize: float fontStyle: str fontWeight: FontWeight_T height: float href: str innerRadius: float interpolate: Interpolate_T invalid: MarkInvalidDataMode_T | None limit: float lineBreak: str lineHeight: float opacity: float order: bool | None orient: Orientation_T outerRadius: float padAngle: float radius: float radius2: float radius2Offset: float radiusOffset: float shape: str size: float smooth: bool startAngle: float stroke: ColorHex | LinearGradientKwds | RadialGradientKwds | ColorName_T | None strokeCap: StrokeCap_T strokeDash: Sequence[float] strokeDashOffset: float strokeJoin: StrokeJoin_T strokeMiterLimit: float strokeOffset: float strokeOpacity: float strokeWidth: float style: str | Sequence[str] tension: float text: str | Sequence[str] theta: float theta2: float theta2Offset: float thetaOffset: float time: float timeUnitBandPosition: float timeUnitBandSize: float tooltip: str | bool | float | TooltipContentKwds | None url: str width: float x: float | Literal["width"] x2: float | Literal["width"] x2Offset: float xOffset: float y: float | Literal["height"] y2: float | Literal["height"] y2Offset: float yOffset: float
OverlayMarkDefKwds
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 53042, "end": 54386 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) jar_uri: Optional[str] = Field( None, deprecated=True, description=( "Deprecated since 04/2016\\. Provide a `jar` through the `libraries` field" " instead. For an example, see" " [Create](https://docs.databricks.com/dev-tools/api/latest/jobs.html#operation/JobsCreate)." ), ) main_class_name: Optional[str] = Field( None, description=( "The full name of the class containing the main method to be executed. This" " class must be contained in a JAR provided as a library.\n\nThe code must" " use `SparkContext.getOrCreate` to obtain a Spark context; otherwise, runs" " of the job fail." ), examples=["com.databricks.ComputeModels"], ) parameters: Optional[List[str]] = Field( None, description=( "Parameters passed to the main method.\n\nUse [Task parameter" " variables](https://docs.databricks.com/jobs.html#parameter-variables) to" " set parameters containing information about job runs." ), examples=[["--data", "dbfs:/path/to/data.json"]], )
SparkJarTask
python
django__django
django/contrib/auth/views.py
{ "start": 13699, "end": 13870 }
class ____(PasswordContextMixin, TemplateView): template_name = "registration/password_change_done.html" title = _("Password change successful")
PasswordChangeDoneView
python
sqlalchemy__sqlalchemy
test/aaa_profiling/test_resultset.py
{ "start": 5238, "end": 6181 }
class ____(fixtures.TestBase): __backend__ = True def test_minimal_connection_execute(self): # create an engine without any instrumentation. e = create_engine("sqlite://") c = e.connect() # ensure initial connect activities complete c.exec_driver_sql("select 1") @profiling.function_call_count() def go(): c.exec_driver_sql("select 1") try: go() finally: c.close() def test_minimal_engine_execute(self, variance=0.10): # create an engine without any instrumentation. e = create_engine("sqlite://") # ensure initial connect activities complete with e.connect() as conn: conn.exec_driver_sql("select 1") @profiling.function_call_count() def go(): with e.connect() as conn: conn.exec_driver_sql("select 1") go()
ExecutionTest
python
sqlalchemy__sqlalchemy
test/sql/test_operators.py
{ "start": 47394, "end": 51897 }
class ____(fixtures.TestBase, testing.AssertsCompiledSQL): """test standalone booleans being wrapped in an AsBoolean, as well as true/false compilation.""" def _dialect(self, native_boolean): d = default.DefaultDialect() d.supports_native_boolean = native_boolean return d def test_one(self): c = column("x", Boolean) self.assert_compile( select(c).where(c), "SELECT x WHERE x", dialect=self._dialect(True), ) def test_two_a(self): c = column("x", Boolean) self.assert_compile( select(c).where(c), "SELECT x WHERE x = 1", dialect=self._dialect(False), ) def test_two_b(self): c = column("x", Boolean) self.assert_compile( select(c).where(c), "SELECT x WHERE x = 1", dialect=self._dialect(False), ) def test_three_a(self): c = column("x", Boolean) self.assert_compile( select(c).where(~c), "SELECT x WHERE x = 0", dialect=self._dialect(False), ) def test_three_a_double(self): c = column("x", Boolean) self.assert_compile( select(c).where(~~c), "SELECT x WHERE x = 1", dialect=self._dialect(False), ) def test_three_b(self): c = column("x", Boolean) self.assert_compile( select(c).where(~c), "SELECT x WHERE x = 0", dialect=self._dialect(False), ) def test_four(self): c = column("x", Boolean) self.assert_compile( select(c).where(~c), "SELECT x WHERE NOT x", dialect=self._dialect(True), ) def test_four_double(self): c = column("x", Boolean) self.assert_compile( select(c).where(~~c), "SELECT x WHERE x", dialect=self._dialect(True), ) def test_five_a(self): c = column("x", Boolean) self.assert_compile( select(c).having(c), "SELECT x HAVING x = 1", dialect=self._dialect(False), ) def test_five_b(self): c = column("x", Boolean) self.assert_compile( select(c).having(c), "SELECT x HAVING x = 1", dialect=self._dialect(False), ) def test_six(self): self.assert_compile( or_(false(), true()), "1 = 1", dialect=self._dialect(False) ) def test_seven_a(self): t1 = table("t1", column("a")) t2 = table("t2", column("b")) self.assert_compile( join(t1, t2, onclause=true()), "t1 JOIN t2 ON 1 = 1", dialect=self._dialect(False), ) def test_seven_b(self): t1 = table("t1", column("a")) t2 = table("t2", column("b")) self.assert_compile( join(t1, t2, onclause=false()), "t1 JOIN t2 ON 0 = 1", dialect=self._dialect(False), ) def test_seven_c(self): t1 = table("t1", column("a")) t2 = table("t2", column("b")) self.assert_compile( join(t1, t2, onclause=true()), "t1 JOIN t2 ON true", dialect=self._dialect(True), ) def test_seven_d(self): t1 = table("t1", column("a")) t2 = table("t2", column("b")) self.assert_compile( join(t1, t2, onclause=false()), "t1 JOIN t2 ON false", dialect=self._dialect(True), ) def test_eight(self): self.assert_compile( and_(false(), true()), "false", dialect=self._dialect(True) ) def test_nine(self): self.assert_compile( and_(false(), true()), "0 = 1", dialect=self._dialect(False) ) def test_ten(self): c = column("x", Boolean) self.assert_compile(c == 1, "x = :x_1", dialect=self._dialect(False)) def test_eleven(self): c = column("x", Boolean) self.assert_compile( c.is_(true()), "x IS true", dialect=self._dialect(True) ) def test_twelve(self): c = column("x", Boolean) # I don't have a solution for this one yet, # other than adding some heavy-handed conditionals # into compiler self.assert_compile( c.is_(true()), "x IS 1", dialect=self._dialect(False) )
BooleanEvalTest
python
aimacode__aima-python
mdp.py
{ "start": 9216, "end": 13120 }
class ____(MDP): """A Partially Observable Markov Decision Process, defined by a transition model P(s'|s,a), actions A(s), a reward function R(s), and a sensor model P(e|s). We also keep track of a gamma value, for use by algorithms. The transition and the sensor models are defined as matrices. We also keep track of the possible states and actions for each state. [Page 659].""" def __init__(self, actions, transitions=None, evidences=None, rewards=None, states=None, gamma=0.95): """Initialize variables of the pomdp""" if not (0 < gamma <= 1): raise ValueError('A POMDP must have 0 < gamma <= 1') self.states = states self.actions = actions # transition model cannot be undefined self.t_prob = transitions or {} if not self.t_prob: print('Warning: Transition model is undefined') # sensor model cannot be undefined self.e_prob = evidences or {} if not self.e_prob: print('Warning: Sensor model is undefined') self.gamma = gamma self.rewards = rewards def remove_dominated_plans(self, input_values): """ Remove dominated plans. This method finds all the lines contributing to the upper surface and removes those which don't. """ values = [val for action in input_values for val in input_values[action]] values.sort(key=lambda x: x[0], reverse=True) best = [values[0]] y1_max = max(val[1] for val in values) tgt = values[0] prev_b = 0 prev_ix = 0 while tgt[1] != y1_max: min_b = 1 min_ix = 0 for i in range(prev_ix + 1, len(values)): if values[i][0] - tgt[0] + tgt[1] - values[i][1] != 0: trans_b = (values[i][0] - tgt[0]) / (values[i][0] - tgt[0] + tgt[1] - values[i][1]) if 0 <= trans_b <= 1 and trans_b > prev_b and trans_b < min_b: min_b = trans_b min_ix = i prev_b = min_b prev_ix = min_ix tgt = values[min_ix] best.append(tgt) return self.generate_mapping(best, input_values) def remove_dominated_plans_fast(self, input_values): """ Remove dominated plans using approximations. Resamples the upper boundary at intervals of 100 and finds the maximum values at these points. """ values = [val for action in input_values for val in input_values[action]] values.sort(key=lambda x: x[0], reverse=True) best = [] sr = 100 for i in range(sr + 1): x = i / float(sr) maximum = (values[0][1] - values[0][0]) * x + values[0][0] tgt = values[0] for value in values: val = (value[1] - value[0]) * x + value[0] if val > maximum: maximum = val tgt = value if all(any(tgt != v) for v in best): best.append(np.array(tgt)) return self.generate_mapping(best, input_values) def generate_mapping(self, best, input_values): """Generate mappings after removing dominated plans""" mapping = defaultdict(list) for value in best: for action in input_values: if any(all(value == v) for v in input_values[action]): mapping[action].append(value) return mapping def max_difference(self, U1, U2): """Find maximum difference between two utility mappings""" for k, v in U1.items(): sum1 = 0 for element in U1[k]: sum1 += sum(element) sum2 = 0 for element in U2[k]: sum2 += sum(element) return abs(sum1 - sum2)
POMDP
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/assets/graph/asset_graph_differ.py
{ "start": 1832, "end": 8338 }
class ____: """Given two asset graphs, base_asset_graph and branch_asset_graph, we can compute how the assets in branch_asset_graph have changed with respect to base_asset_graph. The ChangeReason enum contains the list of potential changes an asset can undergo. If the base_asset_graph is None, this indicates that the branch_asset_graph does not yet exist in the base deployment. In this case we will consider every asset New. """ def __init__( self, branch_asset_graph: "RemoteAssetGraph", base_asset_graph: Optional["RemoteAssetGraph"], ): self._branch_asset_graph = branch_asset_graph self._base_asset_graph = base_asset_graph def _compare_base_and_branch_assets( self, asset_key: "AssetKey", include_diff: bool = False ) -> AssetDefinitionDiffDetails: """Computes the diff between a branch deployment asset and the corresponding base deployment asset. """ if not self._base_asset_graph or not self._base_asset_graph.has(asset_key): # if the base asset graph is None, it is because the asset graph in the branch deployment # is new and doesn't exist in the base deployment. Thus all assets are new. return AssetDefinitionDiffDetails(change_types={AssetDefinitionChangeType.NEW}) if not self._branch_asset_graph.has(asset_key): return AssetDefinitionDiffDetails(change_types={AssetDefinitionChangeType.REMOVED}) base_asset = self._base_asset_graph.get(asset_key).resolve_to_singular_repo_scoped_node() # This may not detect the case where an asset is moved from one repository or code location # to another as a change. branch_asset = self._branch_asset_graph.get( asset_key ).resolve_to_singular_repo_scoped_node() change_types: set[AssetDefinitionChangeType] = set() code_version_diff: Optional[ValueDiff] = None dependencies_diff: Optional[DictDiff] = None partitions_definition_diff: Optional[ValueDiff] = None tags_diff: Optional[DictDiff] = None metadata_diff: Optional[DictDiff] = None if branch_asset.code_version != base_asset.code_version: change_types.add(AssetDefinitionChangeType.CODE_VERSION) if include_diff: code_version_diff = ValueDiff( old=base_asset.code_version, new=branch_asset.code_version ) if branch_asset.parent_keys != base_asset.parent_keys: change_types.add(AssetDefinitionChangeType.DEPENDENCIES) if include_diff: dependencies_diff = DictDiff( added_keys=branch_asset.parent_keys - base_asset.parent_keys, changed_keys=set(), removed_keys=base_asset.parent_keys - branch_asset.parent_keys, ) else: # if the set of upstream dependencies is different, then we don't need to check if the partition mappings # for dependencies have changed since ChangeReason.DEPENDENCIES is already in the list of changes for upstream_asset_key in branch_asset.parent_keys: if branch_asset.partition_mappings.get( upstream_asset_key ) != base_asset.partition_mappings.get(upstream_asset_key): change_types.add(AssetDefinitionChangeType.DEPENDENCIES) if include_diff: dependencies_diff = DictDiff( added_keys=set(), changed_keys={upstream_asset_key}, removed_keys=set(), ) break if branch_asset.partitions_def != base_asset.partitions_def: change_types.add(AssetDefinitionChangeType.PARTITIONS_DEFINITION) if include_diff: partitions_definition_diff = ValueDiff( old=type(base_asset.partitions_def).__name__ if base_asset.partitions_def else None, new=type(branch_asset.partitions_def).__name__ if branch_asset.partitions_def else None, ) if branch_asset.tags != base_asset.tags: change_types.add(AssetDefinitionChangeType.TAGS) if include_diff: added, changed, removed = self._get_map_keys_diff( base_asset.tags, branch_asset.tags ) tags_diff = DictDiff(added_keys=added, changed_keys=changed, removed_keys=removed) if branch_asset.metadata != base_asset.metadata: change_types.add(AssetDefinitionChangeType.METADATA) if include_diff: added, changed, removed = self._get_map_keys_diff( base_asset.metadata, branch_asset.metadata ) metadata_diff = DictDiff( added_keys=added, changed_keys=changed, removed_keys=removed ) return AssetDefinitionDiffDetails( change_types=change_types, code_version=code_version_diff, dependencies=dependencies_diff, partitions_definition=partitions_definition_diff, tags=tags_diff, metadata=metadata_diff, ) def _get_map_keys_diff( self, base: Mapping[str, Any], branch: Mapping[str, Any] ) -> MappedKeyDiff: """Returns the added, changed, and removed keys in the branch map compared to the base map.""" added = set(branch.keys()) - set(base.keys()) changed = {key for key in branch.keys() if key in base and branch[key] != base[key]} removed = set(base.keys()) - set(branch.keys()) return MappedKeyDiff(added, changed, removed) def get_changes_for_asset(self, asset_key: "AssetKey") -> Sequence[AssetDefinitionChangeType]: """Returns list of AssetDefinitionChangeType for asset_key as compared to the base deployment.""" return list(self._compare_base_and_branch_assets(asset_key).change_types) def get_changes_for_asset_with_diff(self, asset_key: "AssetKey") -> AssetDefinitionDiffDetails: """Returns list of AssetDefinitionDiff for asset_key as compared to the base deployment.""" return self._compare_base_and_branch_assets(asset_key, include_diff=True)
AssetGraphDiffer
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/instigation.py
{ "start": 4572, "end": 4778 }
class ____(graphene.Enum): ADD_PARTITIONS = "ADD_PARTITIONS" DELETE_PARTITIONS = "DELETE_PARTITIONS" class Meta: name = "DynamicPartitionsRequestType"
GrapheneDynamicPartitionsRequestType
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 49668, "end": 50376 }
class ____(themeable): """ x-axis minor-tick length Parameters ---------- theme_element : float | complex Value in points. A negative value creates the ticks inside the plot panel. A complex value (e.g. `3j`) creates ticks that span both in and out of the panel. """ def apply_ax(self, ax: Axes): super().apply_ax(ax) value: float | complex = self.properties["value"] if isinstance(value, (float, int)): tickdir = "in" if value < 0 else "out" else: tickdir = "inout" ax.xaxis.set_tick_params( which="minor", length=abs(value), tickdir=tickdir )
axis_ticks_length_minor_x
python
django__django
tests/queries/tests.py
{ "start": 138475, "end": 138875 }
class ____(TestCase): def test_evaluated_proxy_count(self): """ Generating the query string doesn't alter the query's state in irreversible ways. Refs #18248. """ ProxyCategory.objects.create() qs = ProxyCategory.objects.all() self.assertEqual(qs.count(), 1) str(qs.query) self.assertEqual(qs.count(), 1)
ProxyQueryCleanupTest
python
django__django
django/contrib/postgres/fields/ranges.py
{ "start": 9835, "end": 9981 }
class ____(PostgresOperatorLookup): lookup_name = "not_lt" postgres_operator = RangeOperators.NOT_LT @RangeField.register_lookup
NotLessThan
python
ray-project__ray
python/ray/util/state/common.py
{ "start": 28011, "end": 28416 }
class ____(StateSchema): severity: str = state_column(filterable=True) time: str = state_column(filterable=False) source_type: str = state_column(filterable=True) message: str = state_column(filterable=False) event_id: str = state_column(filterable=True) custom_fields: Optional[dict] = state_column(filterable=False, detail=True) @dataclass(init=not IS_PYDANTIC_2)
ClusterEventState
python
ray-project__ray
python/ray/serve/tests/unit/test_deployment_state.py
{ "start": 99003, "end": 138996 }
class ____: def scale( self, dsm: DeploymentStateManager, asm: AutoscalingStateManager, deployment_ids: List[DeploymentID], ): if not deployment_ids: return app_name = deployment_ids[0].app_name assert all(dep_id.app_name == app_name for dep_id in deployment_ids) deployment_to_target_num_replicas = { dep_id: dsm.get_deployment_details(dep_id).target_num_replicas for dep_id in deployment_ids } decisions = asm.get_decision_num_replicas( app_name, deployment_to_target_num_replicas ) for deployment_id, decision_num_replicas in decisions.items(): dsm.autoscale(deployment_id, decision_num_replicas) @pytest.mark.parametrize("target_capacity_direction", ["up", "down"]) def test_basic_autoscaling( self, mock_deployment_state_manager, target_capacity_direction ): """Test autoscaling up and down. Upscaling version: 1. Deploy deployment with autoscaling limits [0,6], initial_replicas=3, target=1. 2. It becomes healthy with 3 running replicas. 3. Set average request metrics to 2 (compare to target=1). 4. Deployment autoscales, 3 replicas starting, status=UPSCALING, trigger=AUTOSCALE. 5. It becomes healthy with 6 running replicas, status=HEALTHY, trigger=UPSCALE. """ # Create deployment state manager create_dsm, timer, _, asm = mock_deployment_state_manager dsm: DeploymentStateManager = create_dsm() asm: AutoscalingStateManager = asm # Deploy deployment with 3 replicas info, _ = deployment_info( autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 0, "max_replicas": 6, "initial_replicas": 3, "upscale_delay_s": 0, "downscale_delay_s": 0, "metrics_interval_s": 100, } ) dsm.deploy(TEST_DEPLOYMENT_ID, info) ds: DeploymentState = dsm._deployment_states[TEST_DEPLOYMENT_ID] # status=UPDATING, status_trigger=DEPLOY dsm.update() check_counts(ds, total=3, by_state=[(ReplicaState.STARTING, 3, None)]) assert ds.curr_status_info.status == DeploymentStatus.UPDATING assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_STARTED ) # Set replicas ready and check statuses for replica in ds._replicas.get(): replica._actor.set_ready() # status=HEALTHY, status_trigger=DEPLOY dsm.update() check_counts(ds, total=3, by_state=[(ReplicaState.RUNNING, 3, None)]) assert ds.curr_status_info.status == DeploymentStatus.HEALTHY assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_COMPLETED ) req_per_replica = 2 if target_capacity_direction == "up" else 0 replicas = ds._replicas.get() if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE: handle_metric_report = HandleMetricReport( deployment_id=TEST_DEPLOYMENT_ID, handle_id="random", actor_id="actor_id", handle_source=DeploymentHandleSource.UNKNOWN, queued_requests=[TimeStampedValue(timer.time() - 0.1, 0)], aggregated_queued_requests=0, aggregated_metrics={ RUNNING_REQUESTS_KEY: { replica._actor.replica_id: req_per_replica for replica in replicas } }, metrics={ RUNNING_REQUESTS_KEY: { replica._actor.replica_id: [ TimeStampedValue(timer.time() - 0.1, req_per_replica) ] for replica in replicas } }, timestamp=timer.time(), ) asm.record_request_metrics_for_handle(handle_metric_report) else: for replica in replicas: replica_metric_report = ReplicaMetricReport( replica_id=replica._actor.replica_id, aggregated_metrics={RUNNING_REQUESTS_KEY: req_per_replica}, metrics={ RUNNING_REQUESTS_KEY: [ TimeStampedValue(timer.time() - 0.1, req_per_replica) ] }, timestamp=timer.time(), ) asm.record_request_metrics_for_replica(replica_metric_report) self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) # status=UPSCALING/DOWNSCALING, status_trigger=AUTOSCALE dsm.update() if target_capacity_direction == "up": check_counts( ds, total=6, by_state=[ (ReplicaState.RUNNING, 3, None), (ReplicaState.STARTING, 3, None), ], ) assert ds.curr_status_info.status == DeploymentStatus.UPSCALING assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.AUTOSCALING ) # Advance timer by 60 seconds; this should exceed the slow startup # warning threshold. The message should be updated, but the status # should remain upscaling/autoscaling timer.advance(60) dsm.update() check_counts( ds, total=6, by_state=[ (ReplicaState.RUNNING, 3, None), (ReplicaState.STARTING, 3, None), ], ) assert ds.curr_status_info.status == DeploymentStatus.UPSCALING assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.AUTOSCALING ) assert "have taken more than" in ds.curr_status_info.message # Set replicas ready for replica in ds._replicas.get(): replica._actor.set_ready() else: # Due to two-stage downscaling one of the replicas will still be running check_counts( ds, total=3, by_state=[ (ReplicaState.STOPPING, 2, None), (ReplicaState.RUNNING, 1, None), ], ) # Trigger the second stage of downscaling self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) dsm.update() check_counts(ds, total=3, by_state=[(ReplicaState.STOPPING, 3, None)]) assert ds.curr_status_info.status == DeploymentStatus.DOWNSCALING assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.AUTOSCALING ) for replica in ds._replicas.get(): replica._actor.set_done_stopping() dsm.update() astate = asm._app_autoscaling_states[ TEST_DEPLOYMENT_ID.app_name ]._deployment_autoscaling_states[TEST_DEPLOYMENT_ID] assert len(astate._replica_metrics) == 0 # status=HEALTHY, status_trigger=UPSCALE/DOWNSCALE dsm.update() assert ds.curr_status_info.status == DeploymentStatus.HEALTHY assert ds.curr_status_info.status_trigger == ( DeploymentStatusTrigger.UPSCALE_COMPLETED if target_capacity_direction == "up" else DeploymentStatusTrigger.DOWNSCALE_COMPLETED ) # Make sure autoscaling state is removed when deployment is deleted dsm.delete_deployment(TEST_DEPLOYMENT_ID) dsm.update() for replica in ds._replicas.get(): replica._actor.set_done_stopping() dsm.update() assert TEST_DEPLOYMENT_ID not in dsm._deployment_states @pytest.mark.parametrize( "target_startup_status", [ ReplicaStartupStatus.PENDING_ALLOCATION, ReplicaStartupStatus.PENDING_INITIALIZATION, ], ) def test_downscaling_reclaiming_starting_replicas_first( self, target_startup_status, mock_deployment_state_manager, ): """This test asserts that when downscaling first any non-running replicas are scavenged, before stopping fully running replicas More context on the issue could be found in: https://github.com/ray-project/ray/issues/43034 """ # Create deployment state manager create_dsm, timer, _, asm = mock_deployment_state_manager dsm: DeploymentStateManager = create_dsm() asm: AutoscalingStateManager = asm # Deploy deployment with 3 replicas info, _ = deployment_info( autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 0, "max_replicas": 6, "initial_replicas": 3, "upscale_delay_s": 0, "downscale_delay_s": 0, "metrics_interval_s": 100, } ) dsm.deploy(TEST_DEPLOYMENT_ID, info) ds: DeploymentState = dsm._deployment_states[TEST_DEPLOYMENT_ID] # status=UPDATING, status_trigger=DEPLOY dsm.update() check_counts(ds, total=3, by_state=[(ReplicaState.STARTING, 3, None)]) assert ds.curr_status_info.status == DeploymentStatus.UPDATING assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_STARTED ) # Set replicas as SUCCESSFUL and check statuses for replica in ds._replicas.get(): replica._actor.set_ready() # status=HEALTHY, status_trigger=DEPLOY dsm.update() check_counts(ds, total=3, by_state=[(ReplicaState.RUNNING, 3, None)]) assert ds.curr_status_info.status == DeploymentStatus.HEALTHY assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_COMPLETED ) # Fetch all currently running replicas running_replicas = ds._replicas.get(states=[ReplicaState.RUNNING]) replicas = ds._replicas.get() if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE: handle_metric_report = HandleMetricReport( deployment_id=TEST_DEPLOYMENT_ID, handle_id="random", actor_id="actor_id", handle_source=DeploymentHandleSource.UNKNOWN, queued_requests=[TimeStampedValue(timer.time() - 0.1, 0)], aggregated_queued_requests=0, aggregated_metrics={ RUNNING_REQUESTS_KEY: { replica._actor.replica_id: 2 for replica in replicas } }, metrics={ RUNNING_REQUESTS_KEY: { replica._actor.replica_id: [ TimeStampedValue(timer.time() - 0.1, 2) ] for replica in replicas } }, timestamp=timer.time(), ) asm.record_request_metrics_for_handle(handle_metric_report) else: for replica in replicas: replica_metric_report = ReplicaMetricReport( replica_id=replica._actor.replica_id, aggregated_metrics={RUNNING_REQUESTS_KEY: 2}, metrics={ RUNNING_REQUESTS_KEY: [TimeStampedValue(timer.time() - 0.1, 2)] }, timestamp=timer.time(), ) asm.record_request_metrics_for_replica(replica_metric_report) # status=UPSCALING, status_trigger=AUTOSCALE self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) dsm.update() check_counts( ds, total=6, by_state=[ (ReplicaState.RUNNING, 3, None), (ReplicaState.STARTING, 3, None), ], ) assert ds.curr_status_info.status == DeploymentStatus.UPSCALING assert ds.curr_status_info.status_trigger == DeploymentStatusTrigger.AUTOSCALING # Set replicas as PENDING_INITIALIZATION: actors have been # successfully allocated, but replicas are still pending # successful initialization for replica in ds._replicas.get(): replica._actor.set_status(target_startup_status) # Advance timer by 60 seconds; this should exceed the slow startup # warning threshold. The message should be updated, but the status # should remain upscaling/autoscaling timer.advance(60) dsm.update() check_counts( ds, total=6, by_state=[ (ReplicaState.RUNNING, 3, None), (ReplicaState.STARTING, 3, None), ], ) assert ds.curr_status_info.status == DeploymentStatus.UPSCALING assert ds.curr_status_info.status_trigger == DeploymentStatusTrigger.AUTOSCALING if target_startup_status == ReplicaStartupStatus.PENDING_INITIALIZATION: expected_message = ( "Deployment 'test_deployment' in application 'test_app' has 3 replicas " f"that have taken more than {SLOW_STARTUP_WARNING_S}s to initialize.\n" "This may be caused by a slow __init__ or reconfigure method." ) elif target_startup_status == ReplicaStartupStatus.PENDING_ALLOCATION: expected_message = ( "Deployment 'test_deployment' in application 'test_app' " "has 3 replicas that have taken more than 30s to be scheduled. " "This may be due to waiting for the cluster to auto-scale or for " "a runtime environment to be installed. " "Resources required for each replica: " '{"CPU": 0.1}, ' "total resources available: " "{}. " "Use `ray status` for more details." ) else: raise RuntimeError(f"Got unexpected status: {target_startup_status}") assert expected_message == ds.curr_status_info.message # Now, trigger downscaling attempting to reclaim half (3) of the replicas replicas = ds._replicas.get(states=[ReplicaState.RUNNING]) if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE: handle_metric_report = HandleMetricReport( deployment_id=TEST_DEPLOYMENT_ID, handle_id="random", actor_id="actor_id", handle_source=DeploymentHandleSource.UNKNOWN, queued_requests=[TimeStampedValue(timer.time() - 0.1, 0)], aggregated_queued_requests=0, aggregated_metrics={ RUNNING_REQUESTS_KEY: { replica._actor.replica_id: 1 for replica in replicas } }, metrics={ RUNNING_REQUESTS_KEY: { replica._actor.replica_id: [ TimeStampedValue(timer.time() - 0.1, 1) ] for replica in replicas } }, timestamp=timer.time(), ) asm.record_request_metrics_for_handle(handle_metric_report) else: for replica in replicas: replica_metric_report = ReplicaMetricReport( replica_id=replica._actor.replica_id, aggregated_metrics={RUNNING_REQUESTS_KEY: 1}, metrics={ RUNNING_REQUESTS_KEY: [TimeStampedValue(timer.time() - 0.1, 1)] }, timestamp=timer.time(), ) asm.record_request_metrics_for_replica(replica_metric_report) # status=DOWNSCALING, status_trigger=AUTOSCALE self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) dsm.update() check_counts( ds, total=6, by_state=[ (ReplicaState.RUNNING, 3, None), (ReplicaState.STOPPING, 3, None), ], ) # Assert that no RUNNING replicas are being stopped assert running_replicas == ds._replicas.get(states=[ReplicaState.RUNNING]) assert ds.curr_status_info.status == DeploymentStatus.DOWNSCALING assert ds.curr_status_info.status_trigger == DeploymentStatusTrigger.AUTOSCALING for replica in ds._replicas.get(): replica._actor.set_done_stopping() # status=HEALTHY, status_trigger=UPSCALE/DOWNSCALE dsm.update() assert ds.curr_status_info.status == DeploymentStatus.HEALTHY assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.DOWNSCALE_COMPLETED ) def test_update_autoscaling_config(self, mock_deployment_state_manager): """Test updating the autoscaling config. 1. Deploy deployment with autoscaling limits [0,6] and initial replicas = 3. 2. It becomes healthy with 3 running replicas. 3. Update autoscaling config to limits [6,10]. 4. 3 new replicas should be STARTING, and deployment status should be UPDATING. 5. It becomes healthy with 6 running replicas. """ # Create deployment state manager create_dsm, timer, _, asm = mock_deployment_state_manager dsm: DeploymentStateManager = create_dsm() asm: AutoscalingStateManager = asm # Deploy deployment with 3 replicas info1, _ = deployment_info( autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 0, "max_replicas": 6, "initial_replicas": 3, "upscale_delay_s": 0, "downscale_delay_s": 0, }, version="1", ) dsm.deploy(TEST_DEPLOYMENT_ID, info1) ds: DeploymentState = dsm._deployment_states[TEST_DEPLOYMENT_ID] # Set replicas ready dsm.update() for replica in ds._replicas.get(): replica._actor.set_ready() # status=HEALTHY, status_trigger=DEPLOY dsm.update() check_counts(ds, total=3, by_state=[(ReplicaState.RUNNING, 3, None)]) assert ds.curr_status_info.status == DeploymentStatus.HEALTHY assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_COMPLETED ) # Num ongoing requests = 1, status should remain HEALTHY replicas = ds._replicas.get() if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE: handle_metric_report = HandleMetricReport( deployment_id=TEST_DEPLOYMENT_ID, handle_id="random", actor_id="actor_id", handle_source=DeploymentHandleSource.UNKNOWN, queued_requests=[TimeStampedValue(timer.time() - 0.1, 0)], aggregated_queued_requests=0, aggregated_metrics={ RUNNING_REQUESTS_KEY: { replica._actor.replica_id: 1 for replica in replicas } }, metrics={ RUNNING_REQUESTS_KEY: { replica._actor.replica_id: [ TimeStampedValue(timer.time() - 0.1, 1) ] for replica in replicas } }, timestamp=timer.time(), ) asm.record_request_metrics_for_handle(handle_metric_report) else: for replica in replicas: replica_metric_report = ReplicaMetricReport( replica_id=replica._actor.replica_id, aggregated_metrics={RUNNING_REQUESTS_KEY: 1}, metrics={ RUNNING_REQUESTS_KEY: [TimeStampedValue(timer.time() - 0.1, 1)] }, timestamp=timer.time(), ) asm.record_request_metrics_for_replica(replica_metric_report) check_counts(ds, total=3, by_state=[(ReplicaState.RUNNING, 3, None)]) assert ds.curr_status_info.status == DeploymentStatus.HEALTHY assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_COMPLETED ) # Update autoscaling config info2, _ = deployment_info( autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 6, "max_replicas": 10, "upscale_delay_s": 0, "downscale_delay_s": 0, }, version="1", ) dsm.deploy(TEST_DEPLOYMENT_ID, info2) # 3 new replicas should be starting, status should be UPDATING (not upscaling) self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) dsm.update() check_counts( ds, total=6, by_state=[ (ReplicaState.RUNNING, 3, None), (ReplicaState.STARTING, 3, None), ], ) assert ds.curr_status_info.status == DeploymentStatus.UPDATING assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_STARTED ) # Set replicas ready dsm.update() for replica in ds._replicas.get(): replica._actor.set_ready() dsm.update() check_counts(ds, total=6, by_state=[(ReplicaState.RUNNING, 6, None)]) assert ds.curr_status_info.status == DeploymentStatus.HEALTHY assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_COMPLETED ) def test_replicas_fail_during_initial_scale_from_zero( self, mock_deployment_state_manager ): """Test the following case: - An "erroneous" deployment (w/ autoscaling enabled) is deployed with initial replicas set to 0. Since no replicas are started, no errors have occurred from trying to start the replicas yet. - A request is sent, triggering an upscale. - The controller tries to start new replicas, but fails because of a constructor error. In this case, the deployment should transition to UNHEALTHY and stop retrying after a threshold. """ create_dsm, timer, _, asm = mock_deployment_state_manager dsm: DeploymentStateManager = create_dsm() asm: AutoscalingStateManager = asm # Deploy deployment with 1 initial replica info, _ = deployment_info( autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 0, "max_replicas": 2, "initial_replicas": 0, "upscale_delay_s": 0, "downscale_delay_s": 0, "metrics_interval_s": 100, } ) dsm.deploy(TEST_DEPLOYMENT_ID, info) ds: DeploymentState = dsm._deployment_states[TEST_DEPLOYMENT_ID] # Send request metrics to controller to make the deployment upscale handle_metric_report = HandleMetricReport( deployment_id=TEST_DEPLOYMENT_ID, handle_id="random", actor_id="actor_id", handle_source=DeploymentHandleSource.UNKNOWN, queued_requests=[TimeStampedValue(timer.time() - 0.1, 1)], aggregated_queued_requests=1, aggregated_metrics={}, metrics={}, timestamp=timer.time(), ) asm.record_request_metrics_for_handle(handle_metric_report) self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) # The controller should try to start a new replica. If that replica repeatedly # fails to start, the deployment should transition to UNHEALTHY and NOT retry # replicas anymore for i in range(10): dsm.update() if i < 3: check_counts(ds, total=1, by_state=[(ReplicaState.STARTING, 1, None)]) assert ds.curr_status_info.status == DeploymentStatus.UPSCALING assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.AUTOSCALING ) # Set replica failed to start replica = ds._replicas.get()[0] replica._actor.set_failed_to_start() dsm.update() if i < 2: check_counts( ds, total=2, by_state=[ (ReplicaState.STOPPING, 1, None), (ReplicaState.STARTING, 1, None), ], ) else: check_counts( ds, total=1, by_state=[(ReplicaState.STOPPING, 1, None)] ) # Set replica finished stopping replica._actor.set_done_stopping() else: check_counts(ds, total=0) assert ds.curr_status_info.status == DeploymentStatus.UNHEALTHY assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.REPLICA_STARTUP_FAILED ) def test_replicas_fail_during_subsequent_scale_from_zero( self, mock_deployment_state_manager ): """Test the following case: - An autoscaling deployment is deployed and it reaches HEALTHY with a non-zero number of replicas. - After a period of no traffic, the deployment scales down to 0. - New traffic is sent, triggering an upscale. - The controller tries to start new replicas, but for some reason some replicas fail to start because of transient errors In this case, the deployment should transition to UNHEALTHY and keep retrying, since at least one replica of this version has successfully started in the past, meaning we don't know if it is an unrecoverable user code error. """ create_dsm, timer, _, asm = mock_deployment_state_manager dsm: DeploymentStateManager = create_dsm() asm: AutoscalingStateManager = asm # Deploy deployment with 1 initial replica info, _ = deployment_info( autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 0, "max_replicas": 2, "initial_replicas": 1, "upscale_delay_s": 0, "downscale_delay_s": 0, "metrics_interval_s": 100, } ) dsm.deploy(TEST_DEPLOYMENT_ID, info) ds: DeploymentState = dsm._deployment_states[TEST_DEPLOYMENT_ID] # Expected: status=UPDATING, status_trigger=CONFIG_UPDATED_STARTED dsm.update() check_counts(ds, total=1, by_state=[(ReplicaState.STARTING, 1, None)]) assert ds.curr_status_info.status == DeploymentStatus.UPDATING assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_STARTED ) # Set replicas ready and check statuses # Expected: status=HEALTHY, status_trigger=CONFIG_UPDATED_COMPLETED ds._replicas.get()[0]._actor.set_ready() dsm.update() check_counts(ds, total=1, by_state=[(ReplicaState.RUNNING, 1, None)]) assert ds.curr_status_info.status == DeploymentStatus.HEALTHY assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_COMPLETED ) # There are no requests, so the deployment should be downscaled to zero. self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) dsm.update() check_counts(ds, total=1, by_state=[(ReplicaState.STOPPING, 1, None)]) ds._replicas.get()[0]._actor.set_done_stopping() dsm.update() check_counts(ds, total=0) # Send request metrics to controller to make the deployment upscale handle_metric_report = HandleMetricReport( deployment_id=TEST_DEPLOYMENT_ID, handle_id="random", actor_id="actor_id", handle_source=DeploymentHandleSource.UNKNOWN, queued_requests=[TimeStampedValue(timer.time() - 0.1, 1)], aggregated_queued_requests=1, aggregated_metrics={}, metrics={}, timestamp=timer.time(), ) asm.record_request_metrics_for_handle(handle_metric_report) self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) # The controller should try to start a new replica. If that replica repeatedly # fails to start, the deployment should transition to UNHEALTHY. Meanwhile # the controller should continue retrying after 3 times. for i in range(10): dsm.update() check_counts(ds, total=1, by_state=[(ReplicaState.STARTING, 1, None)]) if i < 3: assert ds.curr_status_info.status == DeploymentStatus.UPSCALING assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.AUTOSCALING ) else: assert ds.curr_status_info.status == DeploymentStatus.UNHEALTHY assert ( ds.curr_status_info.status_trigger == DeploymentStatusTrigger.REPLICA_STARTUP_FAILED ) # Set replica failed to start replica = ds._replicas.get()[0] replica._actor.set_failed_to_start() dsm.update() check_counts( ds, total=2, by_state=[ (ReplicaState.STOPPING, 1, None), (ReplicaState.STARTING, 1, None), ], ) # Set replica finished stopping replica._actor.set_done_stopping() @pytest.mark.skipif( not RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE, reason="Testing handle metrics behavior.", ) def test_handle_metrics_timeout(self, mock_deployment_state_manager): create_dsm, timer, _, asm = mock_deployment_state_manager dsm: DeploymentStateManager = create_dsm() asm: AutoscalingStateManager = asm # Deploy, start with 1 replica info, _ = deployment_info( autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 0, "max_replicas": 6, "initial_replicas": 1, "upscale_delay_s": 0, "downscale_delay_s": 0, } ) dsm.deploy(TEST_DEPLOYMENT_ID, info) ds: DeploymentState = dsm._deployment_states[TEST_DEPLOYMENT_ID] dsm.update() ds._replicas.get()[0]._actor.set_ready() asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) dsm.update() check_counts(ds, total=1, by_state=[(ReplicaState.RUNNING, 1, None)]) # Record 2 requests/replica -> trigger upscale handle_metric_report = HandleMetricReport( deployment_id=TEST_DEPLOYMENT_ID, handle_id="random", actor_id="actor_id", handle_source=DeploymentHandleSource.UNKNOWN, queued_requests=[TimeStampedValue(timer.time() - 0.1, 0)], aggregated_queued_requests=0, aggregated_metrics={ RUNNING_REQUESTS_KEY: {ds._replicas.get()[0]._actor.replica_id: 2} }, metrics={ RUNNING_REQUESTS_KEY: { ds._replicas.get()[0]._actor.replica_id: [ TimeStampedValue(timer.time() - 0.1, 2) ] } }, timestamp=timer.time(), ) asm.record_request_metrics_for_handle(handle_metric_report) asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) dsm.update() check_counts( ds, total=2, by_state=[ (ReplicaState.RUNNING, 1, None), (ReplicaState.STARTING, 1, None), ], ) assert asm.get_total_num_requests_for_deployment(TEST_DEPLOYMENT_ID) == 2 ds._replicas.get([ReplicaState.STARTING])[0]._actor.set_ready() asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) dsm.update() check_counts(ds, total=2, by_state=[(ReplicaState.RUNNING, 2, None)]) assert asm.get_total_num_requests_for_deployment(TEST_DEPLOYMENT_ID) == 2 # Simulate handle was on an actor that died. 10 seconds later # the handle fails to push metrics timer.advance(10) asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) dsm.update() check_counts(ds, total=2, by_state=[(ReplicaState.RUNNING, 2, None)]) assert asm.get_total_num_requests_for_deployment(TEST_DEPLOYMENT_ID) == 2 # Another 10 seconds later handle still fails to push metrics. At # this point the data from the handle should be invalidated. As a # result, the replicas should scale back down to 0. timer.advance(10) asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) # The first update will trigger the first stage of downscaling to 1 self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) dsm.update() check_counts( ds, total=2, by_state=[ (ReplicaState.STOPPING, 1, None), (ReplicaState.RUNNING, 1, None), ], ) # The second update will trigger the second stage of downscaling from 1 to 0 self.scale(dsm, asm, [TEST_DEPLOYMENT_ID]) dsm.update() check_counts(ds, total=2, by_state=[(ReplicaState.STOPPING, 2, None)]) assert asm.get_total_num_requests_for_deployment(TEST_DEPLOYMENT_ID) == 0 @pytest.mark.skipif( not RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE, reason="Testing handle metrics behavior.", ) def test_handle_metrics_on_dead_serve_actor(self, mock_deployment_state_manager): """Metrics for handles on dead serve actors should be dropped.""" create_dsm, timer, _, asm = mock_deployment_state_manager dsm: DeploymentStateManager = create_dsm() asm: AutoscalingStateManager = asm d_id1 = DeploymentID("d1", "app") d_id2 = DeploymentID("d2", "app") # Deploy, start with 1 replica info1, _ = deployment_info( autoscaling_config={ "target_ongoing_requests": 1, "min_replicas": 0, "max_replicas": 6, "initial_replicas": 1, "upscale_delay_s": 0, "downscale_delay_s": 0, }, ) info2, _ = deployment_info(health_check_period_s=0.1) dsm.deploy(d_id1, info1) dsm.deploy(d_id2, info2) ds1: DeploymentState = dsm._deployment_states[d_id1] ds2: DeploymentState = dsm._deployment_states[d_id2] # One replica each asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) dsm.update() ds1._replicas.get()[0]._actor.set_ready() ds2._replicas.get()[0]._actor.set_ready() ds2._replicas.get()[0]._actor.set_actor_id("d2_replica_actor_id") asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) dsm.update() check_counts(ds1, total=1, by_state=[(ReplicaState.RUNNING, 1, None)]) check_counts(ds2, total=1, by_state=[(ReplicaState.RUNNING, 1, None)]) # Record 2 requests/replica (sent from d2 replica) -> trigger upscale handle_metric_report = HandleMetricReport( deployment_id=d_id1, handle_id="random", actor_id="d2_replica_actor_id", handle_source=DeploymentHandleSource.REPLICA, queued_requests=[TimeStampedValue(timer.time() - 0.1, 0)], aggregated_queued_requests=0, aggregated_metrics={ RUNNING_REQUESTS_KEY: {ds1._replicas.get()[0]._actor.replica_id: 2} }, metrics={ RUNNING_REQUESTS_KEY: { ds1._replicas.get()[0]._actor.replica_id: [ TimeStampedValue(timer.time() - 0.1, 2) ] } }, timestamp=timer.time(), ) asm.record_request_metrics_for_handle(handle_metric_report) asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) self.scale(dsm, asm, [d_id1, d_id2]) dsm.update() check_counts( ds1, total=2, by_state=[ (ReplicaState.RUNNING, 1, None), (ReplicaState.STARTING, 1, None), ], ) assert asm.get_total_num_requests_for_deployment(d_id1) == 2 ds1._replicas.get([ReplicaState.STARTING])[0]._actor.set_ready() asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) self.scale(dsm, asm, [d_id1, d_id2]) dsm.update() check_counts(ds1, total=2, by_state=[(ReplicaState.RUNNING, 2, None)]) assert asm.get_total_num_requests_for_deployment(d_id1) == 2 # d2 replica died ds2._replicas.get()[0]._actor.set_unhealthy() asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) self.scale(dsm, asm, [d_id1, d_id2]) dsm.update() check_counts( ds2, total=2, by_state=[ (ReplicaState.STARTING, 1, None), (ReplicaState.STOPPING, 1, None), ], ) ds2._replicas.get(states=[ReplicaState.STOPPING])[0]._actor.set_done_stopping() asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) self.scale(dsm, asm, [d_id1, d_id2]) dsm.update() check_counts(ds2, total=1, by_state=[(ReplicaState.STARTING, 1, None)]) # Now that the d2 replica is dead, its metrics should be dropped. # Consequently d1 should scale down to 0 replicas asm.drop_stale_handle_metrics(dsm.get_alive_replica_actor_ids()) self.scale(dsm, asm, [d_id1, d_id2]) dsm.update() # Due to two-stage downscaling one of the replicas will still be running check_counts( ds1, total=2, by_state=[ (ReplicaState.STOPPING, 1, None), (ReplicaState.RUNNING, 1, None), ], ) # Trigger the second stage of downscaling self.scale(dsm, asm, [d_id1, d_id2]) dsm.update() check_counts(ds1, total=2, by_state=[(ReplicaState.STOPPING, 2, None)])
TestAutoscaling
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 71874, "end": 74656 }
class ____(VariableTracker): """self.value is a compile-time constant, but not a literal""" _error_prefix = "ConstantLikeVariable" try: from numpy import ( dtype as np_dtype, floating as np_floating, generic as np_generic, ) except ImportError: np_floating = type("invalid_type", (), {}) np_dtype = type("invalid_type", (), {}) def __init__(self, value, **kwargs) -> None: super().__init__(**kwargs) self.value = value def as_python_constant(self): return self.value def call_method( self, tx: "InstructionTranslator", name, args: list[VariableTracker], kwargs: dict[str, VariableTracker], ) -> VariableTracker: try: # we only support constant propagation for methods cargs = [x.as_python_constant() for x in args] ckwargs = {k: v.as_python_constant() for k, v in kwargs.items()} except NotImplementedError: unimplemented( gb_type="constant-like method call with non-constant args", context=f"{self._error_prefix}.{name}(*{args}, **{kwargs})", explanation=f"Attempted to call {self._error_prefix}.{name} with non-constant args.", hints=[ "Ensure that the args to the method call are constant (int, str, etc.).", ], ) result = getattr(self.value, name)(*cargs, **ckwargs) if variables.ConstantVariable.is_literal(result): return variables.ConstantVariable.create(result) if isinstance(result, re.Match): return ConstantRegexMatchVariable(result) unimplemented( gb_type="constant-like method call with unsupported return type", context=f"{self._error_prefix}.{name}(*{args}, **{kwargs}) returned {result}", explanation=f"Attempted to call {self._error_prefix}.{name}, got unsupported return value {result}.", hints=[ *graph_break_hints.SUPPORTABLE, ], ) def var_getattr(self, tx: "InstructionTranslator", name: str) -> VariableTracker: result = getattr(self.value, name) if isinstance(result, self.np_floating): result = float(result) if isinstance(result, self.np_dtype): return NumpyDTypeVariable(result) if isinstance(result, type) and issubclass(result, self.np_generic): # things like x.dtype.type return NumpyVariable(result) if variables.ConstantVariable.is_literal(result): return variables.ConstantVariable.create(result) return GetAttrVariable(self, name)
ConstantLikeVariable
python
explosion__spaCy
spacy/lang/th/__init__.py
{ "start": 1090, "end": 1237 }
class ____(BaseDefaults): config = load_config_from_str(DEFAULT_CONFIG) lex_attr_getters = LEX_ATTRS stop_words = STOP_WORDS
ThaiDefaults
python
great-expectations__great_expectations
great_expectations/expectations/core/expect_column_values_to_not_match_regex_list.py
{ "start": 2193, "end": 15383 }
class ____(ColumnMapExpectation): __doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION} ExpectColumnValuesToNotMatchRegexList is a \ Column Map Expectation. Column Map Expectations are one of the most common types of Expectation. They are evaluated for a single column and ask a yes/no question for every row in that column. Based on the result, they then calculate the percentage of rows that gave a positive answer. If the percentage is high enough, the Expectation considers that data valid. Args: column (str): \ {COLUMN_DESCRIPTION} regex_list (list): \ {REGEX_LIST_DESCRIPTION} Other Parameters: mostly (None or a float between 0 and 1): \ {MOSTLY_DESCRIPTION} \ For more detail, see [mostly](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#mostly). result_format (str or None): \ Which output mode to use: BOOLEAN_ONLY, BASIC, COMPLETE, or SUMMARY. \ For more detail, see [result_format](https://docs.greatexpectations.io/docs/reference/expectations/result_format). catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see [catch_exceptions](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#catch_exceptions). meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without \ modification. For more detail, see [meta](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#meta). severity (str or None): \ {FAILURE_SEVERITY_DESCRIPTION} \ For more detail, see [failure severity](https://docs.greatexpectations.io/docs/cloud/expectations/expectations_overview/#failure-severity). Returns: An [ExpectationSuiteValidationResult](https://docs.greatexpectations.io/docs/terms/validation_result) Exact fields vary depending on the values passed to result_format, catch_exceptions, and meta. See Also: [ExpectColumnValuesToMatchRegex](https://greatexpectations.io/expectations/expect_column_values_to_match_regex) [ExpectColumnValuesToMatchRegexList](https://greatexpectations.io/expectations/expect_column_values_to_match_regex_list) [ExpectColumnValuesToNotMatchRegex](https://greatexpectations.io/expectations/expect_column_values_to_not_match_regex) [ExpectColumnValuesToMatchLikePattern](https://greatexpectations.io/expectations/expect_column_values_to_match_like_pattern) [ExpectColumnValuesToMatchLikePatternList](https://greatexpectations.io/expectations/expect_column_values_to_match_like_pattern_list) [ExpectColumnValuesToNotMatchLikePattern](https://greatexpectations.io/expectations/expect_column_values_to_not_match_like_pattern) [ExpectColumnValuesToNotMatchLikePatternList](https://greatexpectations.io/expectations/expect_column_values_to_not_match_like_pattern_list) Supported Data Sources: [{SUPPORTED_DATA_SOURCES[0]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[1]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[2]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[3]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[4]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[5]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[6]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[7]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[8]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[9]}](https://docs.greatexpectations.io/docs/application_integration_support/) Data Quality Issues: {DATA_QUALITY_ISSUES[0]} Example Data: test test2 0 "aaa" "bcc" 1 "abb" "bdd" 2 "acc" "abc" Code Examples: Passing Case: Input: ExpectColumnValuesToNotMatchRegexList( column="test", regex_list=["^b.*", "^c.*"], ) Output: {{ "exception_info": {{ "raised_exception": false, "exception_traceback": null, "exception_message": null }}, "result": {{ "element_count": 3, "unexpected_count": 0, "unexpected_percent": 0.0, "partial_unexpected_list": [], "missing_count": 0, "missing_percent": 0.0, "unexpected_percent_total": 0.0, "unexpected_percent_nonmissing": 0.0 }}, "meta": {{}}, "success": true }} Failing Case: Input: ExpectColumnValuesToNotMatchRegexList( column="test2", regex_list=["^b.*", "^c.*"], ) Output: {{ "exception_info": {{ "raised_exception": false, "exception_traceback": null, "exception_message": null }}, "result": {{ "element_count": 3, "unexpected_count": 1, "unexpected_percent": 33.33333333333333, "partial_unexpected_list": [ "abc", ], "missing_count": 0, "missing_percent": 0.0, "unexpected_percent_total": 33.33333333333333, "unexpected_percent_nonmissing": 33.33333333333333 }}, "meta": {{}}, "success": false }} """ # noqa: E501 # FIXME CoP regex_list: Union[List[str], SuiteParameterDict] = pydantic.Field( description=REGEX_LIST_DESCRIPTION ) library_metadata: ClassVar[Dict[str, Union[str, list, bool]]] = { "maturity": "production", "tags": ["core expectation", "column map expectation"], "contributors": [ "@great_expectations", ], "requirements": [], "has_full_test_suite": True, "manually_reviewed_code": True, } _library_metadata = library_metadata map_metric = "column_values.not_match_regex_list" success_keys = ( "regex_list", "mostly", ) args_keys = ( "column", "regex_list", ) class Config: title = "Expect column values to not match regex list" @staticmethod def schema_extra( schema: Dict[str, Any], model: Type[ExpectColumnValuesToNotMatchRegexList] ) -> None: ColumnMapExpectation.Config.schema_extra(schema, model) schema["properties"]["metadata"]["properties"].update( { "data_quality_issues": { "title": "Data Quality Issues", "type": "array", "const": DATA_QUALITY_ISSUES, }, "library_metadata": { "title": "Library Metadata", "type": "object", "const": model._library_metadata, }, "short_description": { "title": "Short Description", "type": "string", "const": EXPECTATION_SHORT_DESCRIPTION, }, "supported_data_sources": { "title": "Supported Data Sources", "type": "array", "const": SUPPORTED_DATA_SOURCES, }, } ) @pydantic.validator("regex_list") def _validate_regex_list( cls, regex_list: list[str] | SuiteParameterDict ) -> list[str] | SuiteParameterDict: if not regex_list: raise ValueError("regex_list must not be empty") # noqa: TRY003 # Error message gets swallowed by Pydantic return regex_list @classmethod def _prescriptive_template( cls, renderer_configuration: RendererConfiguration, ) -> RendererConfiguration: add_param_args: AddParamArgs = ( ("column", RendererValueType.STRING), ("regex_list", RendererValueType.ARRAY), ("mostly", RendererValueType.NUMBER), ) for name, param_type in add_param_args: renderer_configuration.add_param(name=name, param_type=param_type) params = renderer_configuration.params if not params.regex_list or not params.regex_list.value: values_string = "[ ]" else: array_param_name = "regex_list" param_prefix = "v__" renderer_configuration = cls._add_array_params( array_param_name=array_param_name, param_prefix=param_prefix, renderer_configuration=renderer_configuration, ) values_string: str = cls._get_array_string( array_param_name=array_param_name, param_prefix=param_prefix, renderer_configuration=renderer_configuration, ) template_str = ( "values must not match any of the following regular expressions: " + values_string ) if params.mostly and params.mostly.value < 1.0: renderer_configuration = cls._add_mostly_pct_param( renderer_configuration=renderer_configuration ) template_str += ", at least $mostly_pct % of the time." else: template_str += "." if renderer_configuration.include_column_name: template_str = f"$column {template_str}" renderer_configuration.template_str = template_str return renderer_configuration @classmethod @renderer(renderer_type=LegacyRendererType.PRESCRIPTIVE) @render_suite_parameter_string def _prescriptive_renderer( cls, configuration: Optional[ExpectationConfiguration] = None, result: Optional[ExpectationValidationResult] = None, runtime_configuration: Optional[dict] = None, **kwargs, ): runtime_configuration = runtime_configuration or {} include_column_name = runtime_configuration.get("include_column_name") is not False styling = runtime_configuration.get("styling") params = substitute_none_for_missing( configuration.kwargs, ["column", "regex_list", "mostly", "row_condition", "condition_parser"], ) if not params.get("regex_list") or len(params.get("regex_list")) == 0: values_string = "[ ]" else: for i, v in enumerate(params["regex_list"]): params[f"v__{i!s}"] = v values_string = " ".join([f"$v__{i!s}" for i, v in enumerate(params["regex_list"])]) template_str = ( "values must not match any of the following regular expressions: " + values_string ) if params["mostly"] is not None: if isinstance(params["mostly"], (int, float)) and params["mostly"] < 1.0: params["mostly_pct"] = num_to_str(params["mostly"] * 100, no_scientific=True) # params["mostly_pct"] = "{:.14f}".format(params["mostly"]*100).rstrip("0").rstrip(".") # noqa: E501 # FIXME CoP template_str += ", at least $mostly_pct % of the time." else: template_str += "." if include_column_name: template_str = f"$column {template_str}" if params["row_condition"] is not None: conditional_template_str = parse_row_condition_string(params["row_condition"]) template_str, styling = _style_row_condition( conditional_template_str, template_str, params, styling, ) return [ RenderedStringTemplateContent( **{ "content_block_type": "string_template", "string_template": { "template": template_str, "params": params, "styling": styling, }, } ) ]
ExpectColumnValuesToNotMatchRegexList
python
pytorch__pytorch
test/distributed/test_c10d_common.py
{ "start": 11158, "end": 11398 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.embedding = nn.EmbeddingBag(10, 10, sparse=True) def forward(self, x): return F.softmax(self.embedding(x), dim=1)
SparseGradientModule
python
huggingface__transformers
tests/models/ijepa/test_modeling_ijepa.py
{ "start": 1459, "end": 6046 }
class ____: def __init__( self, parent, batch_size=13, image_size=30, patch_size=2, num_channels=3, is_training=True, use_labels=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, type_sequence_label_size=10, initializer_range=0.02, scope=None, encoder_stride=2, mask_ratio=0.5, attn_implementation="eager", ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.is_training = is_training self.use_labels = use_labels self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.scope = scope self.encoder_stride = encoder_stride self.attn_implementation = attn_implementation # in IJEPA, the seq length equals the number of patches (we don't add 1 for the [CLS] token) num_patches = (image_size // patch_size) ** 2 self.seq_length = num_patches self.mask_ratio = mask_ratio self.num_masks = int(mask_ratio * self.seq_length) self.mask_length = num_patches def prepare_config_and_inputs(self): pixel_values = floats_tensor( [ self.batch_size, self.num_channels, self.image_size, self.image_size, ] ) labels = None if self.use_labels: labels = ids_tensor([self.batch_size], self.type_sequence_label_size) config = self.get_config() return config, pixel_values, labels def get_config(self): return IJepaConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, is_decoder=False, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, attn_implementation=self.attn_implementation, ) def create_and_check_model(self, config, pixel_values, labels): model = IJepaModel(config=config) model.to(torch_device) model.eval() result = model(pixel_values) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size), ) def create_and_check_for_image_classification(self, config, pixel_values, labels): config.num_labels = self.type_sequence_label_size model = IJepaForImageClassification(config) model.to(torch_device) model.eval() result = model(pixel_values, labels=labels) self.parent.assertEqual( result.logits.shape, (self.batch_size, self.type_sequence_label_size), ) # test greyscale images config.num_channels = 1 model = IJepaForImageClassification(config) model.to(torch_device) model.eval() pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) result = model(pixel_values) self.parent.assertEqual( result.logits.shape, (self.batch_size, self.type_sequence_label_size), ) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, pixel_values, labels, ) = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch
IJepaModelTester
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 10790, "end": 11350 }
class ____: def setup_method(self): def initial_value(): return 123 class TestSerializer(serializers.Serializer): initial_field = serializers.IntegerField(initial=initial_value) self.serializer = TestSerializer() def test_initial_should_accept_callable(self): """ Follows the default ``Field.initial`` behavior where they accept a callable to produce the initial value""" assert self.serializer.data == { 'initial_field': 123, }
TestInitialWithCallable
python
numba__numba
numba/core/datamodel/testing.py
{ "start": 3125, "end": 4140 }
class ____(object): """Test as_data() and from_data() """ # XXX test load_from_data_pointer() as well def test_as_data(self): fnty = ir.FunctionType(ir.VoidType(), []) function = ir.Function(self.module, fnty, name="test_as_data") builder = ir.IRBuilder() builder.position_at_end(function.append_basic_block()) undef_value = ir.Constant(self.datamodel.get_value_type(), None) data = self.datamodel.as_data(builder, undef_value) self.assertIsNot(data, NotImplemented, "as_data returned NotImplemented") self.assertEqual(data.type, self.datamodel.get_data_type()) rev_value = self.datamodel.from_data(builder, data) self.assertEqual(rev_value.type, self.datamodel.get_value_type()) builder.ret_void() # end function # Ensure valid LLVM generation materialized = ll.parse_assembly(str(self.module)) str(materialized)
SupportAsDataMixin
python
huggingface__transformers
tests/models/metaclip_2/test_modeling_metaclip_2.py
{ "start": 20536, "end": 23965 }
class ____(MetaClip2ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (MetaClip2Model,) if is_torch_available() else () pipeline_model_mapping = ( {"feature-extraction": MetaClip2Model, "image-feature-extraction": MetaClip2VisionModel} if is_torch_available() else {} ) additional_model_inputs = ["pixel_values"] test_resize_embeddings = False test_attention_outputs = False _is_composite = True def setUp(self): self.model_tester = MetaClip2ModelTester(self) common_properties = ["projection_dim", "logit_scale_init_value"] self.config_tester = ConfigTester( self, config_class=MetaClip2Config, has_text_modality=False, common_properties=common_properties ) def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="Hidden_states is tested in individual model tests") def test_hidden_states_output(self): pass @unittest.skip(reason="Inputs_embeds is tested in individual model tests") def test_inputs_embeds(self): pass @unittest.skip(reason="Retain_grad is tested in individual model tests") def test_retain_grad_hidden_states_attentions(self): pass @unittest.skip(reason="MetaClip2Model does not have input/output embeddings") def test_model_get_set_embeddings(self): pass def test_load_vision_text_config(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() # Save MetaClip2Config and check if we can load MetaClip2VisionConfig from it with tempfile.TemporaryDirectory() as tmp_dir_name: config.save_pretrained(tmp_dir_name) vision_config = MetaClip2VisionConfig.from_pretrained(tmp_dir_name) self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict()) # Save MetaClip2Config and check if we can load MetaClip2TextConfig from it with tempfile.TemporaryDirectory() as tmp_dir_name: config.save_pretrained(tmp_dir_name) text_config = MetaClip2TextConfig.from_pretrained(tmp_dir_name) self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict()) @slow def test_model_from_pretrained(self): model_name = "facebook/metaclip-2-worldwide-huge-quickgelu" model = MetaClip2Model.from_pretrained(model_name) self.assertIsNotNone(model) @parameterized.expand(TEST_EAGER_MATCHES_SDPA_INFERENCE_PARAMETERIZATION) @slow @is_flaky() def test_eager_matches_sdpa_inference(self, *args): # adding only flaky decorator here and call the parent test method return getattr(ModelTesterMixin, self._testMethodName)(self) def test_sdpa_can_dispatch_composite_models(self): super().test_sdpa_can_dispatch_composite_models() def test_sdpa_can_dispatch_on_flash(self): self.skipTest( reason="MetaClip2 text tower has two attention masks: `causal_attention_mask` and `attention_mask`" ) def test_sdpa_can_compile_dynamic(self): self.skipTest(reason="MetaClip2 model can't be compiled dynamic, error in metaclip_2_loss`")
MetaClip2ModelTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/feature_store.py
{ "start": 8903, "end": 12539 }
class ____(GoogleCloudBaseOperator, OperationHelper): """ Get Feature Online store instance. This method initiates VertexAI Feature Online Store creation request. Feature Online Store aims to serve and manage features data as a part of VertexAI MLOps. :param project_id: Required. The ID of the Google Cloud project that contains the feature store. This is used to identify which project's resources to interact with. :param location: Required. The location of the feature store (e.g., 'us-central1', 'us-east1'). This specifies the Google Cloud region where the feature store resources are located. :param feature_online_store_id: Required. The ID of the online feature store that contains the feature view to be synchronized. This store serves as the online serving layer. :param gcp_conn_id: The connection ID to use for connecting to Google Cloud Platform. Defaults to 'google_cloud_default'. :param impersonation_chain: Optional service account to impersonate using short-term credentials. Can be either a single account or a chain of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account. """ template_fields: Sequence[str] = ( "project_id", "location", "feature_online_store_id", ) def __init__( self, *, project_id: str, location: str, feature_online_store_id: str, timeout: float | _MethodDefault = DEFAULT, retry: Retry | _MethodDefault | None = DEFAULT, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.project_id = project_id self.location = location self.feature_online_store_id = feature_online_store_id self.timeout = timeout self.retry = retry self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context) -> dict[str, Any]: """Execute the get feature view sync operation.""" hook = FeatureStoreHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) self.log.info("Get the Feature Online Store id: %s...", self.feature_online_store_id) try: result = hook.get_feature_online_store( project_id=self.project_id, location=self.location, feature_online_store_id=self.feature_online_store_id, timeout=self.timeout, retry=self.retry, metadata=self.metadata, ) except GoogleAPICallError as ex: exc_msg = f"Google API error getting {self.feature_online_store_id} Feature Online Store instance" raise AirflowException(exc_msg) from ex result = type(result).to_dict(result) self.log.info("The Feature Online Store has been retrieved: %s", self.feature_online_store_id) return result
GetFeatureOnlineStoreOperator
python
getsentry__sentry
tests/sentry/integrations/slack/threads/activity_notifications/test_external_issue_created_activity.py
{ "start": 926, "end": 1752 }
class ____(BaseTestCase): def test_when_link_key_is_not_in_map(self) -> None: self.activity.data = {} create_issue_activity = _ExternalIssueCreatedActivity(self.activity) ret = create_issue_activity.get_link() assert ret == "" def test_when_link_key_is_empty(self) -> None: self.activity.data = {"location": None} create_issue_activity = _ExternalIssueCreatedActivity(self.activity) ret = create_issue_activity.get_link() assert ret == "" def test_returns_correct_value(self) -> None: link_value = "www.example.com" self.activity.data = {"location": link_value} create_issue_activity = _ExternalIssueCreatedActivity(self.activity) ret = create_issue_activity.get_link() assert ret == link_value
TestGetLink
python
scipy__scipy
benchmarks/benchmarks/optimize_linprog.py
{ "start": 4912, "end": 5488 }
class ____(Benchmark): params = [ methods, range(20, 100, 20), range(20, 100, 20) ] param_names = ['method', 'm', 'n'] def setup(self, meth, m, n): self.A, self.b, self.c = lpgen_2d(m, n) def time_lpgen(self, meth, m, n): method, options = meth with warnings.catch_warnings(): warnings.filterwarnings( "ignore", "scipy.linalg.solve\nIll-conditioned", RuntimeWarning) linprog(c=self.c, A_ub=self.A, b_ub=self.b, method=method, options=options)
LpGen
python
google__jax
jax/experimental/mosaic/gpu/utils.py
{ "start": 11121, "end": 13784 }
class ____: op: scf.ForOp results: tuple[Any, ...] @property def result(self): if len(self.results) != 1: raise ValueError return self.results[0] def fori(bound, carrys): unwrap = False if not isinstance(carrys, (list, tuple)): carrys = [carrys] unwrap = True flat_carrys, carry_treedef = jax.tree.flatten(carrys) def wrapper(f): c0 = arith.constant(bound.type, 0) c1 = arith.constant(bound.type, 1) for_op = scf.ForOp(c0, bound, c1, flat_carrys) with ir.InsertionPoint(for_op.body): i = for_op.induction_variable inner_carrys = jax.tree.unflatten(carry_treedef, for_op.inner_iter_args) if unwrap: [inner_carrys] = inner_carrys new_carrys = f(i, inner_carrys) if unwrap: new_carrys = [new_carrys] new_flat_carrys, new_carry_treedef = jax.tree.flatten(new_carrys) if new_carry_treedef != carry_treedef: raise ValueError(new_carry_treedef, carry_treedef) scf.YieldOp(new_flat_carrys) final_flat_carrys = for_op.results return ForResult( for_op, jax.tree.unflatten(carry_treedef, final_flat_carrys) ) return wrapper @contextlib.contextmanager def when(cond): with ir.InsertionPoint(scf.IfOp(cond).then_block): yield scf.yield_([]) def _3d_to_1d_idx(dim_idx_fn, dim_size_fn): i32 = ir.IntegerType.get_signless(32) as_i32 = lambda x: arith.index_cast(i32, x) idx = as_i32(dim_idx_fn(gpu.Dimension.x)) stride = as_i32(dim_size_fn(gpu.Dimension.x)) for dim in (gpu.Dimension.y, gpu.Dimension.z): idx = arith.addi(idx, arith.muli(as_i32(dim_idx_fn(dim)), stride)) stride = arith.muli(stride, as_i32(dim_size_fn(dim))) return idx thread_idx = functools.partial(_3d_to_1d_idx, gpu.thread_id, gpu.block_dim) block_idx = functools.partial(_3d_to_1d_idx, gpu.block_id, gpu.grid_dim) def _warp_bcast(val, lane_idx=0): i32 = ir.IntegerType.get_signless(32) mask = c(0xFFFFFFFF, i32) return nvvm.shfl_sync( val.type, mask, val, c(lane_idx, i32), c(0x1F, i32), nvvm.ShflKind.idx ) def warp_idx(sync=True): i32 = ir.IntegerType.get_signless(32) warp_idx = arith.shrui(thread_idx(), c(5, i32)) # Performing a warp broadcast improves performance as compiler understands # that the value is uniform across the warp. return _warp_bcast(warp_idx) if sync else warp_idx def warpgroup_idx(sync=True): i32 = ir.IntegerType.get_signless(32) wg_idx = arith.shrui(thread_idx(), c(7, i32)) # Performing a warp broadcast improves performance as compiler understands # that the value is uniform across the warp. return _warp_bcast(wg_idx) if sync else wg_idx
ForResult
python
Netflix__metaflow
test/core/tests/switch_basic.py
{ "start": 63, "end": 940 }
class ____(MetaflowTest): """ Tests a basic switch with multiple branches. """ PRIORITY = 2 ONLY_GRAPHS = ["simple_switch"] @steps(0, ["start"], required=True) def step_start(self): self.condition = "case2" @steps(0, ["switch-simple"], required=True) def step_switch_simple(self): pass @steps(0, ["path-a"], required=True) def step_a(self): self.result = "Path A taken" @steps(0, ["path-b"], required=True) def step_b(self): self.result = "Path B taken" @steps(0, ["path-c"], required=True) def step_c(self): self.result = "Path C taken" @steps(1, ["end"], required=True) def step_end(self): assert_equals("Path B taken", self.result) def check_results(self, flow, checker): checker.assert_artifact("b", "result", "Path B taken")
BasicSwitchTest
python
dagster-io__dagster
python_modules/libraries/dagster-azure/dagster_azure/fakes/fake_adls2_resource.py
{ "start": 1342, "end": 1975 }
class ____: def __init__(self, client): self.client = client self.id = None # client needs a ref to self to check if a given lease is valid self.client._lease = self # noqa: SLF001 def acquire(self, lease_duration=-1): if self.id is None: self.id = random.randint(0, 2**9) else: raise Exception("Lease already held") def release(self): self.id = None def is_valid(self, lease): if self.id is None: # no lease is held so any operation is valid return True return lease == self.id
FakeLeaseClient
python
scipy__scipy
scipy/fft/_pocketfft/tests/test_basic.py
{ "start": 8185, "end": 8367 }
class ____(_TestIFFTBase): def setup_method(self): self.cdt = np.complex128 self.rdt = np.float64 self.rtol = 1e-10 self.atol = 1e-10
TestDoubleIFFT
python
pypa__warehouse
tests/unit/legacy/api/xmlrpc/test_cache.py
{ "start": 6536, "end": 9733 }
class ____: def test_redis_lru(self, mockredis): redis_lru = RedisLru(mockredis) expected = func_test(0, 1, kwarg0=2, kwarg1=3) assert expected == redis_lru.fetch( func_test, [0, 1], {"kwarg0": 2, "kwarg1": 3}, None, None, None ) assert expected == redis_lru.fetch( func_test, [0, 1], {"kwarg0": 2, "kwarg1": 3}, None, None, None ) def test_redis_custom_metrics(self, metrics, mockredis): redis_lru = RedisLru(mockredis, metric_reporter=metrics) expected = func_test(0, 1, kwarg0=2, kwarg1=3) assert expected == redis_lru.fetch( func_test, [0, 1], {"kwarg0": 2, "kwarg1": 3}, None, None, None ) assert expected == redis_lru.fetch( func_test, [0, 1], {"kwarg0": 2, "kwarg1": 3}, None, None, None ) assert metrics.increment.calls == [ pretend.call("lru.cache.miss"), pretend.call("lru.cache.hit"), ] def test_redis_purge(self, metrics, mockredis): redis_lru = RedisLru(mockredis, metric_reporter=metrics) expected = func_test(0, 1, kwarg0=2, kwarg1=3) assert expected == redis_lru.fetch( func_test, [0, 1], {"kwarg0": 2, "kwarg1": 3}, None, "test", None ) assert expected == redis_lru.fetch( func_test, [0, 1], {"kwarg0": 2, "kwarg1": 3}, None, "test", None ) redis_lru.purge("test") assert expected == redis_lru.fetch( func_test, [0, 1], {"kwarg0": 2, "kwarg1": 3}, None, "test", None ) assert expected == redis_lru.fetch( func_test, [0, 1], {"kwarg0": 2, "kwarg1": 3}, None, "test", None ) assert metrics.increment.calls == [ pretend.call("lru.cache.miss"), pretend.call("lru.cache.hit"), pretend.call("lru.cache.purge"), pretend.call("lru.cache.miss"), pretend.call("lru.cache.hit"), ] def test_redis_down(self, metrics): down_redis = pretend.stub( hget=pretend.raiser(redis.exceptions.RedisError), pipeline=pretend.raiser(redis.exceptions.RedisError), scan_iter=pretend.raiser(redis.exceptions.RedisError), ) redis_lru = RedisLru(down_redis, metric_reporter=metrics) expected = func_test(0, 1, kwarg0=2, kwarg1=3) assert expected == redis_lru.fetch( func_test, [0, 1], {"kwarg0": 2, "kwarg1": 3}, None, "test", None ) assert expected == redis_lru.fetch( func_test, [0, 1], {"kwarg0": 2, "kwarg1": 3}, None, "test", None ) with pytest.raises(CacheError): redis_lru.purge("test") assert metrics.increment.calls == [ pretend.call("lru.cache.error"), # Failed get pretend.call("lru.cache.miss"), pretend.call("lru.cache.error"), # Failed add pretend.call("lru.cache.error"), # Failed get pretend.call("lru.cache.miss"), pretend.call("lru.cache.error"), # Failed add pretend.call("lru.cache.error"), # Failed purge ]
TestRedisLru
python
tiangolo__fastapi
tests/test_validate_response_recursive/app.py
{ "start": 143, "end": 233 }
class ____(BaseModel): sub_items: List["RecursiveItem"] = [] name: str
RecursiveItem
python
coleifer__peewee
tests/regressions.py
{ "start": 51165, "end": 51311 }
class ____(TestModel): id = CharField(primary_key=True) name = CharField(unique=True) def __str__(self): return self.name
CharPK
python
pandas-dev__pandas
pandas/io/parsers/readers.py
{ "start": 4025, "end": 65272 }
class ____(TypedDict): colspecs: Literal["infer"] infer_nrows: Literal[100] widths: None _fwf_defaults: _Fwf_Defaults = {"colspecs": "infer", "infer_nrows": 100, "widths": None} _c_unsupported = {"skipfooter"} _python_unsupported = {"low_memory", "float_precision"} _pyarrow_unsupported = { "skipfooter", "float_precision", "chunksize", "comment", "nrows", "thousands", "memory_map", "dialect", "quoting", "lineterminator", "converters", "iterator", "dayfirst", "skipinitialspace", "low_memory", } @overload def validate_integer(name: str, val: None, min_val: int = ...) -> None: ... @overload def validate_integer(name: str, val: float, min_val: int = ...) -> int: ... @overload def validate_integer(name: str, val: int | None, min_val: int = ...) -> int | None: ... def validate_integer( name: str, val: int | float | None, min_val: int = 0 ) -> int | None: """ Checks whether the 'name' parameter for parsing is either an integer OR float that can SAFELY be cast to an integer without losing accuracy. Raises a ValueError if that is not the case. Parameters ---------- name : str Parameter name (used for error reporting) val : int or float The value to check min_val : int Minimum allowed value (val < min_val will result in a ValueError) """ if val is None: return val msg = f"'{name:s}' must be an integer >={min_val:d}" if is_float(val): if int(val) != val: raise ValueError(msg) val = int(val) elif not (is_integer(val) and val >= min_val): raise ValueError(msg) return int(val) def _validate_names(names: Sequence[Hashable] | None) -> None: """ Raise ValueError if the `names` parameter contains duplicates or has an invalid data type. Parameters ---------- names : array-like or None An array containing a list of the names used for the output DataFrame. Raises ------ ValueError If names are not unique or are not ordered (e.g. set). """ if names is not None: if len(names) != len(set(names)): raise ValueError("Duplicate names are not allowed.") if not ( is_list_like(names, allow_sets=False) or isinstance(names, abc.KeysView) ): raise ValueError("Names should be an ordered collection.") def _read( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], kwds ) -> DataFrame | TextFileReader: """Generic reader of line files.""" # if we pass a date_format and parse_dates=False, we should not parse the # dates GH#44366 if kwds.get("parse_dates", None) is None: if kwds.get("date_format", None) is None: kwds["parse_dates"] = False else: kwds["parse_dates"] = True # Extract some of the arguments (pass chunksize on). iterator = kwds.get("iterator", False) chunksize = kwds.get("chunksize", None) # Check type of encoding_errors errors = kwds.get("encoding_errors", "strict") if not isinstance(errors, str): raise ValueError( f"encoding_errors must be a string, got {type(errors).__name__}" ) if kwds.get("engine") == "pyarrow": if iterator: raise ValueError( "The 'iterator' option is not supported with the 'pyarrow' engine" ) if chunksize is not None: raise ValueError( "The 'chunksize' option is not supported with the 'pyarrow' engine" ) else: chunksize = validate_integer("chunksize", chunksize, 1) nrows = kwds.get("nrows", None) # Check for duplicates in names. _validate_names(kwds.get("names", None)) # Create the parser. parser = TextFileReader(filepath_or_buffer, **kwds) if chunksize or iterator: return parser with parser: return parser.read(nrows) @overload def read_csv( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, iterator: Literal[True], chunksize: int | None = ..., **kwds: Unpack[_read_shared[HashableT]], ) -> TextFileReader: ... @overload def read_csv( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, iterator: bool = ..., chunksize: int, **kwds: Unpack[_read_shared[HashableT]], ) -> TextFileReader: ... @overload def read_csv( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, iterator: Literal[False] = ..., chunksize: None = ..., **kwds: Unpack[_read_shared[HashableT]], ) -> DataFrame: ... @overload def read_csv( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, iterator: bool = ..., chunksize: int | None = ..., **kwds: Unpack[_read_shared[HashableT]], ) -> DataFrame | TextFileReader: ... @set_module("pandas") def read_csv( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, sep: str | None | lib.NoDefault = lib.no_default, delimiter: str | None | lib.NoDefault = None, # Column and Index Locations and Names header: int | Sequence[int] | None | Literal["infer"] = "infer", names: Sequence[Hashable] | None | lib.NoDefault = lib.no_default, index_col: IndexLabel | Literal[False] | None = None, usecols: UsecolsArgType = None, # General Parsing Configuration dtype: DtypeArg | None = None, engine: CSVEngine | None = None, converters: Mapping[HashableT, Callable] | None = None, true_values: list | None = None, false_values: list | None = None, skipinitialspace: bool = False, skiprows: list[int] | int | Callable[[Hashable], bool] | None = None, skipfooter: int = 0, nrows: int | None = None, # NA and Missing Data Handling na_values: ( Hashable | Iterable[Hashable] | Mapping[Hashable, Iterable[Hashable]] | None ) = None, keep_default_na: bool = True, na_filter: bool = True, skip_blank_lines: bool = True, # Datetime Handling parse_dates: bool | Sequence[Hashable] | None = None, date_format: str | dict[Hashable, str] | None = None, dayfirst: bool = False, cache_dates: bool = True, # Iteration iterator: bool = False, chunksize: int | None = None, # Quoting, Compression, and File Format compression: CompressionOptions = "infer", thousands: str | None = None, decimal: str = ".", lineterminator: str | None = None, quotechar: str = '"', quoting: int = csv.QUOTE_MINIMAL, doublequote: bool = True, escapechar: str | None = None, comment: str | None = None, encoding: str | None = None, encoding_errors: str | None = "strict", dialect: str | csv.Dialect | None = None, # Error Handling on_bad_lines: str = "error", # Internal low_memory: bool = _c_parser_defaults["low_memory"], memory_map: bool = False, float_precision: Literal["high", "legacy", "round_trip"] | None = None, storage_options: StorageOptions | None = None, dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, ) -> DataFrame | TextFileReader: """ Read a comma-separated values (csv) file into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the online docs for `IO Tools <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_. Parameters ---------- filepath_or_buffer : str, path object or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, gs, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.csv. If you want to pass in a path object, pandas accepts any ``os.PathLike``. By file-like object, we refer to objects with a ``read()`` method, such as a file handle (e.g. via builtin ``open`` function) or ``StringIO``. sep : str, default ',' Character or regex pattern to treat as the delimiter. If ``sep=None``, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detect the separator from only the first valid row of the file by Python's builtin sniffer tool, ``csv.Sniffer``. In addition, separators longer than 1 character and different from ``'\\s+'`` will be interpreted as regular expressions and will also force the use of the Python parsing engine. Note that regex delimiters are prone to ignoring quoted data. Regex example: ``'\\r\\t'``. delimiter : str, optional Alias for ``sep``. header : int, Sequence of int, 'infer' or None, default 'infer' Row number(s) containing column labels and marking the start of the data (zero-indexed). Default behavior is to infer the column names: if no ``names`` are passed the behavior is identical to ``header=0`` and column names are inferred from the first line of the file, if column names are passed explicitly to ``names`` then the behavior is identical to ``header=None``. Explicitly pass ``header=0`` to be able to replace existing names. The header can be a list of integers that specify row locations for a :class:`~pandas.MultiIndex` on the columns e.g. ``[0, 1, 3]``. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines if ``skip_blank_lines=True``, so ``header=0`` denotes the first line of data rather than the first line of the file. When inferred from the file contents, headers are kept distinct from each other by renaming duplicate names with a numeric suffix of the form ``".{{count}}"`` starting from 1, e.g. ``"foo"`` and ``"foo.1"``. Empty headers are named ``"Unnamed: {{i}}"`` or `` "Unnamed: {{i}}_level_{{level}}"`` in the case of MultiIndex columns. names : Sequence of Hashable, optional Sequence of column labels to apply. If the file contains a header row, then you should explicitly pass ``header=0`` to override the column names. Duplicates in this list are not allowed. index_col : Hashable, Sequence of Hashable or False, optional Column(s) to use as row label(s), denoted either by column labels or column indices. If a sequence of labels or indices is given, :class:`~pandas.MultiIndex` will be formed for the row labels. Note: ``index_col=False`` can be used to force pandas to *not* use the first column as the index, e.g., when you have a malformed file with delimiters at the end of each line. usecols : Sequence of Hashable or Callable, optional Subset of columns to select, denoted either by column labels or column indices. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in ``names`` or inferred from the document header row(s). If ``names`` are given, the document header row(s) are not taken into account. For example, a valid list-like ``usecols`` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``. Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``. To instantiate a :class:`~pandas.DataFrame` from ``data`` with element order preserved use ``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns in ``['foo', 'bar']`` order or ``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]`` for ``['bar', 'foo']`` order. If callable, the callable function will be evaluated against the column names, returning names where the callable function evaluates to ``True``. An example of a valid callable argument would be ``lambda x: x.upper() in ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster parsing time and lower memory usage. dtype : dtype or dict of {{Hashable : dtype}}, optional Data type(s) to apply to either the whole dataset or individual columns. E.g., ``{{'a': np.float64, 'b': np.int32, 'c': 'Int64'}}`` Use ``str`` or ``object`` together with suitable ``na_values`` settings to preserve and not interpret ``dtype``. If ``converters`` are specified, they will be applied INSTEAD of ``dtype`` conversion. Specify a ``defaultdict`` as input where the default determines the ``dtype`` of the columns which are not explicitly listed. engine : {{'c', 'python', 'pyarrow'}}, optional Parser engine to use. The C and pyarrow engines are faster, while the python engine is currently more feature-complete. Multithreading is currently only supported by the pyarrow engine. Some features of the "pyarrow" engine are unsupported or may not work correctly. converters : dict of {{Hashable : Callable}}, optional Functions for converting values in specified columns. Keys can either be column labels or column indices. true_values : list, optional Values to consider as ``True`` in addition to case-insensitive variants of 'True'. false_values : list, optional Values to consider as ``False`` in addition to case-insensitive variants of 'False'. skipinitialspace : bool, default False Skip spaces after delimiter. skiprows : int, list of int or Callable, optional Line numbers to skip (0-indexed) or number of lines to skip (``int``) at the start of the file. If callable, the callable function will be evaluated against the row indices, returning ``True`` if the row should be skipped and ``False`` otherwise. An example of a valid callable argument would be ``lambda x: x in [0, 2]``. skipfooter : int, default 0 Number of lines at bottom of file to skip (Unsupported with ``engine='c'``). nrows : int, optional Number of rows of file to read. Useful for reading pieces of large files. Refers to the number of data rows in the returned DataFrame, excluding: * The header row containing column names. * Rows before the header row, if ``header=1`` or larger. Example usage: * To read the first 999,999 (non-header) rows: ``read_csv(..., nrows=999999)`` * To read rows 1,000,000 through 1,999,999: ``read_csv(..., skiprows=1000000, nrows=999999)`` na_values : Hashable, Iterable of Hashable or dict of {{Hashable : Iterable}}, optional Additional strings to recognize as ``NA``/``NaN``. If ``dict`` passed, specific per-column ``NA`` values. By default the following values are interpreted as ``NaN``: empty string, "NaN", "N/A", "NULL", and other common representations of missing data. keep_default_na : bool, default True Whether or not to include the default ``NaN`` values when parsing the data. Depending on whether ``na_values`` is passed in, the behavior is as follows: * If ``keep_default_na`` is ``True``, and ``na_values`` are specified, ``na_values`` is appended to the default ``NaN`` values used for parsing. * If ``keep_default_na`` is ``True``, and ``na_values`` are not specified, only the default ``NaN`` values are used for parsing. * If ``keep_default_na`` is ``False``, and ``na_values`` are specified, only the ``NaN`` values specified ``na_values`` are used for parsing. * If ``keep_default_na`` is ``False``, and ``na_values`` are not specified, no strings will be parsed as ``NaN``. Note that if ``na_filter`` is passed in as ``False``, the ``keep_default_na`` and ``na_values`` parameters will be ignored. na_filter : bool, default True Detect missing value markers (empty strings and the value of ``na_values``). In data without any ``NA`` values, passing ``na_filter=False`` can improve the performance of reading a large file. skip_blank_lines : bool, default True If ``True``, skip over blank lines rather than interpreting as ``NaN`` values. parse_dates : bool, None, list of Hashable, default None The behavior is as follows: * ``bool``. If ``True`` -> try parsing the index. * ``None``. Behaves like ``True`` if ``date_format`` is specified. * ``list`` of ``int`` or names. e.g. If ``[1, 2, 3]`` -> try parsing columns 1, 2, 3 each as a separate date column. If a column or index cannot be represented as an array of ``datetime``, say because of an unparsable value or a mixture of timezones, the column or index will be returned unaltered as an ``object`` data type. For non-standard ``datetime`` parsing, use :func:`~pandas.to_datetime` after :func:`~pandas.read_csv`. Note: A fast-path exists for iso8601-formatted dates. date_format : str or dict of column -> format, optional Format to use for parsing dates and/or times when used in conjunction with ``parse_dates``. The strftime to parse time, e.g. :const:`"%d/%m/%Y"`. See `strftime documentation <https://docs.python.org/3/library/datetime.html #strftime-and-strptime-behavior>`_ for more information on choices, though note that :const:`"%f"`` will parse all the way up to nanoseconds. You can also pass: - "ISO8601", to parse any `ISO8601 <https://en.wikipedia.org/wiki/ISO_8601>`_ time string (not necessarily in exactly the same format); - "mixed", to infer the format for each element individually. This is risky, and you should probably use it along with `dayfirst`. .. versionadded:: 2.0.0 dayfirst : bool, default False DD/MM format dates, international and European format. cache_dates : bool, default True If ``True``, use a cache of unique, converted dates to apply the ``datetime`` conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets. iterator : bool, default False Return ``TextFileReader`` object for iteration or getting chunks with ``get_chunk()``. chunksize : int, optional Number of lines to read from the file per chunk. Passing a value will cause the function to return a ``TextFileReader`` object for iteration. See the `IO Tools docs <https://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_ for more information on ``iterator`` and ``chunksize``. compression : str or dict, default 'infer' For on-the-fly decompression of on-disk data. If 'infer' and 'filepath_or_buffer' is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2' (otherwise no compression). If using 'zip' or 'tar', the ZIP file must contain only one data file to be read in. Set to ``None`` for no decompression. Can also be a dict with key ``'method'`` set to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``} and other key-value pairs are forwarded to ``zipfile.ZipFile``, ``gzip.GzipFile``, ``bz2.BZ2File``, ``zstandard.ZstdDecompressor``, ``lzma.LZMAFile`` or ``tarfile.TarFile``, respectively. As an example, the following could be passed for Zstandard decompression using a custom compression dictionary: ``compression={'method': 'zstd', 'dict_data': my_compression_dict}``. thousands : str (length 1), optional Character acting as the thousands separator in numerical values. decimal : str (length 1), default '.' Character to recognize as decimal point (e.g., use ',' for European data). lineterminator : str (length 1), optional Character used to denote a line break. Only valid with C parser. quotechar : str (length 1), optional Character used to denote the start and end of a quoted item. Quoted items can include the ``delimiter`` and it will be ignored. quoting : {{0 or csv.QUOTE_MINIMAL, 1 or csv.QUOTE_ALL, 2 or csv.QUOTE_NONNUMERIC, 3 or csv.QUOTE_NONE}}, default csv.QUOTE_MINIMAL Control field quoting behavior per ``csv.QUOTE_*`` constants. Default is ``csv.QUOTE_MINIMAL`` (i.e., 0) which implies that only fields containing special characters are quoted (e.g., characters defined in ``quotechar``, ``delimiter``, or ``lineterminator``. doublequote : bool, default True When ``quotechar`` is specified and ``quoting`` is not ``QUOTE_NONE``, indicate whether or not to interpret two consecutive ``quotechar`` elements INSIDE a field as a single ``quotechar`` element. escapechar : str (length 1), optional Character used to escape other characters. comment : str (length 1), optional Character indicating that the remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as ``skip_blank_lines=True``), fully commented lines are ignored by the parameter ``header`` but not by ``skiprows``. For example, if ``comment='#'``, parsing ``#empty\\na,b,c\\n1,2,3`` with ``header=0`` will result in ``'a,b,c'`` being treated as the header. encoding : str, optional, default 'utf-8' Encoding to use for UTF when reading/writing (ex. ``'utf-8'``). `List of Python standard encodings <https://docs.python.org/3/library/codecs.html#standard-encodings>`_ . encoding_errors : str, optional, default 'strict' How encoding errors are treated. `List of possible values <https://docs.python.org/3/library/codecs.html#error-handlers>`_ . dialect : str or csv.Dialect, optional If provided, this parameter will override values (default or not) for the following parameters: ``delimiter``, ``doublequote``, ``escapechar``, ``skipinitialspace``, ``quotechar``, and ``quoting``. If it is necessary to override values, a ``ParserWarning`` will be issued. See ``csv.Dialect`` documentation for more details. on_bad_lines : {{'error', 'warn', 'skip'}} or Callable, default 'error' Specifies what to do upon encountering a bad line (a line with too many fields). Allowed values are: - ``'error'``, raise an Exception when a bad line is encountered. - ``'warn'``, raise a warning when a bad line is encountered and skip that line. - ``'skip'``, skip bad lines without raising or warning when they are encountered. - Callable, function that will process a single bad line. - With ``engine='python'``, function with signature ``(bad_line: list[str]) -> list[str] | None``. ``bad_line`` is a list of strings split by the ``sep``. If the function returns ``None``, the bad line will be ignored. If the function returns a new ``list`` of strings with more elements than expected, a ``ParserWarning`` will be emitted while dropping extra elements. - With ``engine='pyarrow'``, function with signature as described in pyarrow documentation: `invalid_row_handler <https://arrow.apache.org/docs/python /generated/pyarrow.csv.ParseOptions.html #pyarrow.csv.ParseOptions.invalid_row_handler>`_. .. versionchanged:: 2.2.0 Callable for ``engine='pyarrow'`` low_memory : bool, default True Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set ``False``, or specify the type with the ``dtype`` parameter. Note that the entire file is read into a single :class:`~pandas.DataFrame` regardless, use the ``chunksize`` or ``iterator`` parameter to return the data in chunks. (Only valid with C parser). memory_map : bool, default False If a filepath is provided for ``filepath_or_buffer``, map the file object directly onto memory and access the data directly from there. Using this option can improve performance because there is no longer any I/O overhead. float_precision : {{'high', 'legacy', 'round_trip'}}, optional Specifies which converter the C engine should use for floating-point values. The options are ``None`` or ``'high'`` for the ordinary converter, ``'legacy'`` for the original lower precision pandas converter, and ``'round_trip'`` for the round-trip converter. storage_options : dict, optional Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_. dtype_backend : {{'numpy_nullable', 'pyarrow'}} Back-end data type applied to the resultant :class:`DataFrame` (still experimental). If not specified, the default behavior is to not use nullable data types. If specified, the behavior is as follows: * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` :class:`DataFrame` .. versionadded:: 2.0 Returns ------- DataFrame or TextFileReader A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes. See Also -------- DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file. read_table : Read general delimited file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame. Examples -------- >>> pd.read_csv("data.csv") # doctest: +SKIP Name Value 0 foo 1 1 bar 2 2 #baz 3 Index and header can be specified via the `index_col` and `header` arguments. >>> pd.read_csv("data.csv", header=None) # doctest: +SKIP 0 1 0 Name Value 1 foo 1 2 bar 2 3 #baz 3 >>> pd.read_csv("data.csv", index_col="Value") # doctest: +SKIP Name Value 1 foo 2 bar 3 #baz Column types are inferred but can be explicitly specified using the dtype argument. >>> pd.read_csv("data.csv", dtype={{"Value": float}}) # doctest: +SKIP Name Value 0 foo 1.0 1 bar 2.0 2 #baz 3.0 True, False, and NA values, and thousands separators have defaults, but can be explicitly specified, too. Supply the values you would like as strings or lists of strings! >>> pd.read_csv("data.csv", na_values=["foo", "bar"]) # doctest: +SKIP Name Value 0 NaN 1 1 NaN 2 2 #baz 3 Comment lines in the input file can be skipped using the `comment` argument. >>> pd.read_csv("data.csv", comment="#") # doctest: +SKIP Name Value 0 foo 1 1 bar 2 By default, columns with dates will be read as ``object`` rather than ``datetime``. >>> df = pd.read_csv("tmp.csv") # doctest: +SKIP >>> df # doctest: +SKIP col 1 col 2 col 3 0 10 10/04/2018 Sun 15 Jan 2023 1 20 15/04/2018 Fri 12 May 2023 >>> df.dtypes # doctest: +SKIP col 1 int64 col 2 object col 3 object dtype: object Specific columns can be parsed as dates by using the `parse_dates` and `date_format` arguments. >>> df = pd.read_csv( ... "tmp.csv", ... parse_dates=[1, 2], ... date_format={{"col 2": "%d/%m/%Y", "col 3": "%a %d %b %Y"}}, ... ) # doctest: +SKIP >>> df.dtypes # doctest: +SKIP col 1 int64 col 2 datetime64[ns] col 3 datetime64[ns] dtype: object """ # locals() should never be modified kwds = locals().copy() del kwds["filepath_or_buffer"] del kwds["sep"] kwds_defaults = _refine_defaults_read( dialect, delimiter, engine, sep, on_bad_lines, names, defaults={"delimiter": ","}, dtype_backend=dtype_backend, ) kwds.update(kwds_defaults) return _read(filepath_or_buffer, kwds) @overload def read_table( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, iterator: Literal[True], chunksize: int | None = ..., **kwds: Unpack[_read_shared[HashableT]], ) -> TextFileReader: ... @overload def read_table( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, iterator: bool = ..., chunksize: int, **kwds: Unpack[_read_shared[HashableT]], ) -> TextFileReader: ... @overload def read_table( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, iterator: Literal[False] = ..., chunksize: None = ..., **kwds: Unpack[_read_shared[HashableT]], ) -> DataFrame: ... @overload def read_table( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, iterator: bool = ..., chunksize: int | None = ..., **kwds: Unpack[_read_shared[HashableT]], ) -> DataFrame | TextFileReader: ... @set_module("pandas") def read_table( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, sep: str | None | lib.NoDefault = lib.no_default, delimiter: str | None | lib.NoDefault = None, # Column and Index Locations and Names header: int | Sequence[int] | None | Literal["infer"] = "infer", names: Sequence[Hashable] | None | lib.NoDefault = lib.no_default, index_col: IndexLabel | Literal[False] | None = None, usecols: UsecolsArgType = None, # General Parsing Configuration dtype: DtypeArg | None = None, engine: CSVEngine | None = None, converters: Mapping[HashableT, Callable] | None = None, true_values: list | None = None, false_values: list | None = None, skipinitialspace: bool = False, skiprows: list[int] | int | Callable[[Hashable], bool] | None = None, skipfooter: int = 0, nrows: int | None = None, # NA and Missing Data Handling na_values: ( Hashable | Iterable[Hashable] | Mapping[Hashable, Iterable[Hashable]] | None ) = None, keep_default_na: bool = True, na_filter: bool = True, skip_blank_lines: bool = True, # Datetime Handling parse_dates: bool | Sequence[Hashable] | None = None, date_format: str | dict[Hashable, str] | None = None, dayfirst: bool = False, cache_dates: bool = True, # Iteration iterator: bool = False, chunksize: int | None = None, # Quoting, Compression, and File Format compression: CompressionOptions = "infer", thousands: str | None = None, decimal: str = ".", lineterminator: str | None = None, quotechar: str = '"', quoting: int = csv.QUOTE_MINIMAL, doublequote: bool = True, escapechar: str | None = None, comment: str | None = None, encoding: str | None = None, encoding_errors: str | None = "strict", dialect: str | csv.Dialect | None = None, # Error Handling on_bad_lines: str = "error", # Internal low_memory: bool = _c_parser_defaults["low_memory"], memory_map: bool = False, float_precision: Literal["high", "legacy", "round_trip"] | None = None, storage_options: StorageOptions | None = None, dtype_backend: DtypeBackend | lib.NoDefault = lib.no_default, ) -> DataFrame | TextFileReader: """ Read general delimited file into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the online docs for `IO Tools <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_. Parameters ---------- filepath_or_buffer : str, path object or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, gs, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.csv. If you want to pass in a path object, pandas accepts any ``os.PathLike``. By file-like object, we refer to objects with a ``read()`` method, such as a file handle (e.g. via builtin ``open`` function) or ``StringIO``. sep : str, default '\\t' (tab-stop) Character or regex pattern to treat as the delimiter. If ``sep=None``, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detect the separator from only the first valid row of the file by Python's builtin sniffer tool, ``csv.Sniffer``. In addition, separators longer than 1 character and different from ``'\\s+'`` will be interpreted as regular expressions and will also force the use of the Python parsing engine. Note that regex delimiters are prone to ignoring quoted data. Regex example: ``'\\r\\t'``. delimiter : str, optional Alias for ``sep``. header : int, Sequence of int, 'infer' or None, default 'infer' Row number(s) containing column labels and marking the start of the data (zero-indexed). Default behavior is to infer the column names: if no ``names`` are passed the behavior is identical to ``header=0`` and column names are inferred from the first line of the file, if column names are passed explicitly to ``names`` then the behavior is identical to ``header=None``. Explicitly pass ``header=0`` to be able to replace existing names. The header can be a list of integers that specify row locations for a :class:`~pandas.MultiIndex` on the columns e.g. ``[0, 1, 3]``. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines if ``skip_blank_lines=True``, so ``header=0`` denotes the first line of data rather than the first line of the file. When inferred from the file contents, headers are kept distinct from each other by renaming duplicate names with a numeric suffix of the form ``".{{count}}"`` starting from 1, e.g. ``"foo"`` and ``"foo.1"``. Empty headers are named ``"Unnamed: {{i}}"`` or ``"Unnamed: {{i}}_level_{{level}}"`` in the case of MultiIndex columns. names : Sequence of Hashable, optional Sequence of column labels to apply. If the file contains a header row, then you should explicitly pass ``header=0`` to override the column names. Duplicates in this list are not allowed. index_col : Hashable, Sequence of Hashable or False, optional Column(s) to use as row label(s), denoted either by column labels or column indices. If a sequence of labels or indices is given, :class:`~pandas.MultiIndex` will be formed for the row labels. Note: ``index_col=False`` can be used to force pandas to *not* use the first column as the index, e.g., when you have a malformed file with delimiters at the end of each line. usecols : Sequence of Hashable or Callable, optional Subset of columns to select, denoted either by column labels or column indices. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in ``names`` or inferred from the document header row(s). If ``names`` are given, the document header row(s) are not taken into account. For example, a valid list-like ``usecols`` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``. Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``. To instantiate a :class:`~pandas.DataFrame` from ``data`` with element order preserved use ``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns in ``['foo', 'bar']`` order or ``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]`` for ``['bar', 'foo']`` order. If callable, the callable function will be evaluated against the column names, returning names where the callable function evaluates to ``True``. An example of a valid callable argument would be ``lambda x: x.upper() in ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster parsing time and lower memory usage. dtype : dtype or dict of {{Hashable : dtype}}, optional Data type(s) to apply to either the whole dataset or individual columns. E.g., ``{{'a': np.float64, 'b': np.int32, 'c': 'Int64'}}`` Use ``str`` or ``object`` together with suitable ``na_values`` settings to preserve and not interpret ``dtype``. If ``converters`` are specified, they will be applied INSTEAD of ``dtype`` conversion. Specify a ``defaultdict`` as input where the default determines the ``dtype`` of the columns which are not explicitly listed. engine : {{'c', 'python', 'pyarrow'}}, optional Parser engine to use. The C and pyarrow engines are faster, while the python engine is currently more feature-complete. Multithreading is currently only supported by the pyarrow engine. The 'pyarrow' engine is an *experimental* engine, and some features are unsupported, or may not work correctly, with this engine. converters : dict of {{Hashable : Callable}}, optional Functions for converting values in specified columns. Keys can either be column labels or column indices. true_values : list, optional Values to consider as ``True`` in addition to case-insensitive variants of 'True'. false_values : list, optional Values to consider as ``False`` in addition to case-insensitive variants of 'False'. skipinitialspace : bool, default False Skip spaces after delimiter. skiprows : int, list of int or Callable, optional Line numbers to skip (0-indexed) or number of lines to skip (``int``) at the start of the file. If callable, the callable function will be evaluated against the row indices, returning ``True`` if the row should be skipped and ``False`` otherwise. An example of a valid callable argument would be ``lambda x: x in [0, 2]``. skipfooter : int, default 0 Number of lines at bottom of file to skip (Unsupported with ``engine='c'``). nrows : int, optional Number of rows of file to read. Useful for reading pieces of large files. Refers to the number of data rows in the returned DataFrame, excluding: * The header row containing column names. * Rows before the header row, if ``header=1`` or larger. Example usage: * To read the first 999,999 (non-header) rows: ``read_csv(..., nrows=999999)`` * To read rows 1,000,000 through 1,999,999: ``read_csv(..., skiprows=1000000, nrows=999999)`` na_values : Hashable, Iterable of Hashable or dict of {{Hashable : Iterable}}, optional Additional strings to recognize as ``NA``/``NaN``. If ``dict`` passed, specific per-column ``NA`` values. By default the following values are interpreted as ``NaN``: empty string, "NaN", "N/A", "NULL", and other common representations of missing data. keep_default_na : bool, default True Whether or not to include the default ``NaN`` values when parsing the data. Depending on whether ``na_values`` is passed in, the behavior is as follows: * If ``keep_default_na`` is ``True``, and ``na_values`` are specified, ``na_values`` is appended to the default ``NaN`` values used for parsing. * If ``keep_default_na`` is ``True``, and ``na_values`` are not specified, only the default ``NaN`` values are used for parsing. * If ``keep_default_na`` is ``False``, and ``na_values`` are specified, only the ``NaN`` values specified ``na_values`` are used for parsing. * If ``keep_default_na`` is ``False``, and ``na_values`` are not specified, no strings will be parsed as ``NaN``. Note that if ``na_filter`` is passed in as ``False``, the ``keep_default_na`` and ``na_values`` parameters will be ignored. na_filter : bool, default True Detect missing value markers (empty strings and the value of ``na_values``). In data without any ``NA`` values, passing ``na_filter=False`` can improve the performance of reading a large file. skip_blank_lines : bool, default True If ``True``, skip over blank lines rather than interpreting as ``NaN`` values. parse_dates : bool, None, list of Hashable, default None The behavior is as follows: * ``bool``. If ``True`` -> try parsing the index. * ``None``. Behaves like ``True`` if ``date_format`` is specified. * ``list`` of ``int`` or names. e.g. If ``[1, 2, 3]`` -> try parsing columns 1, 2, 3 each as a separate date column. If a column or index cannot be represented as an array of ``datetime``, say because of an unparsable value or a mixture of timezones, the column or index will be returned unaltered as an ``object`` data type. For non-standard ``datetime`` parsing, use :func:`~pandas.to_datetime` after :func:`~pandas.read_csv`. Note: A fast-path exists for iso8601-formatted dates. date_format : str or dict of column -> format, optional Format to use for parsing dates and/or times when used in conjunction with ``parse_dates``. The strftime to parse time, e.g. :const:`"%d/%m/%Y"`. See `strftime documentation <https://docs.python.org/3/library/datetime.html #strftime-and-strptime-behavior>`_ for more information on choices, though note that :const:`"%f"`` will parse all the way up to nanoseconds. You can also pass: - "ISO8601", to parse any `ISO8601 <https://en.wikipedia.org/wiki/ISO_8601>`_ time string (not necessarily in exactly the same format); - "mixed", to infer the format for each element individually. This is risky, and you should probably use it along with `dayfirst`. .. versionadded:: 2.0.0 dayfirst : bool, default False DD/MM format dates, international and European format. cache_dates : bool, default True If ``True``, use a cache of unique, converted dates to apply the ``datetime`` conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets. iterator : bool, default False Return ``TextFileReader`` object for iteration or getting chunks with ``get_chunk()``. chunksize : int, optional Number of lines to read from the file per chunk. Passing a value will cause the function to return a ``TextFileReader`` object for iteration. See the `IO Tools docs <https://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_ for more information on ``iterator`` and ``chunksize``. compression : str or dict, default 'infer' For on-the-fly decompression of on-disk data. If 'infer' and 'filepath_or_buffer' is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2' (otherwise no compression). If using 'zip' or 'tar', the ZIP file must contain only one data file to be read in. Set to ``None`` for no decompression. Can also be a dict with key ``'method'`` set to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``} and other key-value pairs are forwarded to ``zipfile.ZipFile``, ``gzip.GzipFile``, ``bz2.BZ2File``, ``zstandard.ZstdDecompressor``, ``lzma.LZMAFile`` or ``tarfile.TarFile``, respectively. As an example, the following could be passed for Zstandard decompression using a custom compression dictionary: ``compression={'method': 'zstd', 'dict_data': my_compression_dict}``. thousands : str (length 1), optional Character acting as the thousands separator in numerical values. decimal : str (length 1), default '.' Character to recognize as decimal point (e.g., use ',' for European data). lineterminator : str (length 1), optional Character used to denote a line break. Only valid with C parser. quotechar : str (length 1), optional Character used to denote the start and end of a quoted item. Quoted items can include the ``delimiter`` and it will be ignored. quoting : {{0 or csv.QUOTE_MINIMAL, 1 or csv.QUOTE_ALL, 2 or csv.QUOTE_NONNUMERIC, 3 or csv.QUOTE_NONE}}, default csv.QUOTE_MINIMAL Control field quoting behavior per ``csv.QUOTE_*`` constants. Default is ``csv.QUOTE_MINIMAL`` (i.e., 0) which implies that only fields containing special characters are quoted (e.g., characters defined in ``quotechar``, ``delimiter``, or ``lineterminator``. doublequote : bool, default True When ``quotechar`` is specified and ``quoting`` is not ``QUOTE_NONE``, indicate whether or not to interpret two consecutive ``quotechar`` elements INSIDE a field as a single ``quotechar`` element. escapechar : str (length 1), optional Character used to escape other characters. comment : str (length 1), optional Character indicating that the remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as ``skip_blank_lines=True``), fully commented lines are ignored by the parameter ``header`` but not by ``skiprows``. For example, if ``comment='#'``, parsing ``#empty\\na,b,c\\n1,2,3`` with ``header=0`` will result in ``'a,b,c'`` being treated as the header. encoding : str, optional, default 'utf-8' Encoding to use for UTF when reading/writing (ex. ``'utf-8'``). `List of Python standard encodings <https://docs.python.org/3/library/codecs.html#standard-encodings>`_ . encoding_errors : str, optional, default 'strict' How encoding errors are treated. `List of possible values <https://docs.python.org/3/library/codecs.html#error-handlers>`_ . dialect : str or csv.Dialect, optional If provided, this parameter will override values (default or not) for the following parameters: ``delimiter``, ``doublequote``, ``escapechar``, ``skipinitialspace``, ``quotechar``, and ``quoting``. If it is necessary to override values, a ``ParserWarning`` will be issued. See ``csv.Dialect`` documentation for more details. on_bad_lines : {{'error', 'warn', 'skip'}} or Callable, default 'error' Specifies what to do upon encountering a bad line (a line with too many fields). Allowed values are: - ``'error'``, raise an Exception when a bad line is encountered. - ``'warn'``, raise a warning when a bad line is encountered and skip that line. - ``'skip'``, skip bad lines without raising or warning when they are encountered. - Callable, function that will process a single bad line. - With ``engine='python'``, function with signature ``(bad_line: list[str]) -> list[str] | None``. ``bad_line`` is a list of strings split by the ``sep``. If the function returns ``None``, the bad line will be ignored. If the function returns a new ``list`` of strings with more elements than expected, a ``ParserWarning`` will be emitted while dropping extra elements. - With ``engine='pyarrow'``, function with signature as described in pyarrow documentation: `invalid_row_handler <https://arrow.apache.org/docs/ python/generated/pyarrow.csv.ParseOptions.html #pyarrow.csv.ParseOptions.invalid_row_handler>`_. .. versionadded:: 2.2.0 Callable for ``engine='pyarrow'`` low_memory : bool, default True Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set ``False``, or specify the type with the ``dtype`` parameter. Note that the entire file is read into a single :class:`~pandas.DataFrame` regardless, use the ``chunksize`` or ``iterator`` parameter to return the data in chunks. (Only valid with C parser). memory_map : bool, default False If a filepath is provided for ``filepath_or_buffer``, map the file object directly onto memory and access the data directly from there. Using this option can improve performance because there is no longer any I/O overhead. float_precision : {{'high', 'legacy', 'round_trip'}}, optional Specifies which converter the C engine should use for floating-point values. The options are ``None`` or ``'high'`` for the ordinary converter, ``'legacy'`` for the original lower precision pandas converter, and ``'round_trip'`` for the round-trip converter. storage_options : dict, optional Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_. dtype_backend : {{'numpy_nullable', 'pyarrow'}} Back-end data type applied to the resultant :class:`DataFrame` (still experimental). If not specified, the default behavior is to not use nullable data types. If specified, the behavior is as follows: * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` :class:`DataFrame` .. versionadded:: 2.0 Returns ------- DataFrame or TextFileReader A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes. See Also -------- DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file. read_csv : Read a comma-separated values (csv) file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame. Examples -------- >>> pd.read_table("data.csv") # doctest: +SKIP Name Value 0 foo 1 1 bar 2 2 #baz 3 Index and header can be specified via the `index_col` and `header` arguments. >>> pd.read_table("data.csv", header=None) # doctest: +SKIP 0 1 0 Name Value 1 foo 1 2 bar 2 3 #baz 3 >>> pd.read_table("data.csv", index_col="Value") # doctest: +SKIP Name Value 1 foo 2 bar 3 #baz Column types are inferred but can be explicitly specified using the dtype argument. >>> pd.read_table("data.csv", dtype={{"Value": float}}) # doctest: +SKIP Name Value 0 foo 1.0 1 bar 2.0 2 #baz 3.0 True, False, and NA values, and thousands separators have defaults, but can be explicitly specified, too. Supply the values you would like as strings or lists of strings! >>> pd.read_table("data.csv", na_values=["foo", "bar"]) # doctest: +SKIP Name Value 0 NaN 1 1 NaN 2 2 #baz 3 Comment lines in the input file can be skipped using the `comment` argument. >>> pd.read_table("data.csv", comment="#") # doctest: +SKIP Name Value 0 foo 1 1 bar 2 By default, columns with dates will be read as ``object`` rather than ``datetime``. >>> df = pd.read_table("tmp.csv") # doctest: +SKIP >>> df # doctest: +SKIP col 1 col 2 col 3 0 10 10/04/2018 Sun 15 Jan 2023 1 20 15/04/2018 Fri 12 May 2023 >>> df.dtypes # doctest: +SKIP col 1 int64 col 2 object col 3 object dtype: object Specific columns can be parsed as dates by using the `parse_dates` and `date_format` arguments. >>> df = pd.read_table( ... "tmp.csv", ... parse_dates=[1, 2], ... date_format={{"col 2": "%d/%m/%Y", "col 3": "%a %d %b %Y"}}, ... ) # doctest: +SKIP >>> df.dtypes # doctest: +SKIP col 1 int64 col 2 datetime64[ns] col 3 datetime64[ns] dtype: object """ # locals() should never be modified kwds = locals().copy() del kwds["filepath_or_buffer"] del kwds["sep"] kwds_defaults = _refine_defaults_read( dialect, delimiter, engine, sep, on_bad_lines, names, defaults={"delimiter": "\t"}, dtype_backend=dtype_backend, ) kwds.update(kwds_defaults) return _read(filepath_or_buffer, kwds) @overload def read_fwf( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, colspecs: Sequence[tuple[int, int]] | str | None = ..., widths: Sequence[int] | None = ..., infer_nrows: int = ..., iterator: Literal[True], chunksize: int | None = ..., **kwds: Unpack[_read_shared[HashableT]], ) -> TextFileReader: ... @overload def read_fwf( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, colspecs: Sequence[tuple[int, int]] | str | None = ..., widths: Sequence[int] | None = ..., infer_nrows: int = ..., iterator: bool = ..., chunksize: int, **kwds: Unpack[_read_shared[HashableT]], ) -> TextFileReader: ... @overload def read_fwf( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, colspecs: Sequence[tuple[int, int]] | str | None = ..., widths: Sequence[int] | None = ..., infer_nrows: int = ..., iterator: Literal[False] = ..., chunksize: None = ..., **kwds: Unpack[_read_shared[HashableT]], ) -> DataFrame: ... @set_module("pandas") def read_fwf( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], *, colspecs: Sequence[tuple[int, int]] | str | None = "infer", widths: Sequence[int] | None = None, infer_nrows: int = 100, iterator: bool = False, chunksize: int | None = None, **kwds: Unpack[_read_shared[HashableT]], ) -> DataFrame | TextFileReader: r""" Read a table of fixed-width formatted lines into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the `online docs for IO Tools <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_. Parameters ---------- filepath_or_buffer : str, path object, or file-like object String, path object (implementing ``os.PathLike[str]``), or file-like object implementing a text ``read()`` function.The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: ``file://localhost/path/to/table.csv``. colspecs : list of tuple (int, int) or 'infer'. optional A list of tuples giving the extents of the fixed-width fields of each line as half-open intervals (i.e., [from, to] ). String value 'infer' can be used to instruct the parser to try detecting the column specifications from the first 100 rows of the data which are not being skipped via skiprows (default='infer'). widths : list of int, optional A list of field widths which can be used instead of 'colspecs' if the intervals are contiguous. infer_nrows : int, default 100 The number of rows to consider when letting the parser determine the `colspecs`. iterator : bool, default False Return ``TextFileReader`` object for iteration or getting chunks with ``get_chunk()``. chunksize : int, optional Number of lines to read from the file per chunk. **kwds : optional Optional keyword arguments can be passed to ``TextFileReader``. Returns ------- DataFrame or TextFileReader A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes. See Also -------- DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file. read_csv : Read a comma-separated values (csv) file into DataFrame. Examples -------- >>> pd.read_fwf("data.csv") # doctest: +SKIP """ # Check input arguments. if colspecs is None and widths is None: raise ValueError("Must specify either colspecs or widths") if colspecs not in (None, "infer") and widths is not None: raise ValueError("You must specify only one of 'widths' and 'colspecs'") # Compute 'colspecs' from 'widths', if specified. if widths is not None: colspecs, col = [], 0 for w in widths: colspecs.append((col, col + w)) col += w # for mypy assert colspecs is not None # GH#40830 # Ensure length of `colspecs` matches length of `names` names = kwds.get("names") if names is not None and names is not lib.no_default: if len(names) != len(colspecs) and colspecs != "infer": # need to check len(index_col) as it might contain # unnamed indices, in which case it's name is not required len_index = 0 if kwds.get("index_col") is not None: index_col: Any = kwds.get("index_col") if index_col is not False: if not is_list_like(index_col): len_index = 1 else: # for mypy: handled in the if-branch assert index_col is not lib.no_default len_index = len(index_col) if kwds.get("usecols") is None and len(names) + len_index != len(colspecs): # If usecols is used colspec may be longer than names raise ValueError("Length of colspecs must match length of names") check_dtype_backend(kwds.setdefault("dtype_backend", lib.no_default)) return _read( filepath_or_buffer, kwds | { "colspecs": colspecs, "infer_nrows": infer_nrows, "engine": "python-fwf", "iterator": iterator, "chunksize": chunksize, }, )
_Fwf_Defaults
python
ray-project__ray
python/ray/tune/search/sample.py
{ "start": 5189, "end": 5521 }
class ____(Sampler): """Dummy sampler used for grid search""" def sample( self, domain: Domain, config: Optional[Union[List[Dict], Dict]] = None, size: int = 1, random_state: "RandomState" = None, ): return RuntimeError("Do not call `sample()` on grid.") @DeveloperAPI
Grid
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py
{ "start": 88742, "end": 95872 }
class ____(ShopifyBulkQuery): """ { products( query: "updated_at:>='2019-04-13T00:00:00+00:00' AND updated_at:<='2024-04-30T12:16:17.273363+00:00'" sortKey: UPDATED_AT ) { edges { node { __typename id products_updated_at: updatedAt # THE MEDIA NODE IS NEEDED TO PROVIDE THE CURSORS media { edges { node { ... on MediaImage { __typename createdAt updatedAt image { url } } } } } # THIS IS THE MAIN NODE WE WANT TO GET images { edges { node { __typename id height alt: altText src url width } } } } } } } """ query_name = "products" sort_key = "UPDATED_AT" # images property fields images_fields: List[Field] = [ Field( name="edges", fields=[ Field( name="node", fields=[ "__typename", "id", "height", Field(name="altText", alias="alt"), "src", "url", "width", ], ) ], ) ] # media fragment, contains the info about when the Image was created or updated. media_fragment: List[InlineFragment] = [ InlineFragment( type="MediaImage", fields=[ "__typename", "createdAt", "updatedAt", # fetch the `url` as the key for the later join Field(name="image", fields=["url"]), ], ), ] # media property fields media_fields: List[Field] = [Field(name="edges", fields=[Field(name="node", fields=media_fragment)])] nodes: List[Field] = [ "__typename", "id", Field(name="media", fields=media_fields), Field(name="images", fields=images_fields), ] record_composition = { "new_record": "Product", # each product could have `MediaImage` associated with the product, # each product could have `Image` assiciated with the product and the related `MediaImage`, # there could be multiple `MediaImage` and `Image` assigned to the product. "record_components": ["MediaImage", "Image"], } @property def query_nodes(self) -> List[Field]: return self.inject_parent_cursor_field(self.nodes) def _process_component(self, entity: List[dict]) -> List[dict]: for item in entity: # remove the `__parentId` from the object if BULK_PARENT_KEY in item: item.pop(BULK_PARENT_KEY) # resolve the id from string item["admin_graphql_api_id"] = item.get("id") item["id"] = self.tools.resolve_str_id(item.get("id")) return entity def _add_product_id(self, options: List[dict], product_id: Optional[int] = None) -> List[dict]: for option in options: # add product_id to each option option["product_id"] = product_id if product_id else None return options def _merge_with_media(self, record_components: List[dict]) -> Optional[Iterable[MutableMapping[str, Any]]]: media = record_components.get("MediaImage", []) images = record_components.get("Image", []) # Create a dictionary to map the 'url' key in images url_map = {item["url"]: item for item in images} # Merge images with data from media when 'image.url' matches 'url' for item in media: # remove the `__parentId` from Media if BULK_PARENT_KEY in item: item.pop(BULK_PARENT_KEY) image = item.get("image", {}) image_url = image.get("url") if image else None if image_url and image_url in url_map: # Merge images into media item.update(url_map.get(image_url)) # remove lefovers item.pop("image", None) item.pop("url", None) # make the `alt` None, if it's an empty str, since server sends the "" instead of Null alt = item.get("alt") item["alt"] = None if not alt else alt # return merged list of images return media def _convert_datetime_to_rfc3339(self, images: List[dict]) -> MutableMapping[str, Any]: for image in images: image["createdAt"] = self.tools.from_iso8601_to_rfc3339(image, "createdAt") image["updatedAt"] = self.tools.from_iso8601_to_rfc3339(image, "updatedAt") return images def _emit_complete_records(self, images: List[Mapping[str, Any]]) -> Iterable[Mapping[str, Any]]: """ Emit records only if they have the primary_key == `id` field, otherwise the record is not fulfilled and should not be emitted (empty record) Reference issue: https://github.com/airbytehq/airbyte/issues/40700 """ primary_key: str = "id" for record in images: if primary_key in record.keys(): yield record def record_process_components(self, record: MutableMapping[str, Any]) -> Iterable[MutableMapping[str, Any]]: """ Defines how to process collected components. """ # get the joined record components collected for the record record_components = record.get("record_components", {}) # process record components if record_components: record["images"] = self._process_component(record_components.get("Image", [])) # add the product_id to each `Image` record["images"] = self._add_product_id(record.get("images", []), record.get("id")) record["images"] = self._merge_with_media(record_components) record.pop("record_components") # produce images records images = record.get("images", []) if len(images) > 0: # convert dates from ISO-8601 to RFC-3339 record["images"] = self._convert_datetime_to_rfc3339(images) yield from self._emit_complete_records(images)
ProductImage
python
conda__conda
conda/activate.py
{ "start": 36473, "end": 37591 }
class ____(_Activator): pathsep_join = ";".join if on_win else ":".join sep = "/" path_conversion = staticmethod( backslash_to_forwardslash if on_win else _path_identity ) # 'scripts' really refer to de/activation scripts, not scripts in the language per se # xonsh can piggy-back activation scripts from other languages depending on the platform script_extension = ".bat" if on_win else ".sh" tempfile_extension = None # output to stdout command_join = "\n" needs_line_ending_fix = False unset_var_tmpl = "try:\n del $%s\nexcept KeyError:\n pass" export_var_tmpl = "$%s = '%s'" path_var_tmpl = export_var_tmpl set_var_tmpl = export_var_tmpl run_script_tmpl = ( 'source-cmd --suppress-skip-message "%s"' if on_win else 'source-bash --suppress-skip-message -n "%s"' ) hook_source_path = Path(CONDA_PACKAGE_ROOT, "shell", "conda.xsh") inline_hook_source = True def template_path_var(self, key: str, value: str) -> str: return self.path_var_tmpl % (key, self.path_conversion(value))
XonshActivator
python
PyCQA__pylint
tests/test_check_parallel.py
{ "start": 4889, "end": 5093 }
class ____(ParallelTestChecker): """A checker that does need to consolidate data across run invocations.""" name = "extra-parallel-checker" test_data = "extra-parallel"
ExtraParallelTestChecker
python
huggingface__transformers
src/transformers/models/granitemoe/modular_granitemoe.py
{ "start": 1567, "end": 1619 }
class ____(GraniteRMSNorm): pass
GraniteMoeRMSNorm