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
django-haystack__django-haystack
test_haystack/simple_tests/test_simple_backend.py
{ "start": 6848, "end": 8663 }
class ____(TestCase): fixtures = ["base_data.json", "bulk_data.json"] def setUp(self): super().setUp() # Stow. self.old_ui = connections["simple"].get_unified_index() self.ui = UnifiedIndex() self.smmi = SimpleMockSearchIndex() self.ui.build(indexes=[self.smmi]) connections["simple"]._index = self.ui self.sample_objs = MockModel.objects.all() self.sqs = SearchQuerySet(using="simple") def tearDown(self): # Restore. connections["simple"]._index = self.old_ui super().tearDown() def test_general_queries(self): # For now, just make sure these don't throw an exception. # They won't work until the simple backend is improved. self.assertTrue(len(self.sqs.auto_query("daniel")) > 0) self.assertTrue(len(self.sqs.filter(text="index")) > 0) self.assertTrue(len(self.sqs.exclude(name="daniel")) > 0) self.assertTrue(len(self.sqs.order_by("-pub_date")) > 0) def test_general_queries_unicode(self): self.assertEqual(len(self.sqs.auto_query("Привет")), 0) def test_more_like_this(self): # MLT shouldn't be horribly broken. This used to throw an exception. mm1 = MockModel.objects.get(pk=1) self.assertEqual(len(self.sqs.filter(text=1).more_like_this(mm1)), 0) def test_values_queries(self): sqs = self.sqs.auto_query("daniel") self.assertTrue(len(sqs) > 0) flat_scores = sqs.values_list("score", flat=True) self.assertEqual(flat_scores[0], 0) scores = sqs.values_list("id", "score") self.assertEqual(scores[0], [1, 0]) scores_dict = sqs.values("id", "score") self.assertEqual(scores_dict[0], {"id": 1, "score": 0})
LiveSimpleSearchQuerySetTestCase
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 33027, "end": 33383 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("cs_CZ") Faker.seed(0) def test_day(self): day = self.fake.day_of_week() assert day in CsCzProvider.DAY_NAMES.values() def test_month(self): month = self.fake.month_name() assert month in CsCzProvider.MONTH_NAMES.values()
TestCsCz
python
aio-libs__aiohttp
aiohttp/abc.py
{ "start": 1327, "end": 2628 }
class ____(ABC): __slots__ = () @property # pragma: no branch @abstractmethod def handler(self) -> Callable[[Request], Awaitable[StreamResponse]]: """Execute matched request handler""" @property @abstractmethod def expect_handler( self, ) -> Callable[[Request], Awaitable[StreamResponse | None]]: """Expect handler for 100-continue processing""" @property # pragma: no branch @abstractmethod def http_exception(self) -> HTTPException | None: """HTTPException instance raised on router's resolving, or None""" @abstractmethod # pragma: no branch def get_info(self) -> dict[str, Any]: """Return a dict with additional info useful for introspection""" @property # pragma: no branch @abstractmethod def apps(self) -> tuple[Application, ...]: """Stack of nested applications. Top level application is left-most element. """ @abstractmethod def add_app(self, app: Application) -> None: """Add application to the nested apps stack.""" @abstractmethod def freeze(self) -> None: """Freeze the match info. The method is called after route resolution. After the call .add_app() is forbidden. """
AbstractMatchInfo
python
apache__airflow
airflow-core/src/airflow/api_fastapi/common/parameters.py
{ "start": 3100, "end": 3466 }
class ____(BaseParam[NonNegativeInt]): """Filter on the limit.""" def to_orm(self, select: Select) -> Select: if self.value is None and self.skip_none: return select return select.limit(self.value) @classmethod def depends(cls, limit: NonNegativeInt = 50) -> LimitFilter: return cls().set_value(limit)
LimitFilter
python
airbytehq__airbyte
airbyte-integrations/connectors/source-monday/unit_tests/integrations/test_items_stream.py
{ "start": 477, "end": 2133 }
class ____(TestCase): def get_authenticator(self, config): return ApiTokenAuthenticator(api_token=config["credentials"]["api_token"]) @HttpMocker() def test_read_item_record(self, http_mocker): """ A full refresh sync of the items stream without pagination or board filtering """ config = ConfigBuilder().with_api_token_credentials("api-token").build() api_token_authenticator = self.get_authenticator(config) http_mocker.post( ItemsRequestBuilder.items_endpoint(api_token_authenticator).build(), ItemsResponseBuilder.items_response() .with_record(ItemsRecordBuilder.items_record()) .with_record(ItemsRecordBuilder.items_record()) .build(), ) output = read_stream("items", SyncMode.full_refresh, config) assert len(output.records) == 2 @HttpMocker() def test_read_with_board_ids_filter(self, http_mocker): """ A full refresh sync of the items stream with board filtering and without pagination """ board_ids = [123, 456] config = ConfigBuilder().with_api_token_credentials("api-token").with_board_ids(board_ids).build() api_token_authenticator = self.get_authenticator(config) http_mocker.post( ItemsRequestBuilder.items_endpoint(api_token_authenticator, board_ids).build(), ItemsResponseBuilder.items_response().with_record(ItemsRecordBuilder.items_record()).build(), ) output = read_stream("items", SyncMode.full_refresh, config) assert len(output.records) == 1
TestItemsStreamFullRefresh
python
ray-project__ray
python/ray/data/_internal/streaming_repartition.py
{ "start": 2174, "end": 5409 }
class ____(BaseRefBundler): """Incrementally builds task inputs to produce multiples of target-sized outputs.""" def __init__(self, target_num_rows_per_block: int): assert ( target_num_rows_per_block > 0 ), "target_num_rows_per_block must be positive for streaming repartition." self._target_num_rows = target_num_rows_per_block self._pending_bundles: Deque[RefBundle] = deque() self._ready_bundles: Deque[RefBundle] = deque() self._consumed_input_bundles: List[RefBundle] = [] self._total_pending_rows = 0 def _try_build_ready_bundle(self, flush_remaining: bool = False): if self._total_pending_rows >= self._target_num_rows: rows_needed_from_last_bundle = ( self._pending_bundles[-1].num_rows() - self._total_pending_rows % self._target_num_rows ) assert rows_needed_from_last_bundle >= 0 # This will never be negative pending_bundles = list(self._pending_bundles) remaining_bundle = None if ( rows_needed_from_last_bundle > 0 and rows_needed_from_last_bundle < pending_bundles[-1].num_rows() ): last_bundle = pending_bundles.pop() sliced_bundle, remaining_bundle = last_bundle.slice( rows_needed_from_last_bundle ) pending_bundles.append(sliced_bundle) self._ready_bundles.append(RefBundle.merge_ref_bundles(pending_bundles)) self._pending_bundles.clear() self._total_pending_rows = 0 if remaining_bundle and remaining_bundle.num_rows() > 0: self._pending_bundles.append(remaining_bundle) self._total_pending_rows += remaining_bundle.num_rows() if flush_remaining and self._total_pending_rows > 0: self._ready_bundles.append( RefBundle.merge_ref_bundles(self._pending_bundles) ) self._pending_bundles.clear() self._total_pending_rows = 0 def add_bundle(self, ref_bundle: RefBundle): self._total_pending_rows += ref_bundle.num_rows() self._pending_bundles.append(ref_bundle) self._try_build_ready_bundle() self._consumed_input_bundles.append(ref_bundle) def has_bundle(self) -> bool: return len(self._ready_bundles) > 0 def get_next_bundle( self, ) -> Tuple[List[RefBundle], RefBundle]: consumed_input_bundles = self._consumed_input_bundles self._consumed_input_bundles = [] return consumed_input_bundles, self._ready_bundles.popleft() def done_adding_bundles(self): if len(self._pending_bundles) > 0: self._try_build_ready_bundle(flush_remaining=True) def num_blocks(self): return sum(len(bundle) for bundle in self._pending_bundles) + sum( len(bundle) for bundle in self._ready_bundles ) def size_bytes(self) -> int: return sum(bundle.size_bytes() for bundle in self._pending_bundles) + sum( bundle.size_bytes() for bundle in self._ready_bundles )
StreamingRepartitionRefBundler
python
openai__openai-python
src/openai/types/beta/realtime/session_create_response.py
{ "start": 392, "end": 797 }
class ____(BaseModel): expires_at: int """Timestamp for when the token expires. Currently, all tokens expire after one minute. """ value: str """ Ephemeral key usable in client environments to authenticate connections to the Realtime API. Use this in client-side environments rather than a standard API token, which should only be used server-side. """
ClientSecret
python
walkccc__LeetCode
solutions/3273. Minimum Amount of Damage Dealt to Bob/3273.py
{ "start": 110, "end": 1011 }
class ____: def minDamage(self, power: int, damage: list[int], health: list[int]) -> int: ans = 0 sumDamage = sum(damage) enemies = [Enemy(d, (h + power - 1) // power) for d, h in zip(damage, health)] # It's better to take down the enemy i first if the damage dealt of taking # down i first is less than the damage dealt of taking down j first. So, # damage[i] * t[i] + (t[i] + t[j]) * damage[j] < # damage[j] * t[j] + (t[i] + t[j]) * damage[i] # => damage[i] * t[i] + damage[j] * t[i] + damage[j] * t[j] < # damage[j] * t[j] + damage[i] * t[j] + damage[i] * t[i] # => damage[j] * t[i] < damage[i] * t[j] # => damage[j] / t[j] < damage[i] / t[i] enemies.sort(key=lambda x: -x.damage / x.timeTakenDown) for enemy in enemies: ans += sumDamage * enemy.timeTakenDown sumDamage -= enemy.damage return ans
Solution
python
allegroai__clearml
clearml/backend_api/services/v2_23/projects.py
{ "start": 95943, "end": 99427 }
class ____(Request): """ Get a list of all metadata keys used in models within the given project. :param project: Project ID :type project: str :param include_subprojects: If set to 'true' and the project field is set then the result includes metadate keys from the subproject models :type include_subprojects: bool :param page: Page number :type page: int :param page_size: Page size :type page_size: int """ _service = "projects" _action = "get_model_metadata_keys" _version = "2.23" _schema = { "definitions": {}, "properties": { "include_subprojects": { "default": True, "description": "If set to 'true' and the project field is set then the result includes metadate keys from the subproject models", "type": "boolean", }, "page": {"default": 0, "description": "Page number", "type": "integer"}, "page_size": { "default": 500, "description": "Page size", "type": "integer", }, "project": {"description": "Project ID", "type": "string"}, }, "required": ["project"], "type": "object", } def __init__( self, project: str, include_subprojects: Optional[bool] = True, page: Optional[int] = 0, page_size: Optional[int] = 500, **kwargs: Any ) -> None: super(GetModelMetadataKeysRequest, self).__init__(**kwargs) self.project = project self.include_subprojects = include_subprojects self.page = page self.page_size = page_size @schema_property("project") def project(self) -> str: return self._property_project @project.setter def project(self, value: str) -> None: if value is None: self._property_project = None return self.assert_isinstance(value, "project", six.string_types) self._property_project = value @schema_property("include_subprojects") def include_subprojects(self) -> Optional[bool]: return self._property_include_subprojects @include_subprojects.setter def include_subprojects(self, value: Optional[bool]) -> None: if value is None: self._property_include_subprojects = None return self.assert_isinstance(value, "include_subprojects", (bool,)) self._property_include_subprojects = value @schema_property("page") def page(self) -> Optional[int]: return self._property_page @page.setter def page(self, value: Optional[int]) -> None: if value is None: self._property_page = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "page", six.integer_types) self._property_page = value @schema_property("page_size") def page_size(self) -> Optional[int]: return self._property_page_size @page_size.setter def page_size(self, value: Optional[int]) -> None: if value is None: self._property_page_size = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "page_size", six.integer_types) self._property_page_size = value
GetModelMetadataKeysRequest
python
ray-project__ray
rllib/algorithms/tests/test_algorithm_export_checkpoint.py
{ "start": 2702, "end": 3106 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls) -> None: ray.init(num_cpus=4) @classmethod def tearDownClass(cls) -> None: ray.shutdown() def test_save_appo_multi_agent(self): save_test("APPO", "torch", multi_agent=True) if __name__ == "__main__": import sys import pytest sys.exit(pytest.main(["-v", __file__]))
TestAlgorithmSave
python
numpy__numpy
numpy/_core/tests/test_strings.py
{ "start": 54251, "end": 54803 }
class ____: def test_isdecimal_raises(self): in_ = np.array(b"1") with assert_raises(TypeError): np.strings.isdecimal(in_) def test_isnumeric_bytes(self): in_ = np.array(b"1") with assert_raises(TypeError): np.strings.isnumeric(in_) def check_itemsize(n_elem, dt): if dt == "T": return np.dtype(dt).itemsize if dt == "S": return n_elem if dt == "U": return n_elem * 4 @pytest.mark.parametrize("dt", ["S", "U", "T"])
TestUnicodeOnlyMethodsRaiseWithBytes
python
django__django
django/db/models/lookups.py
{ "start": 17312, "end": 17465 }
class ____(IntegerFieldOverflow, IntegerFieldFloatRounding, LessThan): overflow_exception = FullResultSet @IntegerField.register_lookup
IntegerLessThan
python
pytorch__pytorch
torch/distributed/elastic/rendezvous/etcd_rendezvous_backend.py
{ "start": 740, "end": 7348 }
class ____(RendezvousBackend): """Represents an etcd-based rendezvous backend. Args: client: The ``etcd.Client`` instance to use to communicate with etcd. run_id: The run id of the rendezvous. key_prefix: The path under which to store the rendezvous state in etcd. ttl: The TTL of the rendezvous state. If not specified, defaults to two hours. """ _DEFAULT_TTL = 7200 # 2 hours _client: etcd.Client _key: str _ttl: int def __init__( self, client: etcd.Client, run_id: str, key_prefix: str | None = None, ttl: int | None = None, ) -> None: if not run_id: raise ValueError("The run id must be a non-empty string.") self._client = client if key_prefix: self._key = key_prefix + "/" + run_id else: self._key = run_id if ttl and ttl > 0: self._ttl = ttl else: self._ttl = self._DEFAULT_TTL @property def name(self) -> str: """See base class.""" return "etcd-v2" def get_state(self) -> tuple[bytes, Token] | None: """See base class.""" try: result = self._client.read(self._key) except etcd.EtcdKeyNotFound: return None except (etcd.EtcdException, urllib3.exceptions.TimeoutError) as exc: raise RendezvousConnectionError( "The connection to etcd has failed. See inner exception for details." ) from exc return self._decode_state(result) def set_state( self, state: bytes, token: Token | None = None ) -> tuple[bytes, Token, bool] | None: """See base class.""" base64_state = b64encode(state).decode() kwargs = {} def get_state(): result = self.get_state() if result is not None: return *result, False return None if token: try: token = int(token) except ValueError: return get_state() if token: kwargs["prevIndex"] = token else: kwargs["prevExist"] = False try: result = self._client.write(self._key, base64_state, self._ttl, **kwargs) except (etcd.EtcdAlreadyExist, etcd.EtcdCompareFailed): result = None except (etcd.EtcdException, urllib3.exceptions.TimeoutError) as exc: raise RendezvousConnectionError( "The connection to etcd has failed. See inner exception for details." ) from exc if result is None: return get_state() tmp = *self._decode_state(result), True return tmp def _decode_state(self, result: etcd.EtcdResult) -> tuple[bytes, Token]: # pyrefly: ignore [missing-attribute] base64_state = result.value.encode() try: state = b64decode(base64_state) except binascii.Error as exc: raise RendezvousStateError( "The state object is corrupt. See inner exception for details." ) from exc # pyrefly: ignore [missing-attribute] return state, result.modifiedIndex def _create_etcd_client(params: RendezvousParameters) -> etcd.Client: host, port = parse_rendezvous_endpoint(params.endpoint, default_port=2379) # The timeout read_timeout = cast(int, params.get_as_int("read_timeout", 60)) if read_timeout <= 0: raise ValueError("The read timeout must be a positive integer.") # The communication protocol protocol = params.get("protocol", "http").strip().lower() if protocol != "http" and protocol != "https": raise ValueError("The protocol must be HTTP or HTTPS.") # The SSL client certificate ssl_cert = params.get("ssl_cert") if ssl_cert: ssl_cert_key = params.get("ssl_cert_key") if ssl_cert_key: # The etcd client expects the certificate key as the second element # of the `cert` tuple. ssl_cert = (ssl_cert, ssl_cert_key) # The root certificate ca_cert = params.get("ca_cert") try: return etcd.Client( host, port, read_timeout=read_timeout, protocol=protocol, cert=ssl_cert, ca_cert=ca_cert, allow_reconnect=True, ) except (etcd.EtcdException, urllib3.exceptions.TimeoutError) as exc: raise RendezvousConnectionError( "The connection to etcd has failed. See inner exception for details." ) from exc def create_backend(params: RendezvousParameters) -> tuple[EtcdRendezvousBackend, Store]: """Create a new :py:class:`EtcdRendezvousBackend` from the specified parameters. +--------------+-----------------------------------------------------------+ | Parameter | Description | +==============+===========================================================+ | read_timeout | The read timeout, in seconds, for etcd operations. | | | Defaults to 60 seconds. | +--------------+-----------------------------------------------------------+ | protocol | The protocol to use to communicate with etcd. Valid | | | values are "http" and "https". Defaults to "http". | +--------------+-----------------------------------------------------------+ | ssl_cert | The path to the SSL client certificate to use along with | | | HTTPS. Defaults to ``None``. | +--------------+-----------------------------------------------------------+ | ssl_cert_key | The path to the private key of the SSL client certificate | | | to use along with HTTPS. Defaults to ``None``. | +--------------+-----------------------------------------------------------+ | ca_cert | The path to the rool SSL authority certificate. Defaults | | | to ``None``. | +--------------+-----------------------------------------------------------+ """ client = _create_etcd_client(params) backend = EtcdRendezvousBackend( client, params.run_id, key_prefix="/torch/elastic/rendezvous" ) store = EtcdStore(client, "/torch/elastic/store") return backend, store
EtcdRendezvousBackend
python
etianen__django-reversion
tests/test_app/tests/test_models.py
{ "start": 9408, "end": 9847 }
class ____(TestModelMixin, TestBase): databases = {"default", "postgres"} def testGetDeletedModelDb(self): with reversion.create_revision(): obj = TestModel.objects.db_manager("postgres").create() obj.delete() self.assertEqual(Version.objects.get_deleted(TestModel).count(), 0) self.assertEqual(Version.objects.get_deleted(TestModel, model_db="postgres").count(), 1)
GetDeletedModelDbTest
python
apache__airflow
providers/google/src/airflow/providers/google/suite/hooks/drive.py
{ "start": 1187, "end": 12637 }
class ____(GoogleBaseHook): """ Hook for the Google Drive APIs. :param api_version: API version used (for example v3). :param gcp_conn_id: The connection ID to use when fetching connection info. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account. """ _conn: Resource | None = None def __init__( self, api_version: str = "v3", gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, ) -> None: super().__init__( gcp_conn_id=gcp_conn_id, impersonation_chain=impersonation_chain, ) self.api_version = api_version def get_conn(self) -> Any: """ Retrieve the connection to Google Drive. :return: Google Drive services object. """ if not self._conn: http_authorized = self._authorize() self._conn = build("drive", self.api_version, http=http_authorized, cache_discovery=False) return self._conn def _ensure_folders_exists(self, path: str, folder_id: str) -> str: service = self.get_conn() current_parent = folder_id folders = path.split("/") depth = 0 # First tries to enter directories for current_folder in folders: self.log.debug("Looking for %s directory with %s parent", current_folder, current_parent) conditions = [ "trashed=false", "mimeType='application/vnd.google-apps.folder'", f"name='{current_folder}'", f"'{current_parent}' in parents", ] result = ( service.files() .list( q=" and ".join(conditions), spaces="drive", fields="files(id, name)", includeItemsFromAllDrives=True, supportsAllDrives=True, ) .execute(num_retries=self.num_retries) ) files = result.get("files", []) if not files: self.log.info("Not found %s directory", current_folder) # If the directory does not exist, break loops break depth += 1 current_parent = files[0].get("id") # Check if there are directories to process if depth != len(folders): # Create missing directories for current_folder in folders[depth:]: file_metadata = { "name": current_folder, "mimeType": "application/vnd.google-apps.folder", "parents": [current_parent], } file = ( service.files() .create( body=file_metadata, fields="id", supportsAllDrives=True, ) .execute(num_retries=self.num_retries) ) self.log.info("Created %s directory", current_folder) current_parent = file.get("id") # Return the ID of the last directory return current_parent def get_media_request(self, file_id: str) -> HttpRequest: """ Return a get_media http request to a Google Drive object. :param file_id: The Google Drive file id :return: request """ service = self.get_conn() request = service.files().get_media(fileId=file_id) return request def exists( self, folder_id: str, file_name: str, drive_id: str | None = None, *, include_trashed: bool = True ) -> bool: """ Check to see if a file exists within a Google Drive folder. :param folder_id: The id of the Google Drive folder in which the file resides :param file_name: The name of a file in Google Drive :param drive_id: Optional. The id of the shared Google Drive in which the file resides. :param include_trashed: Whether to include objects in trash or not, default True as in Google API. :return: True if the file exists, False otherwise """ return bool( self.get_file_id( folder_id=folder_id, file_name=file_name, include_trashed=include_trashed, drive_id=drive_id ) ) def _get_file_info(self, file_id: str): """ Return Google API file_info object containing id, name, parents in the response. https://developers.google.com/drive/api/v3/reference/files/get :param file_id: id as string representation of interested file :return: file """ file_info = ( self.get_conn() .files() .get( fileId=file_id, fields="id,name,parents", supportsAllDrives=True, ) .execute(num_retries=2) ) return file_info def _resolve_file_path(self, file_id: str) -> str: """ Return the full Google Drive path for given file_id. :param file_id: The id of a file in Google Drive :return: Google Drive full path for a file """ has_reached_root = False current_file_id = file_id path: str = "" while not has_reached_root: # current_file_id can be file or directory id, Google API treats them the same way. file_info = self._get_file_info(current_file_id) if current_file_id == file_id: path = f"{file_info['name']}" else: path = f"{file_info['name']}/{path}" # Google API returns parents array if there is at least one object inside if "parents" in file_info and len(file_info["parents"]) == 1: # https://developers.google.com/drive/api/guides/ref-single-parent current_file_id = file_info["parents"][0] else: has_reached_root = True return path def get_file_id( self, folder_id: str, file_name: str, drive_id: str | None = None, *, include_trashed: bool = True ) -> dict: """ Return the file id of a Google Drive file. :param folder_id: The id of the Google Drive folder in which the file resides :param file_name: The name of a file in Google Drive :param drive_id: Optional. The id of the shared Google Drive in which the file resides. :param include_trashed: Whether to include objects in trash or not, default True as in Google API. :return: Google Drive file id if the file exists, otherwise None """ query = f"name = '{file_name}'" if folder_id: query += f" and parents in '{folder_id}'" if not include_trashed: query += " and trashed=false" service = self.get_conn() if drive_id: files = ( service.files() .list( q=query, spaces="drive", fields="files(id, mimeType)", orderBy="modifiedTime desc", driveId=drive_id, includeItemsFromAllDrives=True, supportsAllDrives=True, corpora="drive", ) .execute(num_retries=self.num_retries) ) else: files = ( service.files() .list(q=query, spaces="drive", fields="files(id, mimeType)", orderBy="modifiedTime desc") .execute(num_retries=self.num_retries) ) file_metadata = {} if files["files"]: file_metadata = {"id": files["files"][0]["id"], "mime_type": files["files"][0]["mimeType"]} return file_metadata def upload_file( self, local_location: str, remote_location: str, chunk_size: int = 100 * 1024 * 1024, resumable: bool = False, folder_id: str = "root", show_full_target_path: bool = True, ) -> str: """ Upload a file that is available locally to a Google Drive service. :param local_location: The path where the file is available. :param remote_location: The path where the file will be send :param chunk_size: File will be uploaded in chunks of this many bytes. Only used if resumable=True. Pass in a value of -1 if the file is to be uploaded as a single chunk. Note that Google App Engine has a 5MB limit on request size, so you should never set your chunk size larger than 5MB, or to -1. :param resumable: True if this is a resumable upload. False means upload in a single request. :param folder_id: The base/root folder id for remote_location (part of the drive URL of a folder). :param show_full_target_path: If true then it reveals full available file path in the logs. :return: File ID """ service = self.get_conn() directory_path, _, file_name = remote_location.rpartition("/") if directory_path: parent = self._ensure_folders_exists(path=directory_path, folder_id=folder_id) else: parent = folder_id file_metadata = {"name": file_name, "parents": [parent]} media = MediaFileUpload(local_location, chunksize=chunk_size, resumable=resumable) file = ( service.files() .create(body=file_metadata, media_body=media, fields="id", supportsAllDrives=True) .execute(num_retries=self.num_retries) ) file_id = file.get("id") upload_location = remote_location if folder_id != "root": try: upload_location = self._resolve_file_path(folder_id) except GoogleApiClientError as e: self.log.warning("A problem has been encountered when trying to resolve file path: ", e) if show_full_target_path: self.log.info("File %s uploaded to gdrive://%s.", local_location, upload_location) else: self.log.info("File %s has been uploaded successfully to gdrive", local_location) return file_id def download_file(self, file_id: str, file_handle: IO, chunk_size: int = 100 * 1024 * 1024): """ Download a file from Google Drive. :param file_id: the id of the file :param file_handle: file handle used to write the content to :param chunk_size: File will be downloaded in chunks of this many bytes. """ request = self.get_media_request(file_id=file_id) self.download_content_from_request(file_handle=file_handle, request=request, chunk_size=chunk_size)
GoogleDriveHook
python
facelessuser__soupsieve
soupsieve/css_parser.py
{ "start": 9065, "end": 9547 }
class ____: """Selector pattern.""" def __init__(self, name: str, pattern: str) -> None: """Initialize.""" self.name = name self.re_pattern = re.compile(pattern, re.I | re.X | re.U) def get_name(self) -> str: """Get name.""" return self.name def match(self, selector: str, index: int, flags: int) -> Match[str] | None: """Match the selector.""" return self.re_pattern.match(selector, index)
SelectorPattern
python
pypa__warehouse
warehouse/errors.py
{ "start": 77, "end": 271 }
class ____(Denied): def __new__(cls, s, *args, reason=None, **kwargs): inner = super().__new__(cls, s, *args, **kwargs) inner.reason = reason return inner
WarehouseDenied
python
kubernetes-client__python
kubernetes/client/models/v1beta1_device_claim_configuration.py
{ "start": 383, "end": 5016 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'opaque': 'V1beta1OpaqueDeviceConfiguration', 'requests': 'list[str]' } attribute_map = { 'opaque': 'opaque', 'requests': 'requests' } def __init__(self, opaque=None, requests=None, local_vars_configuration=None): # noqa: E501 """V1beta1DeviceClaimConfiguration - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._opaque = None self._requests = None self.discriminator = None if opaque is not None: self.opaque = opaque if requests is not None: self.requests = requests @property def opaque(self): """Gets the opaque of this V1beta1DeviceClaimConfiguration. # noqa: E501 :return: The opaque of this V1beta1DeviceClaimConfiguration. # noqa: E501 :rtype: V1beta1OpaqueDeviceConfiguration """ return self._opaque @opaque.setter def opaque(self, opaque): """Sets the opaque of this V1beta1DeviceClaimConfiguration. :param opaque: The opaque of this V1beta1DeviceClaimConfiguration. # noqa: E501 :type: V1beta1OpaqueDeviceConfiguration """ self._opaque = opaque @property def requests(self): """Gets the requests of this V1beta1DeviceClaimConfiguration. # noqa: E501 Requests lists the names of requests where the configuration applies. If empty, it applies to all requests. References to subrequests must include the name of the main request and may include the subrequest using the format <main request>[/<subrequest>]. If just the main request is given, the configuration applies to all subrequests. # noqa: E501 :return: The requests of this V1beta1DeviceClaimConfiguration. # noqa: E501 :rtype: list[str] """ return self._requests @requests.setter def requests(self, requests): """Sets the requests of this V1beta1DeviceClaimConfiguration. Requests lists the names of requests where the configuration applies. If empty, it applies to all requests. References to subrequests must include the name of the main request and may include the subrequest using the format <main request>[/<subrequest>]. If just the main request is given, the configuration applies to all subrequests. # noqa: E501 :param requests: The requests of this V1beta1DeviceClaimConfiguration. # noqa: E501 :type: list[str] """ self._requests = requests def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1beta1DeviceClaimConfiguration): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1beta1DeviceClaimConfiguration): return True return self.to_dict() != other.to_dict()
V1beta1DeviceClaimConfiguration
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/backfills.py
{ "start": 1388, "end": 1840 }
class ____(BaseModel): """Base serializer for Backfill.""" id: NonNegativeInt dag_id: str from_date: datetime to_date: datetime dag_run_conf: dict is_paused: bool reprocess_behavior: ReprocessBehavior max_active_runs: int created_at: datetime completed_at: datetime | None updated_at: datetime dag_display_name: str = Field(validation_alias=AliasPath("dag_model", "dag_display_name"))
BackfillResponse
python
bokeh__bokeh
src/bokeh/events.py
{ "start": 21768, "end": 22244 }
class ____(PointEvent): ''' Announce the end of a pinch event on a Bokeh plot. Attributes: sx (float) : x-coordinate of the event in *screen* space sy (float) : y-coordinate of the event in *screen* space x (float) : x-coordinate of the event in *data* space y (float) : y-coordinate of the event in *data* space .. note:: This event is only applicable for touch-enabled devices. ''' event_name = 'pinchend'
PinchEnd
python
PrefectHQ__prefect
tests/deployment/test_steps.py
{ "start": 26755, "end": 37888 }
class ____: async def test_git_clone(self, git_repository_mock): output = await run_step( { "prefect.deployments.steps.git_clone": { "repository": "https://github.com/org/repo.git", } } ) assert output["directory"] == "repo" git_repository_mock.assert_called_once_with( url="https://github.com/org/repo.git", credentials=None, branch=None, commit_sha=None, include_submodules=False, directories=None, ) git_repository_mock.return_value.pull_code.assert_awaited_once() async def test_git_clone_include_submodules(self, git_repository_mock): output = await run_step( { "prefect.deployments.steps.git_clone": { "repository": "https://github.com/org/has-submodules.git", "include_submodules": True, } } ) assert output["directory"] == "repo" git_repository_mock.assert_called_once_with( url="https://github.com/org/has-submodules.git", credentials=None, branch=None, commit_sha=None, include_submodules=True, directories=None, ) git_repository_mock.return_value.pull_code.assert_awaited_once() async def test_git_clone_with_access_token(self, git_repository_mock): await Secret(value="my-access-token").save(name="my-access-token") await run_step( { "prefect.deployments.steps.git_clone": { "repository": "https://github.com/org/repo.git", "access_token": "{{ prefect.blocks.secret.my-access-token }}", } } ) git_repository_mock.assert_called_once_with( url="https://github.com/org/repo.git", credentials={"access_token": "my-access-token"}, branch=None, commit_sha=None, include_submodules=False, directories=None, ) git_repository_mock.return_value.pull_code.assert_awaited_once() async def test_git_clone_with_credentials(self, git_repository_mock): class MockGitCredentials(Block): username: str password: str await MockGitCredentials(username="marvin42", password="hunter2").save( name="my-credentials" ) await run_step( { "prefect.deployments.steps.git_clone": { "repository": "https://github.com/org/repo.git", "credentials": ( "{{ prefect.blocks.mockgitcredentials.my-credentials }}" ), } } ) git_repository_mock.assert_called_once_with( url="https://github.com/org/repo.git", credentials={"username": "marvin42", "password": "hunter2"}, branch=None, commit_sha=None, include_submodules=False, directories=None, ) git_repository_mock.return_value.pull_code.assert_awaited_once() async def test_git_clone_retry(self, monkeypatch, caplog): mock_git_repo = MagicMock() mock_git_repo.return_value.pull_code = AsyncMock( side_effect=[ RuntimeError("Octocat went out to lunch"), RuntimeError("Octocat is playing chess in the break room"), None, # Successful on third attempt ] ) mock_git_repo.return_value.destination.relative_to.return_value = "repo" monkeypatch.setattr( "prefect.deployments.steps.pull.GitRepository", mock_git_repo ) async def mock_sleep(seconds): pass monkeypatch.setattr("asyncio.sleep", mock_sleep) with caplog.at_level("WARNING"): result = await agit_clone(repository="https://github.com/org/repo.git") assert "Octocat went out to lunch" in caplog.text assert "Octocat is playing chess in the break room" in caplog.text assert result == {"directory": "repo"} expected_call = call( url="https://github.com/org/repo.git", credentials=None, branch=None, commit_sha=None, include_submodules=False, directories=None, ) assert mock_git_repo.call_args_list == [expected_call] async def test_git_clone_with_commit_sha(self, git_repository_mock): output = await agit_clone( repository="https://github.com/org/repo.git", commit_sha="1234567890", ) assert output["directory"] == "repo" git_repository_mock.assert_called_once_with( url="https://github.com/org/repo.git", credentials=None, branch=None, commit_sha="1234567890", include_submodules=False, directories=None, ) git_repository_mock.return_value.pull_code.assert_awaited_once() async def test_agit_clone_basic(self, git_repository_mock): """Test basic async git clone functionality""" output = await agit_clone(repository="https://github.com/org/repo.git") assert output["directory"] == "repo" git_repository_mock.assert_called_once_with( url="https://github.com/org/repo.git", credentials=None, branch=None, commit_sha=None, include_submodules=False, directories=None, ) git_repository_mock.return_value.pull_code.assert_awaited_once() async def test_agit_clone_with_all_options(self, git_repository_mock): """Test async git clone with all options specified""" await Secret(value="my-access-token").save(name="test-token") output = await agit_clone( repository="https://github.com/org/repo.git", branch="dev", include_submodules=True, access_token="my-access-token", directories=None, ) assert output["directory"] == "repo" git_repository_mock.assert_called_once_with( url="https://github.com/org/repo.git", credentials={"access_token": "my-access-token"}, branch="dev", commit_sha=None, include_submodules=True, directories=None, ) git_repository_mock.return_value.pull_code.assert_awaited_once() async def test_agit_clone_with_credentials_block(self, git_repository_mock): """Test async git clone with credentials block""" class MockGitCredentials(Block): username: str password: str creds = MockGitCredentials(username="marvin42", password="hunter2") output = await agit_clone( repository="https://github.com/org/repo.git", credentials=creds ) assert output["directory"] == "repo" git_repository_mock.assert_called_once_with( url="https://github.com/org/repo.git", credentials=creds, branch=None, commit_sha=None, include_submodules=False, directories=None, ) git_repository_mock.return_value.pull_code.assert_awaited_once() async def test_agit_clone_raises_on_both_auth_methods(self): """Test that providing both access_token and credentials raises an error""" with pytest.raises( ValueError, match="Please provide either an access token or credentials but not both", ): await agit_clone( repository="https://github.com/org/repo.git", access_token="token", credentials=MagicMock(), ) async def test_agit_clone_retry(self, monkeypatch, caplog): """Test retry behavior of async git clone""" mock_git_repo = MagicMock() mock_git_repo.return_value.pull_code = AsyncMock( side_effect=[ RuntimeError("Network timeout"), RuntimeError("Server busy"), None, # Success on third try ] ) mock_git_repo.return_value.destination.relative_to.return_value = "repo" monkeypatch.setattr( "prefect.deployments.steps.pull.GitRepository", mock_git_repo ) async def mock_sleep(seconds): pass monkeypatch.setattr("asyncio.sleep", mock_sleep) with caplog.at_level("WARNING"): result = await agit_clone(repository="https://github.com/org/repo.git") assert result == {"directory": "repo"} assert mock_git_repo.return_value.pull_code.await_count == 3 assert "Network timeout" in caplog.text assert "Server busy" in caplog.text async def test_agit_clone_with_commit_sha(self, git_repository_mock): output = await agit_clone( repository="https://github.com/org/repo.git", commit_sha="1234567890", ) assert output["directory"] == "repo" git_repository_mock.assert_called_once_with( url="https://github.com/org/repo.git", credentials=None, branch=None, commit_sha="1234567890", include_submodules=False, directories=None, ) git_repository_mock.return_value.pull_code.assert_awaited_once() async def test_agit_clone_via_steps(self, monkeypatch, caplog): """Test that async-only steps work when called via step syntax""" mock_git_repo = MagicMock() mock_git_repo.return_value.pull_code = AsyncMock( side_effect=[ RuntimeError("Network timeout"), RuntimeError("Server busy"), None, # Success on third try ] ) mock_git_repo.return_value.destination.relative_to.return_value = "repo" monkeypatch.setattr( "prefect.deployments.steps.pull.GitRepository", mock_git_repo ) async def mock_sleep(seconds): pass monkeypatch.setattr("asyncio.sleep", mock_sleep) with caplog.at_level("WARNING"): result = await run_step( { "prefect.deployments.steps.pull.agit_clone": { "repository": "https://github.com/org/repo.git" } } ) assert result == {"directory": "repo"} assert mock_git_repo.return_value.pull_code.await_count == 3 assert "Network timeout" in caplog.text assert "Server busy" in caplog.text expected_call = call( url="https://github.com/org/repo.git", credentials=None, branch=None, commit_sha=None, include_submodules=False, directories=None, ) assert mock_git_repo.call_args_list == [expected_call]
TestGitCloneStep
python
pytorch__pytorch
test/test_utils.py
{ "start": 28732, "end": 29182 }
class ____(TestCase): def test_basic(self): self.assertExpectedInline( torch._utils.render_call(torch.sum, [torch.randn(100)], {"dim": 0}), """torch.sum(tensor([...], size=(100,)), dim=0)""", ) self.assertExpectedInline( torch._utils.render_call(torch.sum, [torch.randn(100, 100)], {"dim": 0}), """torch.sum(tensor([...], size=(100, 100)), dim=0)""", )
TestRenderUtils
python
huggingface__transformers
src/transformers/models/mamba/configuration_mamba.py
{ "start": 768, "end": 7433 }
class ____(PreTrainedConfig): """ This is the configuration class to store the configuration of a [`MambaModel`]. It is used to instantiate a MAMBA model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the MAMBA [state-spaces/mamba-2.8b](https://huggingface.co/state-spaces/mamba-2.8b) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 50280): Vocabulary size of the MAMBA model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`MambaModel`]. hidden_size (`int`, *optional*, defaults to 768): Dimensionality of the embeddings and hidden states. state_size (`int`, *optional*, defaults to 16): shape of the state space latents. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the model. layer_norm_epsilon (`float`, *optional*, defaults to 1e-05): The epsilon to use in the layer normalization layers. pad_token_id (`int`, *optional*, defaults to 0): Padding token id. bos_token_id (`int`, *optional*, defaults to 0): The id of the beginning of sentence token in the vocabulary. eos_token_id (`int`, *optional*, defaults to 0): The id of the end of sentence token in the vocabulary. expand (`int`, *optional*, defaults to 2): Expanding factor used to determine the intermediate size. conv_kernel (`int`, *optional*, defaults to 4): Size of the convolution kernel. use_bias (`bool`, *optional*, defaults to `False`): Whether or not to use bias in ["in_proj", "out_proj"] of the mixer block use_conv_bias (`bool`, *optional*, defaults to `True`): Whether or not to use bias in the convolution layer of the mixer block. hidden_act (`str`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. initializer_range (`float`, *optional*, defaults to 0.1): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. residual_in_fp32 (`bool`, *optional*, defaults to `True`): Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model time_step_rank (`Union[int,str]`, *optional*, defaults to `"auto"`): Rank of the discretization projection matrix. `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)` time_step_scale (`float`, *optional*, defaults to 1.0): Scale used used to scale `dt_proj.bias`. time_step_min (`float`, *optional*, defaults to 0.001): Minimum `time_step` used to bound `dt_proj.bias`. time_step_max (`float`, *optional*, defaults to 0.1): Maximum `time_step` used to bound `dt_proj.bias`. time_step_init_scheme (`float`, *optional*, defaults to `"random"`): Init scheme used for `dt_proj.weight`. Should be one of `["random","uniform"]` time_step_floor (`float`, *optional*, defaults to 0.0001): Minimum clamping value of the `dt_proj.bias` layer initialization. rescale_prenorm_residual (`bool`, *optional*, defaults to `False`): Whether or not to rescale `out_proj` weights when initializing. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the cache should be used. use_mambapy (`bool`, *optional*, defaults to `False`): Determines the fallback strategy during training if the CUDA-based official implementation of Mamba is not available. If `True`, the mamba.py implementation is used. If `False`, the naive and slower implementation is used. Consider switching to the naive version if memory is limited. Example: ```python >>> from transformers import MambaConfig, MambaModel >>> # Initializing a Mamba configuration >>> configuration = MambaConfig() >>> # Initializing a model (with random weights) from the configuration >>> model = MambaModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "mamba" def __init__( self, vocab_size=50280, hidden_size=768, state_size=16, num_hidden_layers=32, layer_norm_epsilon=1e-5, pad_token_id=0, bos_token_id=0, eos_token_id=0, expand=2, conv_kernel=4, use_bias=False, use_conv_bias=True, hidden_act="silu", initializer_range=0.1, residual_in_fp32=True, time_step_rank="auto", time_step_scale=1.0, time_step_min=0.001, time_step_max=0.1, time_step_init_scheme="random", time_step_floor=1e-4, rescale_prenorm_residual=False, use_cache=True, use_mambapy=False, **kwargs, ): self.vocab_size = vocab_size self.hidden_size = hidden_size self.state_size = state_size self.num_hidden_layers = num_hidden_layers self.layer_norm_epsilon = layer_norm_epsilon self.conv_kernel = conv_kernel self.expand = expand self.intermediate_size = int(expand * self.hidden_size) self.bos_token_id = bos_token_id self.eos_token_id = eos_token_id self.pad_token_id = pad_token_id self.use_bias = use_bias self.use_conv_bias = use_conv_bias self.hidden_act = hidden_act self.initializer_range = initializer_range self.time_step_rank = math.ceil(self.hidden_size / 16) if time_step_rank == "auto" else time_step_rank self.time_step_scale = time_step_scale self.time_step_min = time_step_min self.time_step_max = time_step_max self.time_step_init_scheme = time_step_init_scheme self.time_step_floor = time_step_floor self.rescale_prenorm_residual = rescale_prenorm_residual self.residual_in_fp32 = residual_in_fp32 self.use_cache = use_cache self.use_mambapy = use_mambapy super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs) __all__ = ["MambaConfig"]
MambaConfig
python
openai__openai-python
tests/api_resources/beta/threads/runs/test_steps.py
{ "start": 484, "end": 6465 }
class ____: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_retrieve(self, client: OpenAI) -> None: with pytest.warns(DeprecationWarning): step = client.beta.threads.runs.steps.retrieve( step_id="step_id", thread_id="thread_id", run_id="run_id", ) assert_matches_type(RunStep, step, path=["response"]) @parametrize def test_method_retrieve_with_all_params(self, client: OpenAI) -> None: with pytest.warns(DeprecationWarning): step = client.beta.threads.runs.steps.retrieve( step_id="step_id", thread_id="thread_id", run_id="run_id", include=["step_details.tool_calls[*].file_search.results[*].content"], ) assert_matches_type(RunStep, step, path=["response"]) @parametrize def test_raw_response_retrieve(self, client: OpenAI) -> None: with pytest.warns(DeprecationWarning): response = client.beta.threads.runs.steps.with_raw_response.retrieve( step_id="step_id", thread_id="thread_id", run_id="run_id", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" step = response.parse() assert_matches_type(RunStep, step, path=["response"]) @parametrize def test_streaming_response_retrieve(self, client: OpenAI) -> None: with pytest.warns(DeprecationWarning): with client.beta.threads.runs.steps.with_streaming_response.retrieve( step_id="step_id", thread_id="thread_id", run_id="run_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" step = response.parse() assert_matches_type(RunStep, step, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_path_params_retrieve(self, client: OpenAI) -> None: with pytest.warns(DeprecationWarning): with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): client.beta.threads.runs.steps.with_raw_response.retrieve( step_id="step_id", thread_id="", run_id="run_id", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): client.beta.threads.runs.steps.with_raw_response.retrieve( step_id="step_id", thread_id="thread_id", run_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `step_id` but received ''"): client.beta.threads.runs.steps.with_raw_response.retrieve( step_id="", thread_id="thread_id", run_id="run_id", ) @parametrize def test_method_list(self, client: OpenAI) -> None: with pytest.warns(DeprecationWarning): step = client.beta.threads.runs.steps.list( run_id="run_id", thread_id="thread_id", ) assert_matches_type(SyncCursorPage[RunStep], step, path=["response"]) @parametrize def test_method_list_with_all_params(self, client: OpenAI) -> None: with pytest.warns(DeprecationWarning): step = client.beta.threads.runs.steps.list( run_id="run_id", thread_id="thread_id", after="after", before="before", include=["step_details.tool_calls[*].file_search.results[*].content"], limit=0, order="asc", ) assert_matches_type(SyncCursorPage[RunStep], step, path=["response"]) @parametrize def test_raw_response_list(self, client: OpenAI) -> None: with pytest.warns(DeprecationWarning): response = client.beta.threads.runs.steps.with_raw_response.list( run_id="run_id", thread_id="thread_id", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" step = response.parse() assert_matches_type(SyncCursorPage[RunStep], step, path=["response"]) @parametrize def test_streaming_response_list(self, client: OpenAI) -> None: with pytest.warns(DeprecationWarning): with client.beta.threads.runs.steps.with_streaming_response.list( run_id="run_id", thread_id="thread_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" step = response.parse() assert_matches_type(SyncCursorPage[RunStep], step, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_path_params_list(self, client: OpenAI) -> None: with pytest.warns(DeprecationWarning): with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): client.beta.threads.runs.steps.with_raw_response.list( run_id="run_id", thread_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): client.beta.threads.runs.steps.with_raw_response.list( run_id="", thread_id="thread_id", )
TestSteps
python
readthedocs__readthedocs.org
readthedocs/embed/apps.py
{ "start": 61, "end": 156 }
class ____(AppConfig): name = "readthedocs.embed" verbose_name = "Embedded API"
EmbedConfig
python
walkccc__LeetCode
solutions/3163. String Compression III/3163.py
{ "start": 0, "end": 315 }
class ____: def compressedString(self, word: str) -> str: n = len(word) ans = [] i = 0 j = 0 while i < n: count = 0 while j < n and word[j] == word[i] and count < 9: j += 1 count += 1 ans.append(str(count) + word[i]) i = j return ''.join(ans)
Solution
python
etianen__django-reversion
tests/test_app/tests/test_api.py
{ "start": 864, "end": 1041 }
class ____(TestModelMixin, TestBase): def testGetRegisteredModels(self): self.assertEqual(set(reversion.get_registered_models()), {TestModel})
GetRegisteredModelsTest
python
Textualize__textual
src/textual/drivers/_writer_thread.py
{ "start": 174, "end": 1733 }
class ____(threading.Thread): """A thread / file-like to do writes to stdout in the background.""" def __init__(self, file: IO[str]) -> None: super().__init__(daemon=True, name="textual-output") self._queue: Queue[str | None] = Queue(MAX_QUEUED_WRITES) self._file = file def write(self, text: str) -> None: """Write text. Text will be enqueued for writing. Args: text: Text to write to the file. """ self._queue.put(text) def isatty(self) -> bool: """Pretend to be a terminal. Returns: True. """ return True def fileno(self) -> int: """Get file handle number. Returns: File number of proxied file. """ return self._file.fileno() def flush(self) -> None: """Flush the file (a no-op, because flush is done in the thread).""" return def run(self) -> None: """Run the thread.""" write = self._file.write flush = self._file.flush get = self._queue.get qsize = self._queue.qsize # Read from the queue, write to the file. # Flush when there is a break. while True: text: str | None = get() if text is None: break write(text) if qsize() == 0: flush() flush() def stop(self) -> None: """Stop the thread, and block until it finished.""" self._queue.put(None) self.join()
WriterThread
python
huggingface__transformers
src/transformers/models/mpnet/modeling_mpnet.py
{ "start": 9831, "end": 13228 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.n_heads = config.num_attention_heads self.layer = nn.ModuleList([MPNetLayer(config) for _ in range(config.num_hidden_layers)]) self.relative_attention_bias = nn.Embedding(config.relative_attention_num_buckets, self.n_heads) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, output_hidden_states: bool = False, return_dict: bool = False, **kwargs, ): position_bias = self.compute_position_bias(hidden_states) all_hidden_states = () if output_hidden_states else None all_attentions = () if output_attentions else None for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_outputs = layer_module( hidden_states, attention_mask, position_bias, output_attentions=output_attentions, **kwargs, ) hidden_states = layer_outputs[0] if output_attentions: all_attentions = all_attentions + (layer_outputs[1],) # Add last layer if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None) return BaseModelOutput( last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions, ) def compute_position_bias(self, x, position_ids=None, num_buckets=32): bsz, qlen, klen = x.size(0), x.size(1), x.size(1) if position_ids is not None: context_position = position_ids[:, :, None] memory_position = position_ids[:, None, :] else: context_position = torch.arange(qlen, dtype=torch.long)[:, None] memory_position = torch.arange(klen, dtype=torch.long)[None, :] relative_position = memory_position - context_position rp_bucket = self.relative_position_bucket(relative_position, num_buckets=num_buckets) rp_bucket = rp_bucket.to(x.device) values = self.relative_attention_bias(rp_bucket) values = values.permute([2, 0, 1]).unsqueeze(0) values = values.expand((bsz, -1, qlen, klen)).contiguous() return values @staticmethod def relative_position_bucket(relative_position, num_buckets=32, max_distance=128): ret = 0 n = -relative_position num_buckets //= 2 ret += (n < 0).to(torch.long) * num_buckets n = torch.abs(n) max_exact = num_buckets // 2 is_small = n < max_exact val_if_large = max_exact + ( torch.log(n.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact) ).to(torch.long) val_if_large = torch.min(val_if_large, torch.full_like(val_if_large, num_buckets - 1)) ret += torch.where(is_small, n, val_if_large) return ret # Copied from transformers.models.bert.modeling_bert.BertPooler
MPNetEncoder
python
getsentry__sentry
src/sentry/integrations/msteams/webhook.py
{ "start": 3129, "end": 3255 }
class ____(MsTeamsIntegrationAnalytics): pass @analytics.eventclass("integrations.msteams.resolve")
MsTeamsIntegrationAssign
python
streamlit__streamlit
lib/streamlit/testing/v1/element_tree.py
{ "start": 9326, "end": 9529 }
class ____(AlertBase): # noqa: A001 def __init__(self, proto: AlertProto, root: ElementTree) -> None: super().__init__(proto, root) self.type = "warning" @dataclass(repr=False)
Warning
python
getsentry__sentry
src/sentry/auth/providers/saml2/provider.py
{ "start": 7778, "end": 12425 }
class ____(Provider, abc.ABC): """ Base SAML2 Authentication provider. SAML style authentication plugins should implement this. - The provider must implement the `get_configure_view`. - The provider must implement the `get_saml_setup_pipeline`. The AuthView(s) passed in this method MUST bind the `idp` configuration object. The dict should match the shape: >>> state.get('idp') { 'entity_id': # Identity Provider entity ID. Usually a URL 'x509cert': # Identity Provider x509 public certificate 'sso_url': # Identity Provider Single Sign-On URL 'slo_url': # identity Provider Single Sign-Out URL } The provider may also bind the `advanced` configuration. This dict provides advanced SAML configurations. The dict should match the shape: HINT: You *probably* don't need this. >>> state.get('advanced') { 'authn_request_signed': # Sign the authentication request? 'logout_request_signed': # Sign the logout request? 'logout_response_signed': # Sign the logout response? 'metadata_signed': # Sign the metadata? 'want_message_signed': # Expect signed message 'want_assertion_signed': # Expect signed assertions 'want_assertion_encrypted': # Expect encrypted assertions 'signature_algorithm': # Algorithm used to sign / verify requests / responses 'digest_algorithm': # Algorithm used to generate / verify digests 'x509cert': # Public Service Provider key 'private_key': # Private Key used for signing / encryption } - The provider must EITHER specify an attribute mapping by implementing the `attribute_mapping` method OR bind the `attribute_mapping` key to the state during setup. The attribute mapping should map the `Attributes` constants to the Identity Provider attribute keys. """ # SAML does nothing with refresh state -- don't waste resources calling it in check_auth job. requires_refresh = False required_feature = "organizations:sso-saml2" is_saml = True def get_auth_pipeline(self) -> list[AuthView]: return [SAML2LoginView(), SAML2ACSView()] def get_setup_pipeline(self) -> list[AuthView]: return self.get_saml_setup_pipeline() + self.get_auth_pipeline() @abc.abstractmethod def get_saml_setup_pipeline(self) -> list[AuthView]: """ Return a list of AuthViews to setup the SAML provider. The setup AuthView(s) must bind the `idp` parameter into the pipeline state. """ def attribute_mapping(self) -> Mapping[str, Any]: """ Returns the default Attribute Key -> IdP attribute key mapping. This value will be merged into the configuration by self.build_config, however, should a attribute_mapping exist in the pipeline state at configuration build time, these may be overridden. """ return {} def build_config(self, state: dict[str, Any]) -> dict[str, Any]: config = state # Default attribute mapping if none bound if "attribute_mapping" not in config: config["attribute_mapping"] = self.attribute_mapping() return config def build_identity(self, state: Mapping[str, Any]) -> Mapping[str, Any]: raw_attributes = state["auth_attributes"] attributes = {} # map configured provider attributes for key, provider_key in self.config["attribute_mapping"].items(): attribute_list = raw_attributes.get(provider_key, [""]) attributes[key] = attribute_list[0] if len(attribute_list) > 0 else "" # Email and identifier MUST be correctly mapped if not attributes[Attributes.IDENTIFIER] or not attributes[Attributes.USER_EMAIL]: error_msg_keys = ", ".join(repr(key) for key in sorted(raw_attributes.keys())) raise IdentityNotValid( _( f"Failed to map SAML attributes. Assertion returned the following attribute keys: {error_msg_keys}" ) ) name_gen = (attributes[k] for k in (Attributes.FIRST_NAME, Attributes.LAST_NAME)) name = " ".join(_f for _f in name_gen if _f) return { "id": attributes[Attributes.IDENTIFIER], "email": attributes[Attributes.USER_EMAIL], "name": name, } def refresh_identity(self, auth_identity: AuthIdentity) -> None: # Nothing to refresh return
SAML2Provider
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 301520, "end": 303349 }
class ____(DataFormat): """ CsvDataFormat schema wrapper. Parameters ---------- parse : dict, :class:`Parse`, None If set to ``null``, disable type inference based on the spec and only use type inference based on the data. Alternatively, a parsing directive object can be provided for explicit data types. Each property of the object corresponds to a field name, and the value to the desired data type (one of ``"number"``, ``"boolean"``, ``"date"``, or null (do not parse the field)). For example, ``"parse": {"modified_on": "date"}`` parses the ``modified_on`` field in each input record a Date value. For ``"date"``, we parse data based using JavaScript's `Date.parse() <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse>`__. For Specific date formats can be provided (e.g., ``{foo: "date:'%m%d%Y'"}``), using the `d3-time-format syntax <https://github.com/d3/d3-time-format#locale_format>`__. UTC date format parsing is supported similarly (e.g., ``{foo: "utc:'%m%d%Y'"}``). See more about `UTC time <https://vega.github.io/vega-lite/docs/timeunit.html#utc>`__ type : Literal['csv', 'tsv'] Type of input data: ``"json"``, ``"csv"``, ``"tsv"``, ``"dsv"``. **Default value:** The default format type is determined by the extension of the file URL. If no extension is detected, ``"json"`` will be used by default. """ _schema = {"$ref": "#/definitions/CsvDataFormat"} def __init__( self, parse: Optional[SchemaBase | Map | None] = Undefined, type: Optional[Literal["csv", "tsv"]] = Undefined, **kwds, ): super().__init__(parse=parse, type=type, **kwds)
CsvDataFormat
python
gevent__gevent
src/gevent/tests/test__threadpool.py
{ "start": 11996, "end": 12515 }
class ____(TestCase): error_fatal = False def test(self): self.pool = self._makeOne(3) self.assertRaises(greentest.ExpectedException, self.pool.map, lambda x: None, error_iter()) gevent.sleep(0.001) def test_unordered(self): self.pool = self._makeOne(3) def unordered(): return list(self.pool.imap_unordered(lambda x: None, error_iter())) self.assertRaises(greentest.ExpectedException, unordered) gevent.sleep(0.001)
TestErrorInIterator
python
weaviate__weaviate-python-client
weaviate/connect/event_loop.py
{ "start": 4227, "end": 4882 }
class ____: _instances: Optional[Dict[int, _EventLoop]] = None @classmethod def get_instance(cls) -> _EventLoop: pid = os.getpid() if cls._instances is not None and pid in cls._instances: return cls._instances[pid] if cls._instances is None: cls._instances = {} instance = _EventLoop() instance.start() cls._instances[pid] = instance return instance def __del__(self) -> None: if self._instances is not None: for instance in self._instances.values(): instance.shutdown() self._instances = None
_EventLoopSingleton
python
langchain-ai__langchain
libs/langchain/langchain_classic/agents/agent.py
{ "start": 32220, "end": 32886 }
class ____(BaseTool): """Tool that just returns the query.""" name: str = "_Exception" """Name of the tool.""" description: str = "Exception tool" """Description of the tool.""" @override def _run( self, query: str, run_manager: CallbackManagerForToolRun | None = None, ) -> str: return query @override async def _arun( self, query: str, run_manager: AsyncCallbackManagerForToolRun | None = None, ) -> str: return query NextStepOutput = list[AgentFinish | AgentAction | AgentStep] RunnableAgentType = RunnableAgent | RunnableMultiActionAgent
ExceptionTool
python
ansible__ansible
test/units/plugins/connection/test_winrm.py
{ "start": 7096, "end": 14874 }
class ____(object): @pytest.mark.parametrize('options, expected', [ [{"_extras": {}}, (["kinit", "user@domain"],)], [{"_extras": {}, 'ansible_winrm_kinit_cmd': 'kinit2'}, (["kinit2", "user@domain"],)], [{"_extras": {'ansible_winrm_kerberos_delegation': True}}, (["kinit", "-f", "user@domain"],)], [{"_extras": {}, 'ansible_winrm_kinit_args': '-f -p'}, (["kinit", "-f", "-p", "user@domain"],)], [{"_extras": {}, 'ansible_winrm_kerberos_delegation': True, 'ansible_winrm_kinit_args': '-p'}, (["kinit", "-p", "user@domain"],)] ]) def test_kinit_success_subprocess(self, monkeypatch, options, expected): def mock_communicate(input=None, timeout=None): return b"", b"" mock_popen = MagicMock() mock_popen.return_value.communicate = mock_communicate mock_popen.return_value.returncode = 0 monkeypatch.setattr("subprocess.Popen", mock_popen) pc = PlayContext() conn = connection_loader.get('winrm', pc) conn.set_options(var_options=options) conn._build_winrm_kwargs() conn._kerb_auth("user@domain", "pass") mock_calls = mock_popen.mock_calls assert len(mock_calls) == 1 assert mock_calls[0][1] == expected actual_env = mock_calls[0][2]['env'] assert sorted(list(actual_env.keys())) == ['KRB5CCNAME', 'PATH'] assert actual_env['KRB5CCNAME'].startswith("FILE:/") assert actual_env['PATH'] == os.environ['PATH'] def test_kinit_with_missing_executable_subprocess(self, monkeypatch): expected_err = "[Errno 2] No such file or directory: " \ "'/fake/kinit': '/fake/kinit'" mock_popen = MagicMock(side_effect=OSError(expected_err)) monkeypatch.setattr("subprocess.Popen", mock_popen) pc = PlayContext() conn = connection_loader.get('winrm', pc) options = {"_extras": {}, "ansible_winrm_kinit_cmd": "/fake/kinit"} conn.set_options(var_options=options) conn._build_winrm_kwargs() with pytest.raises(AnsibleConnectionFailure) as err: conn._kerb_auth("user@domain", "pass") assert str(err.value) == "Kerberos auth failure when calling " \ "kinit cmd '/fake/kinit': %s" % expected_err def test_kinit_error_subprocess(self, monkeypatch): expected_err = "kinit: krb5_parse_name: " \ "Configuration file does not specify default realm" def mock_communicate(input=None, timeout=None): return b"", to_bytes(expected_err) mock_popen = MagicMock() mock_popen.return_value.communicate = mock_communicate mock_popen.return_value.returncode = 1 monkeypatch.setattr("subprocess.Popen", mock_popen) pc = PlayContext() conn = connection_loader.get('winrm', pc) conn.set_options(var_options={"_extras": {}}) conn._build_winrm_kwargs() with pytest.raises(AnsibleConnectionFailure) as err: conn._kerb_auth("invaliduser", "pass") assert str(err.value) == \ "Kerberos auth failure for principal invaliduser: %s" % (expected_err) def test_kinit_error_pass_in_output_subprocess(self, monkeypatch): def mock_communicate(input=None, timeout=None): return b"", b"Error with kinit\n" + input mock_popen = MagicMock() mock_popen.return_value.communicate = mock_communicate mock_popen.return_value.returncode = 1 monkeypatch.setattr("subprocess.Popen", mock_popen) pc = PlayContext() conn = connection_loader.get('winrm', pc) conn.set_options(var_options={"_extras": {}}) conn._build_winrm_kwargs() with pytest.raises(AnsibleConnectionFailure) as err: conn._kerb_auth("username", "password") assert str(err.value) == \ "Kerberos auth failure for principal username: " \ "Error with kinit\n<redacted>" def test_exec_command_with_timeout(self, monkeypatch): requests_exc = pytest.importorskip("requests.exceptions") pc = PlayContext() conn = connection_loader.get('winrm', pc) mock_proto = MagicMock() mock_proto.run_command.side_effect = requests_exc.Timeout("msg") conn._connected = True conn._winrm_host = 'hostname' monkeypatch.setattr(conn, "_winrm_connect", lambda: mock_proto) with pytest.raises(AnsibleConnectionFailure) as e: conn.exec_command('cmd', in_data=None, sudoable=True) assert str(e.value) == "winrm connection error: msg" def test_exec_command_get_output_timeout(self, monkeypatch): requests_exc = pytest.importorskip("requests.exceptions") pc = PlayContext() conn = connection_loader.get('winrm', pc) mock_proto = MagicMock() mock_proto.run_command.return_value = "command_id" mock_proto.send_message.side_effect = requests_exc.Timeout("msg") conn._connected = True conn._winrm_host = 'hostname' monkeypatch.setattr(conn, "_winrm_connect", lambda: mock_proto) with pytest.raises(AnsibleConnectionFailure) as e: conn.exec_command('cmd', in_data=None, sudoable=True) assert str(e.value) == "winrm connection error: msg" def test_connect_failure_auth_401(self, monkeypatch): pc = PlayContext() conn = connection_loader.get('winrm', pc) conn.set_options(var_options={"ansible_winrm_transport": "basic", "_extras": {}}) mock_proto = MagicMock() mock_proto.open_shell.side_effect = ValueError("Custom exc Code 401") mock_proto_init = MagicMock() mock_proto_init.return_value = mock_proto monkeypatch.setattr(winrm, "Protocol", mock_proto_init) with pytest.raises(AnsibleConnectionFailure, match="the specified credentials were rejected by the server"): conn.exec_command('cmd', in_data=None, sudoable=True) def test_connect_failure_other_exception(self, monkeypatch): pc = PlayContext() conn = connection_loader.get('winrm', pc) conn.set_options(var_options={"ansible_winrm_transport": "basic", "_extras": {}}) mock_proto = MagicMock() mock_proto.open_shell.side_effect = ValueError("Custom exc") mock_proto_init = MagicMock() mock_proto_init.return_value = mock_proto monkeypatch.setattr(winrm, "Protocol", mock_proto_init) with pytest.raises(AnsibleConnectionFailure, match="basic: Custom exc"): conn.exec_command('cmd', in_data=None, sudoable=True) def test_connect_failure_operation_timed_out(self, monkeypatch): pc = PlayContext() conn = connection_loader.get('winrm', pc) conn.set_options(var_options={"ansible_winrm_transport": "basic", "_extras": {}}) mock_proto = MagicMock() mock_proto.open_shell.side_effect = ValueError("Custom exc Operation timed out") mock_proto_init = MagicMock() mock_proto_init.return_value = mock_proto monkeypatch.setattr(winrm, "Protocol", mock_proto_init) with pytest.raises(AnsibleError, match="the connection attempt timed out"): conn.exec_command('cmd', in_data=None, sudoable=True) def test_connect_no_transport(self): pc = PlayContext() conn = connection_loader.get('winrm', pc) conn.set_options(var_options={"_extras": {}}) conn._build_winrm_kwargs() conn._winrm_transport = [] with pytest.raises(AnsibleError, match="No transport found for WinRM connection"): conn._winrm_connect()
TestWinRMKerbAuth
python
huggingface__transformers
src/transformers/models/blip_2/modeling_blip_2.py
{ "start": 33338, "end": 40780 }
class ____(Blip2PreTrainedModel): _supports_attention_backend = False # adds position on attn weights before last matmul _supports_flash_attn = False _supports_sdpa = False _supports_flex_attn = False _can_record_outputs = { "hidden_states": Blip2QFormerLayer, "attentions": [ OutputRecorder(Blip2QFormerMultiHeadAttention, index=1, layer_name=".attention"), ], "cross_attentions": [ OutputRecorder(Blip2QFormerMultiHeadAttention, index=1, layer_name=".crossattention"), ], } def __init__(self, config: Blip2QFormerConfig): super().__init__(config) self.config = config self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.encoder = Blip2QFormerEncoder(config) self.post_init() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value def get_extended_attention_mask( self, attention_mask: torch.Tensor, input_shape: tuple[int], device: torch.device, has_query: bool = False, ) -> torch.Tensor: """ Makes broadcastable attention and causal masks so that future and masked tokens are ignored. Arguments: attention_mask (`torch.Tensor`): Mask with ones indicating tokens to attend to, zeros for tokens to ignore. input_shape (`tuple[int]`): The shape of the input to the model. device (`torch.device`): The device of the input to the model. Returns: `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`. """ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. if attention_mask.dim() == 3: extended_attention_mask = attention_mask[:, None, :, :] elif attention_mask.dim() == 2: # Provided a padding mask of dimensions [batch_size, seq_length] # - the model is an encoder, so make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] extended_attention_mask = attention_mask[:, None, None, :] else: raise ValueError( f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})" ) # Since attention_mask is 1.0 for positions we want to attend and 0.0 for # masked positions, this operation will create a tensor which is 0.0 for # positions we want to attend and -10000.0 for masked positions. # Since we are adding it to the raw scores before the softmax, this is # effectively the same as removing these entirely. extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0 return extended_attention_mask @check_model_inputs() @auto_docstring def forward( self, query_embeds: torch.FloatTensor, query_length: Optional[int] = None, attention_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]: r""" query_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Hidden states to be used in the attention computation. If cross-attention, will be used for the query (i.e., key and value will use the encoder_hidden_states). query_length (`int`, *optional*): Length of the query, usually based on the number of query tokens. If no value is provided, query_length will be inferred by the query_embeds. """ query_length = ( query_length if query_length is not None else query_embeds.shape[1] if query_embeds is not None else 0 ) # `Blip2QFormerModel` is kept as fp32 query_embeds = query_embeds.to(self.layernorm.weight.dtype) embedding_output = self.layernorm(query_embeds) embedding_output = self.dropout(embedding_output) input_shape = embedding_output.size()[:-1] batch_size, seq_length = input_shape device = embedding_output.device if attention_mask is None: attention_mask = torch.ones(((batch_size, seq_length)), device=device) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, device) # If a 2D or 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_hidden_states is not None: # Qformer and latent query tokens are kept in fp32. We cast `encoder_hidden_states` if not fp32 already if encoder_hidden_states.dtype != query_embeds.dtype: encoder_hidden_states = encoder_hidden_states.to(query_embeds.dtype) if isinstance(encoder_hidden_states, list): encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size() else: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) if isinstance(encoder_attention_mask, list): encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask] elif encoder_attention_mask is None: encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) else: encoder_extended_attention_mask = None encoder_outputs: BaseModelOutput = self.encoder( embedding_output, attention_mask=extended_attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, query_length=query_length, **kwargs, ) sequence_output = encoder_outputs.last_hidden_state pooled_output = sequence_output[:, 0, :] return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, ) @auto_docstring( custom_intro=""" BLIP-2 Model for generating text and image features. The model consists of a vision encoder, Querying Transformer (Q-Former) and a language model. """ )
Blip2QFormerModel
python
encode__django-rest-framework
tests/test_filters.py
{ "start": 11738, "end": 11820 }
class ____(models.Model): label = models.CharField(max_length=32)
AttributeModel
python
sympy__sympy
sympy/diffgeom/diffgeom.py
{ "start": 22544, "end": 24766 }
class ____(Symbol): """A symbol which denotes an abstract value of i-th coordinate of the coordinate system with given context. Explanation =========== Each coordinates in coordinate system are represented by unique symbol, such as x, y, z in Cartesian coordinate system. You may not construct this class directly. Instead, use `symbols` method of CoordSystem. Parameters ========== coord_sys : CoordSystem index : integer Examples ======== >>> from sympy import symbols, Lambda, Matrix, sqrt, atan2, cos, sin >>> from sympy.diffgeom import Manifold, Patch, CoordSystem >>> m = Manifold('M', 2) >>> p = Patch('P', m) >>> x, y = symbols('x y', real=True) >>> r, theta = symbols('r theta', nonnegative=True) >>> relation_dict = { ... ('Car2D', 'Pol'): Lambda((x, y), Matrix([sqrt(x**2 + y**2), atan2(y, x)])), ... ('Pol', 'Car2D'): Lambda((r, theta), Matrix([r*cos(theta), r*sin(theta)])) ... } >>> Car2D = CoordSystem('Car2D', p, [x, y], relation_dict) >>> Pol = CoordSystem('Pol', p, [r, theta], relation_dict) >>> x, y = Car2D.symbols ``CoordinateSymbol`` contains its coordinate symbol and index. >>> x.name 'x' >>> x.coord_sys == Car2D True >>> x.index 0 >>> x.is_real True You can transform ``CoordinateSymbol`` into other coordinate system using ``rewrite()`` method. >>> x.rewrite(Pol) r*cos(theta) >>> sqrt(x**2 + y**2).rewrite(Pol).simplify() r """ def __new__(cls, coord_sys, index, **assumptions): name = coord_sys.args[2][index].name obj = super().__new__(cls, name, **assumptions) obj.coord_sys = coord_sys obj.index = index return obj def __getnewargs__(self): return (self.coord_sys, self.index) def _hashable_content(self): return ( self.coord_sys, self.index ) + tuple(sorted(self.assumptions0.items())) def _eval_rewrite(self, rule, args, **hints): if isinstance(rule, CoordSystem): return rule.transform(self.coord_sys)[self.index] return super()._eval_rewrite(rule, args, **hints)
CoordinateSymbol
python
huggingface__transformers
examples/modular-transformers/modeling_test_detr.py
{ "start": 27371, "end": 31240 }
class ____(GradientCheckpointingLayer): def __init__(self, config: TestDetrConfig): super().__init__() self.embed_dim = config.d_model self.self_attn = TestDetrMultiscaleDeformableAttention( config, num_heads=config.encoder_attention_heads, n_points=config.encoder_n_points, ) self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.dropout = config.dropout self.activation_fn = ACT2FN[config.activation_function] self.activation_dropout = config.activation_dropout self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim) self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) self.final_layer_norm = nn.LayerNorm(self.embed_dim) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, position_embeddings: Optional[torch.Tensor] = None, reference_points=None, spatial_shapes=None, spatial_shapes_list=None, level_start_index=None, output_attentions: bool = False, ): """ Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Input to the layer. attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Attention mask. position_embeddings (`torch.FloatTensor`, *optional*): Position embeddings, to be added to `hidden_states`. reference_points (`torch.FloatTensor`, *optional*): Reference points. spatial_shapes (`torch.LongTensor`, *optional*): Spatial shapes of the backbone feature maps. level_start_index (`torch.LongTensor`, *optional*): Level start index. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states # Apply Multi-scale Deformable Attention Module on the multi-scale feature maps. hidden_states, attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, encoder_hidden_states=hidden_states, encoder_attention_mask=attention_mask, position_embeddings=position_embeddings, reference_points=reference_points, spatial_shapes=spatial_shapes, spatial_shapes_list=spatial_shapes_list, level_start_index=level_start_index, output_attentions=output_attentions, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.self_attn_layer_norm(hidden_states) residual = hidden_states hidden_states = self.activation_fn(self.fc1(hidden_states)) hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training) hidden_states = self.fc2(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.final_layer_norm(hidden_states) if self.training: if torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any(): clamp_value = torch.finfo(hidden_states.dtype).max - 1000 hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value) outputs = (hidden_states,) if output_attentions: outputs += (attn_weights,) return outputs
TestDetrEncoderLayer
python
ansible__ansible
test/units/module_utils/facts/test_collectors.py
{ "start": 16160, "end": 16402 }
class ____(BaseFactsTest): __test__ = True gather_subset = ['!all', 'ssh_pub_keys'] valid_subsets = ['ssh_pub_keys'] fact_namespace = 'ansible_ssh_pub_leys' collector_class = SshPubKeyFactCollector
TestSshPubKeyFactCollector
python
Lightning-AI__lightning
tests/tests_fabric/utilities/test_data.py
{ "start": 4438, "end": 24334 }
class ____(DataLoader): def __init__(self, dataset, **kwargs): super().__init__(list(dataset) + list(range(5, 10)), **kwargs) @pytest.mark.parametrize( ("cls", "args", "kwargs", "arg_names", "dataset", "checked_values"), [ pytest.param( DataLoaderSubclass1, ("attribute1",), {"dataset": range(4), "batch_size": 2}, ("attribute1",), range(4), {"batch_size": 2, "at1": "attribute1"}, id="test1", ), pytest.param( DataLoaderSubclass2, ("attribute2",), {"dataset": range(4), "batch_size": 2}, ("attribute2",), range(4), {"batch_size": 2, "at1": "attribute2-2", "at2": "attribute2"}, id="test2", ), pytest.param( MyDataLoader, (test3_data,), {"batch_size": 2}, ("data",), range(10), {"batch_size": 2, "data": test3_data}, id="test3", ), pytest.param(PoptorchDataLoader, (123, [1]), {}, ("options",), [1], {"options": 123}, id="test4"), pytest.param( IncompleteDataLoader, (range(10),), {"batch_size": 10}, ("dataset",), range(10), {"batch_size": 5}, id="test5", ), pytest.param( WeirdDataLoader1, (10, range(10)), {"batch_size": 10}, ("arg1", "arg2"), range(10), {"arg1": 10, "batch_size": 10}, id="test6", ), pytest.param( WeirdDataLoader2, (range(10), range(10, 20)), {"batch_size": 10}, ("data_part1", "data_part2"), list(range(20)), {"batch_size": 10}, id="test7", ), pytest.param(NoneDataLoader, (None,), {}, (), None, {}, id="test8"), pytest.param(ChangingDataLoader, (range(5),), {}, ("dataset",), list(range(10)), {}, id="test9"), ], ) def test_replace_dunder_methods_dataloader(cls, args, kwargs, arg_names, dataset, checked_values): with _replace_dunder_methods(DataLoader, "dataset"): dataloader = cls(*args, **kwargs) assert dataloader.__pl_saved_args == args assert dataloader.__pl_saved_kwargs == kwargs assert dataloader.__pl_saved_arg_names == arg_names assert dataloader.__pl_saved_default_kwargs == {} assert dataloader.__dataset == dataset assert dataloader.dataset == dataset for key, value in checked_values.items(): dataloader_value = getattr(dataloader, key) if isinstance(dataloader_value, Tensor): assert dataloader_value is value else: assert dataloader_value == value dataloader = _update_dataloader(dataloader, dataloader.sampler) assert isinstance(dataloader, cls) assert not hasattr(dataloader, "__pl_saved_kwargs") assert not hasattr(dataloader, "__pl_saved_arg_names") assert not hasattr(dataloader, "__pl_saved_args") assert not hasattr(dataloader, "__pl_saved_default_kwargs") assert not hasattr(dataloader, "__dataset") assert dataloader.dataset == dataset for key, value in checked_values.items(): dataloader_value = getattr(dataloader, key) if isinstance(dataloader_value, Tensor): assert dataloader_value is value else: assert dataloader_value == value def test_replace_dunder_methods_extra_kwargs(): class LoaderSubclass(DataLoader): def __init__(self, dataset, *args, batch_size=10, **kwargs): super().__init__(dataset, *args, batch_size=batch_size, **kwargs) with _replace_dunder_methods(DataLoader, "dataset"): dataloader = LoaderSubclass(range(10)) assert dataloader.__pl_saved_args == (range(10),) assert dataloader.__pl_saved_kwargs == {} assert dataloader.__pl_saved_arg_names == ("dataset",) assert dataloader.__pl_saved_default_kwargs == {"batch_size": 10} assert dataloader.__dataset == range(10) def test_replace_dunder_methods_attrs(): """This test checks, that all the calls from setting and deleting attributes within `_replace_dunder_methods` are correctly preserved even after reinstantiation. It also includes a custom `__setattr__` """ class Loader(DataLoader): def __setattr__(self, attr, val): if attr == "custom_arg": val = val + 2 super().__setattr__(attr, val) with _replace_dunder_methods(DataLoader, "dataset"): dataloader = Loader(range(10)) dataloader.custom_arg = 5 dataloader.my_arg = 10 dataloader.another_arg = 100 del dataloader.dataset with contextlib.suppress(AttributeError): del dataloader.abc_arg assert dataloader.__pl_saved_args == (range(10),) assert dataloader.__pl_saved_kwargs == {} assert dataloader.__pl_saved_arg_names == ("dataset",) assert dataloader.__dataset == range(10) assert dataloader.custom_arg == 7 assert dataloader.my_arg == 10 assert dataloader.another_arg == 100 assert not hasattr(dataloader, "dataset") assert dataloader.__pl_attrs_record == [ (("custom_arg", 5), _WrapAttrTag.SET), (("my_arg", 10), _WrapAttrTag.SET), (("another_arg", 100), _WrapAttrTag.SET), (("dataset",), _WrapAttrTag.DEL), ] dataloader = _update_dataloader(dataloader, dataloader.sampler) assert dataloader.custom_arg == 7 assert dataloader.my_arg == 10 assert dataloader.another_arg == 100 assert not hasattr(dataloader, "dataset") def test_replace_dunder_methods_restore_methods(): """This tests checks whether are all dunder methods restored to their original versions.""" class Init(DataLoader): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class SetAttr(DataLoader): def __setattr__(self, *args): return super().__setattr__(*args) class DelAttr(DataLoader): def __delattr__(self, *args): return super().__delattr__(*args) class InitAndSetAttr(Init, SetAttr): pass class InitAndDelAttr(Init, DelAttr): pass class SetAttrAndDelAttr(SetAttr, DelAttr): pass class AllDunder(Init, SetAttr, DelAttr): pass before = {} for cls in (Init, SetAttr, DelAttr, InitAndSetAttr, InitAndDelAttr, SetAttrAndDelAttr, AllDunder): before[cls] = {"init": cls.__init__, "setattr": cls.__setattr__, "delattr": cls.__delattr__} with _replace_dunder_methods(DataLoader, "dataset"): pass for cls in (Init, SetAttr, DelAttr, InitAndSetAttr, InitAndDelAttr, SetAttrAndDelAttr, AllDunder): assert before[cls] == {"init": cls.__init__, "setattr": cls.__setattr__, "delattr": cls.__delattr__} @pytest.mark.parametrize( ( "args", "kwargs", "default_kwargs", "arg_names", "replace_key", "replace_value", "expected_status", "expected_args", "expected_kwargs", ), [ pytest.param((), {}, {}, [], "a", 1, False, (), {}, id="empty"), pytest.param((1,), {}, {}, ["a"], "a", 2, True, (2,), {}, id="simple1"), pytest.param((1, 2, 3), {}, {}, ["a", "b", "c"], "b", False, True, (1, False, 3), {}, id="simple2"), pytest.param((1, 2, 3), {"a": 1}, {}, ["b", "c", "d"], "a", 2, True, (1, 2, 3), {"a": 2}, id="simple_kwargs"), pytest.param( (1, 2, 3), {"a": 1}, {"e": 5}, ["b", "c", "d"], "e", 2, True, (1, 2, 3), {"a": 1, "e": 2}, id="default_kwargs", ), ], ) def test_replace_value_in_args( args, kwargs, default_kwargs, arg_names, replace_key, replace_value, expected_status, expected_args, expected_kwargs ): assert _replace_value_in_saved_args(replace_key, replace_value, args, kwargs, default_kwargs, arg_names) == ( expected_status, expected_args, expected_kwargs, ) def test_update_dataloader_typerror_custom_exception(): class BadStandaloneGoodHookImpl(DataLoader): def __init__(self, foo, *args, **kwargs): self.foo = foo # positional conflict with `dataset` super().__init__(foo, *args, **kwargs) dataloader = BadStandaloneGoodHookImpl([1, 2, 3]) with pytest.raises(MisconfigurationException, match="implementation has an error.*`dataset`"): _update_dataloader(dataloader, dataloader.sampler) with _replace_dunder_methods(DataLoader, "dataset"): dataloader = BadStandaloneGoodHookImpl([1, 2, 3]) new_dataloader = _update_dataloader(dataloader, dataloader.sampler) assert isinstance(new_dataloader, BadStandaloneGoodHookImpl) class BadImpl(DataLoader): def __init__(self, randomize, *args, **kwargs): self.randomize = randomize # keyword conflict with `shuffle` super().__init__(*args, shuffle=randomize, **kwargs) dataloader = BadImpl(False, []) with pytest.raises(MisconfigurationException, match="implementation has an error.*`shuffle`"): _update_dataloader(dataloader, dataloader.sampler) class GoodImpl(DataLoader): def __init__(self, randomize, *args, **kwargs): # fixed implementation, kwargs are filtered self.randomize = randomize or kwargs.pop("shuffle", False) super().__init__(*args, shuffle=randomize, **kwargs) dataloader = GoodImpl(False, []) new_dataloader = _update_dataloader(dataloader, dataloader.sampler) assert isinstance(new_dataloader, GoodImpl) def test_custom_torch_batch_sampler(): """This test asserts, that custom `BatchSampler`, with all the arguments, that are required in order to properly reinstantiate the class, is invoked properly. It also asserts, that during the reinstantiation, the wrapper of `__init__` method is not present anymore, therefore not setting `__pl_saved_{args,arg_names,kwargs}` attributes. """ class MyBatchSampler(BatchSampler): # Custom Batch sampler with extra argument and default value def __init__(self, sampler, extra_arg, drop_last=True): self.extra_arg = extra_arg super().__init__(sampler, 10, drop_last) sampler = RandomSampler(range(10)) with _replace_dunder_methods(BatchSampler): # instantiate within `_replace_dunder_method` context manager, simulating `*_dataloader` hooks batch_sampler = MyBatchSampler(sampler, "random_str") dataloader = DataLoader(range(10), batch_sampler=batch_sampler) # assert that passed information got saved assert dataloader.batch_sampler.__pl_saved_args == (sampler, "random_str") assert dataloader.batch_sampler.__pl_saved_kwargs == {} assert dataloader.batch_sampler.__pl_saved_arg_names == ("sampler", "extra_arg") assert dataloader.batch_sampler.__pl_saved_default_kwargs == {"drop_last": True} # updating dataloader, what happens on access of the dataloaders. # This should not fail, and would fail before support for custom args. dataloader = _update_dataloader(dataloader, dataloader.sampler) # Assert the `__init__` method is not replaced anymore and everything is instantiated to correct types batch_sampler = dataloader.batch_sampler assert isinstance(batch_sampler, MyBatchSampler) assert batch_sampler.extra_arg == "random_str" assert not hasattr(batch_sampler, "__pl_saved_kwargs") assert not hasattr(batch_sampler, "__pl_saved_arg_names") assert not hasattr(batch_sampler, "__pl_saved_args") assert not hasattr(batch_sampler, "__pl_saved_default_kwargs") def test_custom_torch_batch_sampler_doppelganger(): """Test we can reinstantiate a sampler that mimics PyTorch's BatchSampler even if it does not inherit from it. This is only possible if that sampler accepts the `batch_size` and `drop_last` arguments, and stores them as attributes. """ class BatchSamplerDoppelganger: """A batch sampler that mimics `torch.utils.data.BatchSampler` but does not inherit from it.""" def __init__(self, sampler, batch_size, drop_last): self.sampler = sampler self.batch_size = batch_size self.drop_last = drop_last def __iter__(self): while True: yield [0, 1, 2, 3] def __len__(self) -> int: return 4 batch_sampler = BatchSamplerDoppelganger(sampler=Mock(), batch_size=2, drop_last=True) dataloader = DataLoader(range(100), batch_sampler=batch_sampler) new_sampler = Mock() dataloader = _update_dataloader(dataloader, sampler=new_sampler) batch_sampler = dataloader.batch_sampler assert isinstance(batch_sampler, BatchSamplerDoppelganger) assert batch_sampler.sampler == new_sampler def test_custom_batch_sampler(): """Test that a custom (non-PyTorch) batch sampler requires the user to set `use_distributed_sampler=False`.""" class CustomBatchSampler: # not inheriting from `BatchSampler` def __iter__(self): while True: yield [0, 1, 2, 3] batch_sampler = CustomBatchSampler() dataloader = DataLoader(range(100), batch_sampler=batch_sampler) with pytest.raises(TypeError, match=r"can't inject a \(distributed\) sampler into your batch sampler"): _ = _update_dataloader(dataloader, sampler=Mock()) def test_custom_batch_sampler_no_sampler(): """Tests whether appropriate error is raised when the custom `BatchSampler` does not support sampler argument.""" class MyBatchSampler(BatchSampler): # Custom batch sampler, without sampler argument. def __init__(self, extra_arg): self.extra_arg = extra_arg super().__init__(RandomSampler(range(10)), 10, False) with _replace_dunder_methods(BatchSampler): # instantiate within `_replace_dunder_method` context manager, simulating `*_dataloader` hooks batch_sampler = MyBatchSampler("random_str") dataloader = DataLoader(range(10), batch_sampler=batch_sampler) # assert that passed information got saved assert dataloader.batch_sampler.__pl_saved_args == ("random_str",) assert dataloader.batch_sampler.__pl_saved_kwargs == {} assert dataloader.batch_sampler.__pl_saved_arg_names == ("extra_arg",) assert dataloader.batch_sampler.__pl_saved_default_kwargs == {} # Assert that error is raised with pytest.raises(TypeError, match="sampler into the batch sampler"): _ = _update_dataloader(dataloader, dataloader.sampler) def test_dataloader_kwargs_replacement_with_iterable_dataset(): """Test that DataLoader kwargs are not replaced when using Iterable Dataset.""" dataset = RandomIterableDataset(7, 100) dataloader = DataLoader(dataset, batch_size=32) _, dl_kwargs = _get_dataloader_init_args_and_kwargs(dataloader, dataloader.sampler) assert dl_kwargs["sampler"] is None assert dl_kwargs["batch_sampler"] is None assert dl_kwargs["batch_size"] is dataloader.batch_size assert dl_kwargs["dataset"] is dataloader.dataset assert dl_kwargs["collate_fn"] is dataloader.collate_fn def test_dataloader_kwargs_replacement_with_array_default_comparison(): """Test that the comparison of attributes and default argument values works with arrays (truth value ambiguous). Regression test for issue #15408. """ dataset = RandomDataset(5, 100) class ArrayAttributeDataloader(DataLoader): def __init__(self, indices=None, **kwargs): super().__init__(dataset) self.indices = np.random.rand(2, 2) # an attribute we can't compare with == dataloader = ArrayAttributeDataloader(dataset) _, dl_kwargs = _get_dataloader_init_args_and_kwargs(dataloader, dataloader.sampler) assert dl_kwargs["indices"] is dataloader.indices def test_set_sampler_epoch(): # No samplers dataloader = Mock() dataloader.sampler = None dataloader.batch_sampler = None _set_sampler_epoch(dataloader, 55) # set_epoch not callable dataloader = Mock() dataloader.sampler.set_epoch = None dataloader.batch_sampler.set_epoch = None _set_sampler_epoch(dataloader, 55) # set_epoch callable dataloader = Mock() _set_sampler_epoch(dataloader, 55) dataloader.sampler.set_epoch.assert_called_once_with(55) dataloader.batch_sampler.sampler.set_epoch.assert_called_once_with(55) @pytest.mark.parametrize( ("cpu_count", "local_world_size", "expected"), [ (0, 1, 1), (1, 1, 1), (2, 1, 2 - 1), (1, 2, 1), (2, 2, 1), (3, 2, 1), (4, 2, 2 - 1), (4, 3, 1), (4, 1, 4 - 1), ], ) @pytest.mark.parametrize( "affinity", [ False, pytest.param( True, marks=pytest.mark.skipif( not hasattr(os, "sched_getaffinity"), reason="OS does not support restricting CPU cores" ), ), ], ) @mock.patch("lightning.fabric.utilities.data.os.cpu_count") def test_suggested_max_num_workers(cpu_count_mock, affinity, cpu_count, local_world_size, expected, monkeypatch): if affinity: monkeypatch.setattr(lightning.fabric.utilities.data.os, "sched_getaffinity", lambda _: list(range(cpu_count))) else: monkeypatch.delattr(lightning.fabric.utilities.data.os, "sched_getaffinity", raising=False) cpu_count_mock.return_value = cpu_count assert suggested_max_num_workers(local_world_size) == expected @pytest.mark.parametrize("invalid", [-1, 0]) def test_suggested_max_num_workers_input_validation(invalid): with pytest.raises(ValueError, match="should be >= 1"): suggested_max_num_workers(invalid) @pytest.mark.parametrize("cpu_count", [1, 2, 3]) @pytest.mark.parametrize("local_world_size", [1, 2, 3]) def test_suggested_max_num_workers_not_triggering_torch_warning(local_world_size, cpu_count, monkeypatch): """Test that our suggestion for num workers doesn't trigger a warning in the DataLoader for too many workers.""" monkeypatch.delattr(lightning.fabric.utilities.data.os, "sched_getaffinity", raising=False) monkeypatch.delattr(torch.utils.data.dataloader.os, "sched_getaffinity", raising=False) monkeypatch.setattr(lightning.fabric.utilities.data.os, "cpu_count", lambda: cpu_count) monkeypatch.setattr(torch.utils.data.dataloader.os, "cpu_count", lambda: cpu_count) # The dataloader runs a check in `DataLoader.check_worker_number_rationality` with pytest.warns(UserWarning, match="This DataLoader will create"): DataLoader(range(2), num_workers=(cpu_count + 1)) with no_warning_call(): DataLoader(range(2), num_workers=suggested_max_num_workers(local_world_size)) def test_state(): # init via dict inputs = {"key1": 1, "key2": "abc"} state = AttributeDict(inputs) for key, value in inputs.items(): assert getattr(state, key) == value # init via kwargs inputs = {"key1": 1, "key2": "abc"} state = AttributeDict(**inputs) for key, value in inputs.items(): assert getattr(state, key) == value # update via dict state = AttributeDict() state.update({"key1": 1}) assert state.key1 == 1 # update via setter state = AttributeDict({"key1": 1}) state.key1 = 123 assert state.key1 == 123 with pytest.raises(AttributeError, match="has no attribute 'key3'"): _ = state.key3 # delete attribute del state.key1 assert "key1" not in state with pytest.raises(KeyError): del state.key3
ChangingDataLoader
python
google__pytype
pytype/pytd/visitors.py
{ "start": 71687, "end": 71789 }
class ____(Visitor): def VisitUnionType(self, _): return pytd.AnythingType()
ReplaceUnionsWithAny
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/no_redistribute_dependent/package.py
{ "start": 228, "end": 782 }
class ____(AutotoolsPackage): """Package with one dependency on a package that should not be redistributed""" homepage = "http://www.example.com" url = "http://www.example.com/no-redistribute-dependent-1.0.tar.gz" version("1.0", "0123456789abcdef0123456789abcdef") depends_on("no-redistribute") def install(self, spec, prefix): # sanity_check_prefix requires something in the install directory # Test requires overriding the one provided by `AutotoolsPackage` mkdirp(prefix.bin)
NoRedistributeDependent
python
realpython__materials
python-bytes/redis_client.py
{ "start": 80, "end": 4210 }
class ____: def __init__(self, address: str = "localhost", port: int = 6379) -> None: self._socket = socket.create_connection((address, port)) def __enter__(self) -> Self: return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: self._socket.close() def flush(self) -> None: self._socket.sendall(flush_command()) def ping(self) -> None: self._socket.sendall(ping_command()) def echo(self, message: str) -> None: self._socket.sendall(echo_command(message)) def last_save(self) -> None: self._socket.sendall(last_save_command()) def keys(self, pattern: str = "*") -> None: self._socket.sendall(keys_command(pattern)) def get(self, key: str) -> None: self._socket.sendall(get_command(key)) def set(self, key: str, value: str, ex: int | None = None) -> None: self._socket.sendall(set_command(key, value, ex)) def delete(self, *keys: str) -> None: self._socket.sendall(del_command(*keys)) def get_response(self) -> str | int | None | list: line = bytearray() while not line.endswith(b"\r\n"): line.extend(self._socket.recv(1)) match prefix := line[:1]: case b"+" | b"-": return line[1:-2].decode("ascii") case b":": return int(line[1:-2]) case b"$": if (length := int(line[1:])) == -1: return None else: data = self._socket.recv(length + 2) return data[:-2].decode("utf-8") case b"*": return [self.get_response() for _ in range(int(line[1:]))] case _: raise ValueError(f"Unsupported type: {prefix}") def flush_command() -> bytes: return array(bulk_string("FLUSHDB")) def ping_command() -> bytes: return array(bulk_string("PING")) def echo_command(message: str) -> bytes: return array(bulk_string("ECHO"), bulk_string(message)) def keys_command(pattern: str) -> bytes: return array(bulk_string("KEYS"), bulk_string(pattern)) def set_command(key: str, value: str, ex: int | None) -> bytes: items = [ bulk_string("SET"), bulk_string(key), bulk_string(value), ] if ex is not None: items.append(bulk_string("EX")) items.append(bulk_string(str(ex))) return array(*items) def get_command(key: str) -> bytes: return array(bulk_string("GET"), bulk_string(key)) def del_command(*keys: str) -> bytes: return array(bulk_string("DEL"), *map(bulk_string, keys)) def last_save_command() -> bytes: return array(bulk_string("LASTSAVE")) def array(*items: bytes) -> bytes: binary = bytearray(f"*{len(items)}\r\n".encode("ascii")) for item in items: binary.extend(item) return bytes(binary) def bulk_string(value: str) -> bytes: binary = value.encode("utf-8") return f"${len(binary)}\r\n".encode("utf-8") + binary + b"\r\n" def simple_string(value: str) -> bytes: return f"+{value}\r\n".encode("ascii", errors="strict") def integer(value: int) -> bytes: return f":{value}\r\n".encode("ascii") if __name__ == "__main__": with RedisClient() as redis: commands: list[Callable] = [ redis.ping, partial(redis.echo, "Café"), redis.last_save, redis.flush, partial(redis.get, "key"), partial(redis.set, "key1", "value1"), partial(redis.set, "key2", "value2"), partial(redis.get, "key1"), redis.keys, partial(redis.delete, "key1", "key2"), partial(redis.set, "key3", "value3", 5), ] for command in commands: if isinstance(command, partial): args = " ".join([str(x) for x in command.args]) print(f"{command.func.__name__.upper()} {args}") else: print(f"{command.__name__.upper()}") command() print(repr(redis.get_response())) print()
RedisClient
python
getsentry__sentry
tests/sentry/codecov/endpoints/test_test_suites.py
{ "start": 520, "end": 3219 }
class ____(APITestCase): endpoint_name = "sentry-api-0-test-suites" def setUp(self) -> None: super().setUp() self.user = self.create_user(email="user@example.com") self.organization = self.create_organization(owner=self.user) self.integration = self.create_integration( organization=self.organization, external_id="1234", name="testowner", provider="github", ) self.login_as(user=self.user) def reverse_url(self, owner="testowner", repository="testrepo"): """Custom reverse URL method to handle required URL parameters""" return reverse( self.endpoint_name, kwargs={ "organization_id_or_slug": self.organization.slug, "owner": self.integration.id, "repository": repository, }, ) @patch("sentry.codecov.endpoints.test_suites.test_suites.CodecovApiClient") def test_get_returns_mock_response(self, mock_codecov_client_class: MagicMock) -> None: mock_codecov_client_instance = Mock() mock_response = Mock() mock_response.json.return_value = mock_graphql_response_populated mock_codecov_client_instance.query.return_value = mock_response mock_codecov_client_class.return_value = mock_codecov_client_instance url = self.reverse_url() response = self.client.get(url) mock_codecov_client_class.assert_called_once_with(git_provider_org="testowner") assert mock_codecov_client_instance.query.call_count == 1 assert response.status_code == 200 assert response.data["testSuites"] == ["suite-1", "another-2", "suite-3"] @patch("sentry.codecov.endpoints.test_suites.test_suites.CodecovApiClient") def test_get_with_interval_query_param(self, mock_codecov_client_class: MagicMock) -> None: mock_codecov_client_instance = Mock() mock_response = Mock() mock_response.json.return_value = mock_graphql_response_populated mock_codecov_client_instance.query.return_value = mock_response mock_codecov_client_class.return_value = mock_codecov_client_instance url = self.reverse_url() response = self.client.get(url, {"term": "suite-1"}) assert response.status_code == 200 mock_codecov_client_class.assert_called_once_with(git_provider_org="testowner") mock_codecov_client_instance.query.assert_called_once_with( query=ANY, variables={ "owner": "testowner", "repo": "testrepo", "term": "suite-1", }, )
TestSuitesEndpointTest
python
viewflow__viewflow
viewflow/workflow/flow/viewset.py
{ "start": 5495, "end": 6615 }
class ____(metaclass=ViewsetMeta): """ Bulk Assign Tasks """ tasks_assign_view_class = views.BulkAssignTasksActionView def get_tasks_assign_view_kwargs(self, **kwargs): return self.filter_kwargs(self.tasks_assign_view_class, **kwargs) @viewprop def tasks_assign_view(self): return self.tasks_assign_view_class.as_view( **self.get_tasks_assign_view_kwargs() ) @property def tasks_assign_path(self): return path("queue/assign/", self.tasks_assign_view, name="tasks_assign") """ Bulk Unassign Tasks """ tasks_unassign_view_class = views.BulkUnassignTasksActionView def get_tasks_unassign_view_kwargs(self, **kwargs): return self.filter_kwargs(self.tasks_unassign_view_class, **kwargs) @viewprop def tasks_unassign_view(self): return self.tasks_unassign_view_class.as_view( **self.get_tasks_unassign_view_kwargs() ) @property def tasks_unassign_path(self): return path("inbox/unassign/", self.tasks_unassign_view, name="tasks_unassign")
BulkActionsViewsMixin
python
lepture__authlib
authlib/jose/rfc7518/jws_algs.py
{ "start": 1993, "end": 3013 }
class ____(JWSAlgorithm): """RSA using SHA algorithms for JWS. Available algorithms: - RS256: RSASSA-PKCS1-v1_5 using SHA-256 - RS384: RSASSA-PKCS1-v1_5 using SHA-384 - RS512: RSASSA-PKCS1-v1_5 using SHA-512 """ SHA256 = hashes.SHA256 SHA384 = hashes.SHA384 SHA512 = hashes.SHA512 def __init__(self, sha_type): self.name = f"RS{sha_type}" self.description = f"RSASSA-PKCS1-v1_5 using SHA-{sha_type}" self.hash_alg = getattr(self, f"SHA{sha_type}") self.padding = padding.PKCS1v15() def prepare_key(self, raw_data): return RSAKey.import_key(raw_data) def sign(self, msg, key): op_key = key.get_op_key("sign") return op_key.sign(msg, self.padding, self.hash_alg()) def verify(self, msg, sig, key): op_key = key.get_op_key("verify") try: op_key.verify(sig, msg, self.padding, self.hash_alg()) return True except InvalidSignature: return False
RSAAlgorithm
python
numpy__numpy
benchmarks/benchmarks/bench_io.py
{ "start": 1669, "end": 1835 }
class ____(Benchmark): def setup(self): self.squares = get_squares() def time_vb_savez_squares(self): np.savez('tmp.npz', **self.squares)
Savez
python
getsentry__sentry
tests/sentry/api/test_event_search.py
{ "start": 10746, "end": 54159 }
class ____(SimpleTestCase): """ These test cases cannot be represented by the test data used to drive the ParseSearchQueryTest. """ def test_key_remapping(self) -> None: config = SearchConfig(key_mappings={"target_value": ["someValue", "legacy-value"]}) assert parse_search_query( "someValue:123 legacy-value:456 normal_value:hello", config=config ) == [ SearchFilter( key=SearchKey(name="target_value"), operator="=", value=SearchValue("123") ), SearchFilter( key=SearchKey(name="target_value"), operator="=", value=SearchValue("456") ), SearchFilter( key=SearchKey(name="normal_value"), operator="=", value=SearchValue("hello") ), ] def test_paren_expression(self) -> None: assert parse_search_query("(x:1 OR y:1) AND z:1") == [ ParenExpression( children=[ SearchFilter( key=SearchKey(name="x"), operator="=", value=SearchValue(raw_value="1") ), "OR", SearchFilter( key=SearchKey(name="y"), operator="=", value=SearchValue(raw_value="1") ), ] ), "AND", SearchFilter(key=SearchKey(name="z"), operator="=", value=SearchValue(raw_value="1")), ] def test_paren_expression_of_empty_string(self) -> None: assert parse_search_query('("")') == parse_search_query('""') == [] def test_paren_expression_with_bool_disabled(self) -> None: config = SearchConfig.create_from(default_config, allow_boolean=False) ret = parse_search_query("( x:1 )", config=config) assert ret == [ SearchFilter( key=SearchKey(name="message"), operator="=", value=SearchValue(raw_value="( x:1 )") ) ] def test_paren_expression_to_query_string(self) -> None: (val,) = parse_search_query("(has:1 random():<5)") assert isinstance(val, ParenExpression) assert val.to_query_string() == "(has:=1 random():<5.0)" def test_bool_operator_with_bool_disabled(self) -> None: config = SearchConfig.create_from(default_config, allow_boolean=False) with pytest.raises(InvalidSearchQuery) as excinfo: parse_search_query("x:1 OR y:1", config=config) (msg,) = excinfo.value.args assert msg == 'Boolean statements containing "OR" or "AND" are not supported in this search' def test_wildcard_free_text(self) -> None: config = SearchConfig.create_from(default_config, wildcard_free_text=True) assert parse_search_query("foo", config=config) == [ SearchFilter( key=SearchKey(name="message"), operator="=", value=SearchValue(raw_value="*foo*") ) ] # already wildcarded assert parse_search_query("*foo", config=config) == [ SearchFilter( key=SearchKey(name="message"), operator="=", value=SearchValue(raw_value="*foo") ) ] @patch("sentry.search.events.builder.base.BaseQueryBuilder.get_field_type") def test_size_filter(self, mock_type: MagicMock) -> None: config = SearchConfig() mock_type.return_value = "gigabyte" assert parse_search_query("measurements.foo:>5gb measurements.bar:<3pb", config=config) == [ SearchFilter( key=SearchKey(name="measurements.foo"), operator=">", value=SearchValue(5 * 1000**3), ), SearchFilter( key=SearchKey(name="measurements.bar"), operator="<", value=SearchValue(3 * 1000**5), ), ] def test_size_field_unrelated_field(self) -> None: assert parse_search_query("something:5gb") == [ SearchFilter( key=SearchKey(name="something"), operator="=", value=SearchValue(raw_value="5gb") ) ] @patch("sentry.search.events.builder.base.BaseQueryBuilder.get_field_type") def test_ibyte_size_filter(self, mock_type: MagicMock) -> None: config = SearchConfig() mock_type.return_value = "gibibyte" assert parse_search_query( "measurements.foo:>5gib measurements.bar:<3pib", config=config ) == [ SearchFilter( key=SearchKey(name="measurements.foo"), operator=">", value=SearchValue(5 * 1024**3), ), SearchFilter( key=SearchKey(name="measurements.bar"), operator="<", value=SearchValue(3 * 1024**5), ), ] @patch("sentry.search.events.builder.base.BaseQueryBuilder.get_field_type") def test_aggregate_size_filter(self, mock_type: MagicMock) -> None: config = SearchConfig() mock_type.return_value = "gigabyte" assert parse_search_query( "p50(measurements.foo):>5gb p100(measurements.bar):<3pb", config=config ) == [ SearchFilter( key=SearchKey(name="p50(measurements.foo)"), operator=">", value=SearchValue(5 * 1000**3), ), SearchFilter( key=SearchKey(name="p100(measurements.bar)"), operator="<", value=SearchValue(3 * 1000**5), ), ] def test_aggregate_empty_quoted_arg(self) -> None: assert parse_search_query('p50(""):5') == [ AggregateFilter( key=AggregateKey(name='p50("")'), operator="=", value=SearchValue(raw_value=5.0) ) ] @patch("sentry.search.events.builder.base.BaseQueryBuilder.get_field_type") def test_aggregate_ibyte_size_filter(self, mock_type: MagicMock) -> None: config = SearchConfig() mock_type.return_value = "gibibyte" assert parse_search_query( "p50(measurements.foo):>5gib p100(measurements.bar):<3pib", config=config ) == [ SearchFilter( key=SearchKey(name="p50(measurements.foo)"), operator=">", value=SearchValue(5 * 1024**3), ), SearchFilter( key=SearchKey(name="p100(measurements.bar)"), operator="<", value=SearchValue(3 * 1024**5), ), ] @patch("sentry.search.events.builder.base.BaseQueryBuilder.get_field_type") def test_duration_measurement_filter(self, mock_type: MagicMock) -> None: config = SearchConfig() mock_type.return_value = "second" assert parse_search_query("measurements.foo:>5s measurements.bar:<3m", config=config) == [ SearchFilter( key=SearchKey(name="measurements.foo"), operator=">", value=SearchValue(5 * 1000), ), SearchFilter( key=SearchKey(name="measurements.bar"), operator="<", value=SearchValue(3 * 1000 * 60), ), ] def test_invalid_duration(self) -> None: with pytest.raises(InvalidSearchQuery) as excinfo: parse_search_query("transaction.duration:>1111111111w") (msg,) = excinfo.value.args assert msg == "1111111111w is too large of a value, the maximum value is 999999999 days" @patch("sentry.search.events.builder.base.BaseQueryBuilder.get_field_type") def test_aggregate_duration_measurement_filter(self, mock_type: MagicMock) -> None: config = SearchConfig() mock_type.return_value = "minute" assert parse_search_query( "p50(measurements.foo):>5s p100(measurements.bar):<3m", config=config ) == [ SearchFilter( key=SearchKey(name="p50(measurements.foo)"), operator=">", value=SearchValue(5 * 1000), ), SearchFilter( key=SearchKey(name="p100(measurements.bar)"), operator="<", value=SearchValue(3 * 1000 * 60), ), ] def test_invalid_aggregate_duration(self) -> None: with pytest.raises(InvalidSearchQuery) as excinfo: parse_search_query("trend_difference():>1111111111w") (msg,) = excinfo.value.args assert msg == "1111111111w is too large of a value, the maximum value is 999999999 days" @patch("sentry.search.events.builder.base.BaseQueryBuilder.get_field_type") def test_numeric_measurement_filter(self, mock_type: MagicMock) -> None: config = SearchConfig() mock_type.return_value = "number" assert parse_search_query("measurements.foo:>5k measurements.bar:<3m", config=config) == [ SearchFilter( key=SearchKey(name="measurements.foo"), operator=">", value=SearchValue(5 * 1000), ), SearchFilter( key=SearchKey(name="measurements.bar"), operator="<", value=SearchValue(3 * 1_000_000), ), ] @patch("sentry.search.events.builder.base.BaseQueryBuilder.get_field_type") def test_aggregate_numeric_measurement_filter(self, mock_type: MagicMock) -> None: config = SearchConfig() mock_type.return_value = "number" assert parse_search_query( "p50(measurements.foo):>5k p100(measurements.bar):<3m", config=config ) == [ SearchFilter( key=SearchKey(name="p50(measurements.foo)"), operator=">", value=SearchValue(5 * 1000), ), SearchFilter( key=SearchKey(name="p100(measurements.bar)"), operator="<", value=SearchValue(3 * 1_000_000), ), ] def test_rel_time_filter(self) -> None: now = timezone.now() with freeze_time(now): assert parse_search_query("time:+7d") == [ SearchFilter( key=SearchKey(name="time"), operator="<=", value=SearchValue(raw_value=now - timedelta(days=7)), ) ] assert parse_search_query("time:-2w") == [ SearchFilter( key=SearchKey(name="time"), operator=">=", value=SearchValue(raw_value=now - timedelta(days=14)), ) ] assert parse_search_query("random:-2w") == [ SearchFilter(key=SearchKey(name="random"), operator="=", value=SearchValue("-2w")) ] def test_invalid_rel_time_filter(self) -> None: with pytest.raises(InvalidSearchQuery) as excinfo: parse_search_query(f'time:+{"1" * 9999}d') (msg,) = excinfo.value.args assert msg.endswith(" is not a valid datetime query") def test_aggregate_rel_time_filter(self) -> None: now = timezone.now() with freeze_time(now): assert parse_search_query("last_seen():+7d") == [ AggregateFilter( key=AggregateKey(name="last_seen()"), operator="<=", value=SearchValue(raw_value=now - timedelta(days=7)), ) ] assert parse_search_query("last_seen():-2w") == [ AggregateFilter( key=AggregateKey(name="last_seen()"), operator=">=", value=SearchValue(raw_value=now - timedelta(days=14)), ) ] assert parse_search_query("random():-2w") == [ SearchFilter(key=SearchKey(name="random()"), operator="=", value=SearchValue("-2w")) ] def test_invalid_aggregate_rel_time_filter(self) -> None: with pytest.raises(InvalidSearchQuery) as excinfo: parse_search_query(f'last_seen():+{"1" * 9999}d') (msg,) = excinfo.value.args assert msg.endswith(" is not a valid datetime query") def test_invalid_date_filter(self) -> None: with pytest.raises(InvalidSearchQuery) as excinfo: parse_search_query("time:>0000-00-00") (msg,) = excinfo.value.args assert msg == "0000-00-00 is not a valid ISO8601 date query" def test_specific_time_filter(self) -> None: assert parse_search_query("time:2018-01-01") == [ SearchFilter( key=SearchKey(name="time"), operator=">=", value=SearchValue(raw_value=datetime.datetime(2018, 1, 1, tzinfo=datetime.UTC)), ), SearchFilter( key=SearchKey(name="time"), operator="<", value=SearchValue(raw_value=datetime.datetime(2018, 1, 2, tzinfo=datetime.UTC)), ), ] assert parse_search_query("time:2018-01-01T05:06:07Z") == [ SearchFilter( key=SearchKey(name="time"), operator=">=", value=SearchValue( raw_value=datetime.datetime(2018, 1, 1, 5, 1, 7, tzinfo=datetime.UTC) ), ), SearchFilter( key=SearchKey(name="time"), operator="<", value=SearchValue( raw_value=datetime.datetime(2018, 1, 1, 5, 12, 7, tzinfo=datetime.UTC) ), ), ] assert parse_search_query("time:2018-01-01T05:06:07+00:00") == [ SearchFilter( key=SearchKey(name="time"), operator=">=", value=SearchValue( raw_value=datetime.datetime(2018, 1, 1, 5, 1, 7, tzinfo=datetime.UTC) ), ), SearchFilter( key=SearchKey(name="time"), operator="<", value=SearchValue( raw_value=datetime.datetime(2018, 1, 1, 5, 12, 7, tzinfo=datetime.UTC) ), ), ] assert parse_search_query("random:2018-01-01T05:06:07") == [ SearchFilter( key=SearchKey(name="random"), operator="=", value=SearchValue(raw_value="2018-01-01T05:06:07"), ) ] def test_invalid_time_format(self) -> None: with pytest.raises(InvalidSearchQuery) as excinfo: parse_search_query("time:0000-00-00") (msg,) = excinfo.value.args assert msg == "0000-00-00 is not a valid datetime query" def test_aggregate_time_filter(self) -> None: assert parse_search_query("last_seen():>2025-01-01") == [ AggregateFilter( key=AggregateKey(name="last_seen()"), operator=">", value=SearchValue( raw_value=datetime.datetime(2025, 1, 1, 0, 0, tzinfo=datetime.UTC) ), ) ] assert parse_search_query("random():>2025-01-01") == [ AggregateFilter( key=AggregateKey(name="random()"), operator="=", value=SearchValue(raw_value=">2025-01-01"), ) ] def test_aggregate_time_filter_invalid_date_format(self) -> None: with pytest.raises(InvalidSearchQuery) as excinfo: parse_search_query("last_seen():>0000-00-00") (msg,) = excinfo.value.args assert msg == "0000-00-00 is not a valid ISO8601 date query" def test_timestamp_rollup(self) -> None: assert parse_search_query("timestamp.to_hour:2018-01-01T05:06:07+00:00") == [ SearchFilter( key=SearchKey(name="timestamp.to_hour"), operator=">=", value=SearchValue( raw_value=datetime.datetime(2018, 1, 1, 5, 1, 7, tzinfo=datetime.UTC) ), ), SearchFilter( key=SearchKey(name="timestamp.to_hour"), operator="<", value=SearchValue( raw_value=datetime.datetime(2018, 1, 1, 5, 12, 7, tzinfo=datetime.UTC) ), ), ] def test_percentage_filter(self) -> None: assert parse_search_query("failure_rate():<5%") == [ AggregateFilter( key=AggregateKey(name="failure_rate()"), operator="<", value=SearchValue(raw_value=0.05), ) ] assert parse_search_query("last_seen():<5%") == [ AggregateFilter( key=AggregateKey(name="last_seen()"), operator="=", value=SearchValue(raw_value="<5"), ) ] def test_percentage_filter_unknown_column(self) -> None: with pytest.raises(InvalidSearchQuery) as excinfo: parse_search_query("unknown():<5%") (msg,) = excinfo.value.args assert msg == "unknown is not a valid function" def test_binary_operators(self) -> None: ret_or = parse_search_query("has:release or has:something_else") assert ret_or == [ SearchFilter( key=SearchKey(name="release"), operator="!=", value=SearchValue(raw_value="") ), "OR", SearchFilter( key=SearchKey(name="something_else"), operator="!=", value=SearchValue(raw_value="") ), ] ret_and = parse_search_query("has:release and has:something_else") assert ret_and == [ SearchFilter( key=SearchKey(name="release"), operator="!=", value=SearchValue(raw_value="") ), "AND", SearchFilter( key=SearchKey(name="something_else"), operator="!=", value=SearchValue(raw_value="") ), ] def test_flags(self) -> None: ret_flags = parse_search_query("flags[feature.one]:true") assert ret_flags == [ SearchFilter( key=SearchKey(name="flags[feature.one]"), operator="=", value=SearchValue(raw_value="true"), ) ] ret_flags_numeric = parse_search_query("flags[feature.two,number]:123") assert ret_flags_numeric == [ SearchFilter( key=SearchKey(name="flags[feature.two,number]"), operator="=", value=SearchValue(raw_value="123"), ) ] ret_flags_string = parse_search_query("flags[feature.three,string]:prod") assert ret_flags_string == [ SearchFilter( key=SearchKey(name="flags[feature.three,string]"), operator="=", value=SearchValue(raw_value="prod"), ) ] def test_has_tag(self) -> None: # unquoted key assert parse_search_query("has:release") == [ SearchFilter( key=SearchKey(name="release"), operator="!=", value=SearchValue(raw_value="") ) ] # quoted key assert parse_search_query('has:"hi:there"') == [ SearchFilter( key=SearchKey(name="hi:there"), operator="!=", value=SearchValue(raw_value="") ) ] # malformed key with pytest.raises(InvalidSearchQuery): parse_search_query('has:"hi there"') def test_not_has_tag(self) -> None: # unquoted key assert parse_search_query("!has:release") == [ SearchFilter(key=SearchKey(name="release"), operator="=", value=SearchValue("")) ] # quoted key assert parse_search_query('!has:"hi:there"') == [ SearchFilter(key=SearchKey(name="hi:there"), operator="=", value=SearchValue("")) ] def test_allowed_keys(self) -> None: config = SearchConfig(allowed_keys={"good_key"}) assert parse_search_query("good_key:123 bad_key:123 text") == [ SearchFilter(key=SearchKey(name="good_key"), operator="=", value=SearchValue("123")), SearchFilter(key=SearchKey(name="bad_key"), operator="=", value=SearchValue("123")), SearchFilter(key=SearchKey(name="message"), operator="=", value=SearchValue("text")), ] with pytest.raises(InvalidSearchQuery, match="Invalid key for this search"): assert parse_search_query("good_key:123 bad_key:123 text", config=config) assert parse_search_query("good_key:123 text", config=config) == [ SearchFilter(key=SearchKey(name="good_key"), operator="=", value=SearchValue("123")), SearchFilter(key=SearchKey(name="message"), operator="=", value=SearchValue("text")), ] def test_blocked_keys(self) -> None: config = SearchConfig(blocked_keys={"bad_key"}) assert parse_search_query("some_key:123 bad_key:123 text") == [ SearchFilter(key=SearchKey(name="some_key"), operator="=", value=SearchValue("123")), SearchFilter(key=SearchKey(name="bad_key"), operator="=", value=SearchValue("123")), SearchFilter(key=SearchKey(name="message"), operator="=", value=SearchValue("text")), ] with pytest.raises(InvalidSearchQuery, match="Invalid key for this search: bad_key"): assert parse_search_query("some_key:123 bad_key:123 text", config=config) assert parse_search_query("some_key:123 some_other_key:456 text", config=config) == [ SearchFilter(key=SearchKey(name="some_key"), operator="=", value=SearchValue("123")), SearchFilter( key=SearchKey(name="some_other_key"), operator="=", value=SearchValue("456") ), SearchFilter(key=SearchKey(name="message"), operator="=", value=SearchValue("text")), ] def test_invalid_aggregate_column_with_duration_filter(self) -> None: with self.assertRaisesMessage( InvalidSearchQuery, expected_message="avg: column argument invalid: stack.colno is not a numeric column", ): parse_search_query("avg(stack.colno):>500s") def test_invalid_numeric_aggregate_filter(self) -> None: with self.assertRaisesMessage( InvalidSearchQuery, "is not a valid number suffix, must be k, m or b" ): parse_search_query("min(measurements.size):3s") with self.assertRaisesMessage( InvalidSearchQuery, "is not a valid number suffix, must be k, m or b" ): parse_search_query("count_if(measurements.fcp, greater, 5s):3s") def test_is_query_unsupported(self) -> None: with pytest.raises( InvalidSearchQuery, match=".*queries are not supported in this search.*" ): parse_search_query("is:unassigned") def test_is_query_when_configured(self) -> None: config = SearchConfig.create_from( default_config, is_filter_translation={ "assigned": ("status", ("unassigned", False)), "unassigned": ("status", ("unasssigned", True)), }, ) ret = parse_search_query("is:assigned", config=config) assert ret == [ SearchFilter( key=SearchKey(name="status"), operator="=", value=SearchValue(raw_value=("unassigned", False)), # type: ignore[arg-type] # XXX: soon ) ] def test_is_query_invalid_is_value_when_configured(self) -> None: config = SearchConfig.create_from( default_config, is_filter_translation={ "assigned": ("status", ("unassigned", False)), "unassigned": ("status", ("unasssigned", True)), }, ) with pytest.raises(InvalidSearchQuery) as excinfo: parse_search_query("is:unrelated", config=config) (msg,) = excinfo.value.args assert msg == "Invalid value for \"is\" search, valid values are ['assigned', 'unassigned']" def test_is_query_invalid_is_value_syntax(self) -> None: config = SearchConfig.create_from( default_config, is_filter_translation={ "assigned": ("status", ("unassigned", False)), "unassigned": ("status", ("unasssigned", True)), }, ) with pytest.raises(InvalidSearchQuery) as excinfo: parse_search_query("is:[assigned]", config=config) (msg,) = excinfo.value.args assert msg == '"in" syntax invalid for "is" search' def test_escaping_asterisk(self) -> None: # the asterisk is escaped with a preceding backslash, so it's a literal and not a wildcard search_filters = parse_search_query(r"title:a\*b") assert search_filters == [ SearchFilter(key=SearchKey(name="title"), operator="=", value=SearchValue(r"a\*b")) ] search_filter = search_filters[0] # the slash should be removed in the final value assert isinstance(search_filter, SearchFilter) assert search_filter.value.value == "a*b" # the first and last asterisks arent escaped with a preceding backslash, so they're # wildcards and not literals search_filters = parse_search_query(r"title:*\**") assert search_filters == [ SearchFilter(key=SearchKey(name="title"), operator="=", value=SearchValue(r"*\**")) ] search_filter = search_filters[0] assert isinstance(search_filter, SearchFilter) assert search_filter.value.value == r"^.*\*.*$" @pytest.mark.xfail(reason="escaping backslashes is not supported yet") def test_escaping_backslashes(self) -> None: search_filters = parse_search_query(r"title:a\\b") assert search_filters == [ SearchFilter(key=SearchKey(name="title"), operator="=", value=SearchValue(r"a\\b")) ] search_filter = search_filters[0] # the extra slash should be removed in the final value assert isinstance(search_filter, SearchFilter) assert search_filter.value.value == r"a\b" @pytest.mark.xfail(reason="escaping backslashes is not supported yet") def test_trailing_escaping_backslashes(self) -> None: search_filters = parse_search_query(r"title:a\\") assert search_filters == [ SearchFilter(key=SearchKey(name="title"), operator="=", value=SearchValue(r"a\\")) ] search_filter = search_filters[0] # the extra slash should be removed in the final value assert isinstance(search_filter, SearchFilter) assert search_filter.value.value == "a\\" def test_escaping_quotes(self) -> None: search_filters = parse_search_query(r"title:a\"b") assert search_filters == [ SearchFilter(key=SearchKey(name="title"), operator="=", value=SearchValue(r'a"b')) ] search_filter = search_filters[0] # the slash should be removed in the final value assert isinstance(search_filter, SearchFilter) assert search_filter.value.value == 'a"b' @pytest.mark.parametrize( "raw,result", [ (r"", r""), (r"foo", r"foo"), (r"foo*bar", r"^foo.*bar$"), (r"foo\*bar", r"foo*bar"), (r"foo\\*bar", r"^foo\\.*bar$"), (r"foo\\\*bar", r"foo\\*bar"), (r"foo*", r"^foo.*$"), (r"foo\*", r"foo*"), (r"foo\\*", r"^foo\\.*$"), (r"foo\\\*", r"foo\\*"), (r"*bar", r"^.*bar$"), (r"\*bar", r"*bar"), (r"\\*bar", r"^\\.*bar$"), (r"\\\*bar", r"\\*bar"), (r"*\**", r"^.*\*.*$"), (r"\*a\*b\*c\*", r"*a*b*c*"), (r"\*\*\*aaa\*\*\*", r"***aaa***"), ], ) def test_search_value(raw, result) -> None: search_value = SearchValue(raw) assert search_value.value == result @pytest.mark.parametrize( "query", [ "event.type:=transaction", "!event.type:[transaction]", "event.type:[transaction, event]", "event.type:[1, 2]", "transaction.duration:>=1.0", "transaction.duration:>1.0", "transaction.duration:=1.0", "transaction.duration:<=1.0", "transaction.duration:<1.0", ], ) def test_search_filter_to_query_string(query) -> None: """ Does a round trip (from query string to tokens and back to query string) """ filters = parse_search_query(query) assert len(filters) == 1 assert isinstance(filters[0], SearchFilter) actual = filters[0].to_query_string() assert actual == query @pytest.mark.parametrize( "value,expected_query_string", [ (1, "1"), ("abc", "abc"), ([1, 2, 3], "[1, 2, 3]"), (["a", "b", "c"], "[a, b, c]"), (datetime.datetime(2023, 10, 15, 11, 12, 13), "2023-10-15T11:12:13"), ], ) def test_search_value_to_query_string(value, expected_query_string) -> None: """ Test turning a QueryValue back to a string usable in a query string """ search_value = SearchValue(value) actual = search_value.to_query_string() assert actual == expected_query_string @pytest.mark.parametrize( ["value", "expected_kind", "expected_value"], [ (1, "other", 1), ("1", "other", "1"), ("*", "suffix", ""), # consider special casing this ("*foo", "suffix", "foo"), ("foo*", "prefix", "foo"), ("*foo*", "infix", "foo"), (r"\*foo", "other", r"*foo"), (r"\\*foo", "other", r"^\\.*foo$"), (r"foo\*", "other", r"foo*"), (r"foo\\*", "prefix", r"foo\\"), ("*f*o*o*", "other", "^.*f.*o.*o.*$"), (r"*foo\*", "suffix", r"foo*"), (r"*foo\\*", "infix", r"foo\\"), pytest.param("*Case*", "infix", "Case", id="infix casing is kept"), pytest.param("*Case", "suffix", "case", id="suffix is lower cased"), pytest.param("Case*", "prefix", "case", id="prefix is lower cased"), ], ) def test_search_value_classify_and_format_wildcard(value, expected_kind, expected_value) -> None: """ Test classifying the wildcard type into one of prefix/suffix/infix/other and formatting the value according to the classification results. """ search_value = SearchValue(value) kind, wildcard = search_value.classify_and_format_wildcard() assert (kind, wildcard) == (expected_kind, expected_value) @pytest.mark.parametrize( ["pattern", "clickhouse"], [ pytest.param("simple", "simple", id="simple"), pytest.param("wild * card", "wild % card", id="wildcard"), pytest.param("under_score", "under\\_score", id="underscore"), pytest.param("per%centage", "per\\%centage", id="percentage"), pytest.param("ast\\*erisk", "ast*erisk", id="asterisk"), pytest.param("c*o_m%p\\*lex", "c%o\\_m\\%p*lex", id="complex"), ], ) def test_translate_wildcard_as_clickhouse_pattern(pattern, clickhouse) -> None: assert translate_wildcard_as_clickhouse_pattern(pattern) == clickhouse @pytest.mark.parametrize( ["pattern"], [ pytest.param("\\."), pytest.param("\\%"), pytest.param("\\_"), ], ) def test_invalid_translate_wildcard_as_clickhouse_pattern(pattern) -> None: with pytest.raises(InvalidSearchQuery): assert translate_wildcard_as_clickhouse_pattern(pattern) @pytest.mark.parametrize( ["query", "key", "value"], [ pytest.param("tags[foo/bar]:baz", "message", "tags[foo/bar]:baz"), pytest.param("flags[foo/bar]:baz", "message", "flags[foo/bar]:baz"), pytest.param("tags[foo]:true", "tags[foo]", "true"), pytest.param("tags[foo,string]:true", "tags[foo,string]", "true"), pytest.param("tags[foo:bar,string]:true", "tags[foo:bar,string]", "true"), pytest.param("tags[foo,number]:0", "tags[foo,number]", "0"), pytest.param("tags[foo:bar,number]:0", "tags[foo:bar,number]", "0"), pytest.param("flags[foo]:true", "flags[foo]", "true"), pytest.param("flags[foo,string]:true", "flags[foo,string]", "true"), pytest.param("flags[foo:bar,string]:true", "flags[foo:bar,string]", "true"), pytest.param("flags[foo,number]:0", "flags[foo,number]", "0"), pytest.param("flags[foo:bar,number]:0", "flags[foo:bar,number]", "0"), ], ) def test_handles_special_character_in_tags_and_flags(query, key, value) -> None: parsed = parse_search_query(query) assert parsed == [SearchFilter(SearchKey(key), "=", SearchValue(value))] @pytest.mark.parametrize( ["query", "key"], [ pytest.param("has:tags[foo]", "tags[foo]"), pytest.param("has:tags[foo,string]", "tags[foo,string]"), pytest.param("has:tags[foo,number]", "tags[foo,number]"), pytest.param("has:tags[foo:bar]", "tags[foo:bar]"), pytest.param("has:tags[foo:bar,string]", "tags[foo:bar,string]"), pytest.param("has:tags[foo:bar,number]", "tags[foo:bar,number]"), pytest.param("has:flags[foo]", "flags[foo]"), pytest.param("has:flags[foo,string]", "flags[foo,string]"), pytest.param("has:flags[foo,number]", "flags[foo,number]"), pytest.param("has:flags[foo:bar]", "flags[foo:bar]"), pytest.param("has:flags[foo:bar,string]", "flags[foo:bar,string]"), pytest.param("has:flags[foo:bar,number]", "flags[foo:bar,number]"), ], ) def test_handles_has_tags_and_flags(query, key) -> None: parsed = parse_search_query(query) assert parsed == [SearchFilter(SearchKey(key), "!=", SearchValue(""))] @pytest.mark.parametrize( ["value", "wildcard_op", "expected"], [ # testing basic cases pytest.param("test", "", "test"), pytest.param("", WILDCARD_OPERATOR_MAP["contains"], ""), pytest.param("*test*", WILDCARD_OPERATOR_MAP["contains"], "*\\*test\\**"), pytest.param("\\*test\\*", WILDCARD_OPERATOR_MAP["contains"], "*\\*test\\**"), ], ) def test_gen_wildcard_value(value, wildcard_op, expected) -> None: assert gen_wildcard_value(value, wildcard_op) == expected @pytest.mark.parametrize( ["query", "expected"], [ # --- contains --- pytest.param( f"span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}test", "span.op:=^.*test.*$" ), pytest.param( f"span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}*test", "span.op:=^.*\\*test.*$" ), pytest.param( f"span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}test*", "span.op:=^.*test\\*.*$" ), pytest.param( f"span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}*test*", "span.op:=^.*\\*test\\*.*$", ), # --- contains quoted text --- pytest.param( f'span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}"test 1"', "span.op:=^.*test\\ 1.*$", ), pytest.param( f'span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}"*test 1"', "span.op:=^.*\\*test\\ 1.*$", ), pytest.param( f'span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}"test 1*"', "span.op:=^.*test\\ 1\\*.*$", ), pytest.param( f'span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}"*test 1*"', "span.op:=^.*\\*test\\ 1\\*.*$", ), # --- contains text list --- pytest.param( f"span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}[test, test2]", "span.op:[*test*, *test2*]", ), pytest.param( f"span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}[*test, *test2]", "span.op:[*\\*test*, *\\*test2*]", ), pytest.param( f"span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}[test*, test2*]", "span.op:[*test\\**, *test2\\**]", ), pytest.param( f"span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}[*test*, *test2*]", "span.op:[*\\*test\\**, *\\*test2\\**]", ), # --- contains quoted text list --- pytest.param( f'span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}["test 1", "test 2"]', "span.op:[*test 1*, *test 2*]", ), pytest.param( f'span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}["*test 1", "*test 2"]', "span.op:[*\\*test 1*, *\\*test 2*]", ), pytest.param( f'span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}["test 1*", "test 2*"]', "span.op:[*test 1\\**, *test 2\\**]", ), pytest.param( f'span.op:{WILDCARD_UNICODE}Contains{WILDCARD_UNICODE}["*test 1*", "*test 2*"]', "span.op:[*\\*test 1\\**, *\\*test 2\\**]", ), ], ) def test_handles_contains_wildcard_op_translations(query, expected) -> None: filters = parse_search_query(query) assert len(filters) == 1 assert isinstance(filters[0], SearchFilter) actual = filters[0].to_query_string() assert actual == expected @pytest.mark.parametrize( ["query", "expected"], [ # --- StartsWith --- pytest.param( f"span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}test", "span.op:=^test.*$" ), pytest.param( f"span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}*test", "span.op:=^\\*test.*$" ), pytest.param( f"span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}test*", "span.op:=^test\\*.*$" ), pytest.param( f"span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}*test*", "span.op:=^\\*test\\*.*$", ), # --- StartsWith quoted text --- pytest.param( f'span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}"test 1"', "span.op:=^test\\ 1.*$", ), pytest.param( f'span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}"*test 1"', "span.op:=^\\*test\\ 1.*$", ), pytest.param( f'span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}"test 1*"', "span.op:=^test\\ 1\\*.*$", ), pytest.param( f'span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}"*test 1*"', "span.op:=^\\*test\\ 1\\*.*$", ), # --- StartsWith text list --- pytest.param( f"span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}[test, test2]", "span.op:[test*, test2*]", ), pytest.param( f"span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}[*test, *test2]", "span.op:[\\*test*, \\*test2*]", ), pytest.param( f"span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}[test*, test2*]", "span.op:[test\\**, test2\\**]", ), pytest.param( f"span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}[*test*, *test2*]", "span.op:[\\*test\\**, \\*test2\\**]", ), # --- StartsWith quoted text list --- pytest.param( f'span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}["test 1", "test 2"]', "span.op:[test 1*, test 2*]", ), pytest.param( f'span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}["*test 1", "*test 2"]', "span.op:[\\*test 1*, \\*test 2*]", ), pytest.param( f'span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}["test 1*", "test 2*"]', "span.op:[test 1\\**, test 2\\**]", ), pytest.param( f'span.op:{WILDCARD_UNICODE}StartsWith{WILDCARD_UNICODE}["*test 1*", "*test 2*"]', "span.op:[\\*test 1\\**, \\*test 2\\**]", ), ], ) def test_handles_starts_with_wildcard_op_translations(query, expected) -> None: filters = parse_search_query(query) assert len(filters) == 1 assert isinstance(filters[0], SearchFilter) actual = filters[0].to_query_string() assert actual == expected @pytest.mark.parametrize( ["query", "expected"], [ # --- EndsWith --- pytest.param( f"span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}test", "span.op:=^.*test$" ), pytest.param( f"span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}*test", "span.op:=^.*\\*test$" ), pytest.param( f"span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}test*", "span.op:=^.*test\\*$" ), pytest.param( f"span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}*test*", "span.op:=^.*\\*test\\*$", ), # --- EndsWith quoted text --- pytest.param( f'span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}"test 1"', "span.op:=^.*test\\ 1$", ), pytest.param( f'span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}"*test 1"', "span.op:=^.*\\*test\\ 1$", ), pytest.param( f'span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}"test 1*"', "span.op:=^.*test\\ 1\\*$", ), pytest.param( f'span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}"*test 1*"', "span.op:=^.*\\*test\\ 1\\*$", ), # --- EndsWith text list --- pytest.param( f"span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}[test, test2]", "span.op:[*test, *test2]", ), pytest.param( f"span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}[*test, *test2]", "span.op:[*\\*test, *\\*test2]", ), pytest.param( f"span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}[test*, test2*]", "span.op:[*test\\*, *test2\\*]", ), pytest.param( f"span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}[*test*, *test2*]", "span.op:[*\\*test\\*, *\\*test2\\*]", ), # --- EndsWith quoted text list --- pytest.param( f'span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}["test 1", "test 2"]', "span.op:[*test 1, *test 2]", ), pytest.param( f'span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}["*test 1", "*test 2"]', "span.op:[*\\*test 1, *\\*test 2]", ), pytest.param( f'span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}["test 1*", "test 2*"]', "span.op:[*test 1\\*, *test 2\\*]", ), pytest.param( f'span.op:{WILDCARD_UNICODE}EndsWith{WILDCARD_UNICODE}["*test 1*", "*test 2*"]', "span.op:[*\\*test 1\\*, *\\*test 2\\*]", ), ], ) def test_handles_ends_with_wildcard_op_translations(query, expected) -> None: filters = parse_search_query(query) assert len(filters) == 1 assert isinstance(filters[0], SearchFilter) actual = filters[0].to_query_string() assert actual == expected
ParseSearchQueryBackendTest
python
pytorch__pytorch
test/jit/fixtures_srcs/fixtures_src.py
{ "start": 260, "end": 490 }
class ____(torch.nn.Module): def forward(self, a: Union[int, float, complex], b: Union[int, float, complex]): c = torch.linspace(a, b, steps=5) d = torch.linspace(a, b) return c, d
TestVersionedLinspaceV7
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-subsequences-after-one-inserting.py
{ "start": 46, "end": 701 }
class ____(object): def numOfSubsequences(self, s): """ :type s: str :rtype: int """ cnt_l = cnt_c = 0 cnt_t = s.count('T') mx_cnt_lt = cnt_lct = cnt_lc = cnt_ct = 0 for x in s: mx_cnt_lt = max(mx_cnt_lt, cnt_l*cnt_t) if x == 'L': cnt_l += 1 elif x == 'C': cnt_c += 1 cnt_lc += cnt_l elif x == 'T': cnt_t -= 1 cnt_ct += cnt_c cnt_lct += cnt_lc mx = max(mx_cnt_lt, cnt_l*cnt_t) return cnt_lct+max(cnt_ct, mx_cnt_lt, cnt_lc)
Solution
python
agronholm__apscheduler
tests/test_datastores.py
{ "start": 30088, "end": 31411 }
class ____: async def test_memory(self, memory_store: MemoryDataStore) -> None: assert repr(memory_store) == "MemoryDataStore()" async def test_sqlite(self, tmp_path: Path) -> None: from sqlalchemy import create_engine expected_path = str(tmp_path).replace("\\", "\\\\") engine = create_engine(f"sqlite:///{tmp_path}") data_store = SQLAlchemyDataStore(engine) assert repr(data_store) == ( f"SQLAlchemyDataStore(url='sqlite:///{expected_path}')" ) async def test_psycopg(self) -> None: from sqlalchemy.ext.asyncio import create_async_engine pytest.importorskip("psycopg", reason="psycopg not available") engine = create_async_engine( "postgresql+psycopg://postgres:secret@localhost/testdb" ) data_store = SQLAlchemyDataStore(engine, schema="myschema") assert repr(data_store) == ( "SQLAlchemyDataStore(url='postgresql+psycopg://postgres:***@localhost/" "testdb', schema='myschema')" ) async def test_mongodb(self) -> None: from pymongo import MongoClient with MongoClient() as client: data_store = MongoDBDataStore(client) assert repr(data_store) == "MongoDBDataStore(host=[('localhost', 27017)])"
TestRepr
python
airbytehq__airbyte
airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py
{ "start": 10889, "end": 11306 }
class ____(RawDataMixin, IncrementalAppsflyerStream): cursor_field = "event_time" additional_fields = additional_fields.uninstall_events def path( self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> str: return f"raw-data/export/app/{self.app_id}/organic_uninstall_events_report/v5"
OrganicUninstallEvents
python
kamyu104__LeetCode-Solutions
Python/day-of-the-year.py
{ "start": 29, "end": 621 }
class ____(object): def __init__(self): def dayOfMonth(M): return (28 if (M == 2) else 31-(M-1)%7%2) self.__lookup = [0]*12 for M in xrange(1, len(self.__lookup)): self.__lookup[M] += self.__lookup[M-1]+dayOfMonth(M) def dayOfYear(self, date): """ :type date: str :rtype: int """ Y, M, D = map(int, date.split("-")) leap = 1 if M > 2 and (((Y % 4 == 0) and (Y % 100 != 0)) or (Y % 400 == 0)) else 0 return self.__lookup[M-1]+D+leap # Time: O(1) # Space: O(1)
Solution
python
getsentry__sentry
src/sentry/models/group.py
{ "start": 21522, "end": 41134 }
class ____(Model): """ Aggregated message which summarizes a set of Events. """ __relocation_scope__ = RelocationScope.Excluded project = FlexibleForeignKey("sentry.Project") logger = models.CharField( max_length=64, blank=True, default=str(DEFAULT_LOGGER_NAME), db_index=True ) level = BoundedPositiveIntegerField( choices=[(key, str(val)) for key, val in sorted(LOG_LEVELS.items())], default=logging.ERROR, blank=True, db_index=True, ) message = models.TextField() culprit = models.CharField( max_length=MAX_CULPRIT_LENGTH, blank=True, null=True, db_column="view" ) num_comments = BoundedPositiveIntegerField(default=0, null=True) platform = models.CharField(max_length=64, null=True) status = BoundedPositiveIntegerField( default=GroupStatus.UNRESOLVED, choices=( (GroupStatus.UNRESOLVED, _("Unresolved")), (GroupStatus.RESOLVED, _("Resolved")), (GroupStatus.IGNORED, _("Ignored")), ), db_index=True, ) substatus = BoundedIntegerField( null=True, choices=( (GroupSubStatus.UNTIL_ESCALATING, _("Until escalating")), (GroupSubStatus.ONGOING, _("Ongoing")), (GroupSubStatus.ESCALATING, _("Escalating")), (GroupSubStatus.UNTIL_CONDITION_MET, _("Until condition met")), (GroupSubStatus.FOREVER, _("Forever")), ), ) times_seen = BoundedPositiveIntegerField(default=1, db_index=True) last_seen = models.DateTimeField(default=timezone.now, db_index=True) first_seen = models.DateTimeField(default=timezone.now, db_index=True) first_release = FlexibleForeignKey("sentry.Release", null=True, on_delete=models.PROTECT) resolved_at = models.DateTimeField(null=True, db_index=True) # active_at should be the same as first_seen by default active_at = models.DateTimeField(null=True, db_index=True) time_spent_total = BoundedIntegerField(default=0) time_spent_count = BoundedIntegerField(default=0) # deprecated, do not use. GroupShare has superseded is_public = models.BooleanField(default=False, null=True) data = LegacyTextJSONField(null=True) short_id = BoundedBigIntegerField(null=True) type = BoundedPositiveIntegerField( default=DEFAULT_TYPE_ID, db_default=DEFAULT_TYPE_ID, db_index=True ) priority = models.PositiveIntegerField(null=True) priority_locked_at = models.DateTimeField(null=True) seer_fixability_score = models.FloatField(null=True) seer_autofix_last_triggered = models.DateTimeField(null=True) objects: ClassVar[GroupManager] = GroupManager(cache_fields=("id",)) class Meta: app_label = "sentry" db_table = "sentry_groupedmessage" verbose_name_plural = _("grouped messages") verbose_name = _("grouped message") permissions = (("can_view", "Can view"),) indexes = [ models.Index(fields=("project", "first_release")), models.Index(fields=("project", "id")), models.Index(fields=("project", "status", "last_seen", "id")), models.Index(fields=("project", "status", "type", "last_seen", "id")), models.Index(fields=("project", "status", "substatus", "last_seen", "id")), models.Index(fields=("project", "status", "substatus", "type", "last_seen", "id")), models.Index(fields=("project", "status", "substatus", "id")), models.Index(fields=("status", "substatus", "id")), # TODO: Remove this models.Index(fields=("status", "substatus", "first_seen")), models.Index(fields=("project", "status", "priority", "last_seen", "id")), ] unique_together = (("project", "short_id"),) __repr__ = sane_repr("project_id") def __str__(self) -> str: return f"({self.times_seen}) {self.title}" def save(self, *args, **kwargs): if not self.last_seen: self.last_seen = timezone.now() if not self.first_seen: self.first_seen = self.last_seen if not self.active_at: self.active_at = self.first_seen # We limit what we store for the message body self.message = strip(self.message) if self.message: self.message = truncatechars(self.message.splitlines()[0], 255) if self.times_seen is None: self.times_seen = 1 super().save(*args, **kwargs) def get_absolute_url( self, params: Mapping[str, str] | None = None, event_id: str | None = None, ) -> str: # Built manually in preference to django.urls.reverse, # because reverse has a measured performance impact. organization = self.organization if self.issue_category == GroupCategory.FEEDBACK: path = f"/organizations/{organization.slug}/feedback/" params = { **(params or {}), "feedbackSlug": f"{self.project.slug}:{self.id}", "project": str(self.project.id), } query = urlencode(params) return organization.absolute_url(path, query=query) else: path = f"/organizations/{organization.slug}/issues/{self.id}/" if event_id: path += f"events/{event_id}/" query = None if params: query = urlencode(params) return organization.absolute_url(path, query=query) def get_absolute_api_url(self): path = f"/issues/{self.id}/" return self.organization.absolute_api_url(path=path) @property def qualified_short_id(self): if self.short_id is not None: return f"{self.project.slug.upper()}-{base32_encode(self.short_id)}" def is_over_resolve_age(self): resolve_age = self.project.get_option("sentry:resolve_age", None) if not resolve_age: return False return self.last_seen < timezone.now() - timedelta(hours=int(resolve_age)) def is_ignored(self): return self.get_status() == GroupStatus.IGNORED def is_unresolved(self): return self.get_status() == GroupStatus.UNRESOLVED def is_resolved(self): return self.get_status() == GroupStatus.RESOLVED def has_replays(self): def make_snuba_params_for_replay_count_query(): return SnubaParams( organization=self.project.organization, projects=[self.project], user=None, start=datetime.now() - timedelta(days=14), end=datetime.now(), environments=[], teams=[], ) def _cache_key(issue_id) -> str: return f"group:has_replays:{issue_id}" from sentry.replays.usecases.replay_counts import get_replay_counts from sentry.search.events.types import SnubaParams metrics.incr("group.has_replays") # XXX(jferg) Note that this check will preclude backend projects from receiving the "View Replays" # link in their notification. This will need to be addressed in a future change. if not self.project.flags.has_replays: metrics.incr("group.has_replays.project_has_replays_false") return False cached_has_replays = cache.get(_cache_key(self.id)) if cached_has_replays is not None: metrics.incr( "group.has_replays.cached", tags={ "has_replays": cached_has_replays, }, ) return cached_has_replays data_source = ( Dataset.Discover if self.issue_category == GroupCategory.ERROR else Dataset.IssuePlatform ) counts = get_replay_counts( make_snuba_params_for_replay_count_query(), f"issue.id:[{self.id}]", return_ids=False, data_source=data_source, ) has_replays = counts.get(self.id, 0) > 0 # need to refactor counts so that the type of the key returned in the dict is always a str # for typing metrics.incr( "group.has_replays.replay_count_query", tags={ "has_replays": has_replays, }, ) cache.set(_cache_key(self.id), has_replays, 300) return has_replays def get_status(self): # XXX(dcramer): GroupSerializer reimplements this logic from sentry.models.groupsnooze import GroupSnooze status = self.status if status == GroupStatus.IGNORED: try: snooze = GroupSnooze.objects.get_from_cache(group=self) except GroupSnooze.DoesNotExist: pass else: if not snooze.is_valid(group=self): status = GroupStatus.UNRESOLVED # If the issue is UNRESOLVED but has resolved_at set, it means the user manually # unresolved it after it was resolved. We should respect that and not override # the status back to RESOLVED. if status == GroupStatus.UNRESOLVED and self.is_over_resolve_age() and not self.resolved_at: # Only auto-resolve if this group type has auto-resolve enabled if self.issue_type.enable_auto_resolve: return GroupStatus.RESOLVED return status def get_share_id(self): from sentry.models.groupshare import GroupShare try: return GroupShare.objects.filter(group_id=self.id).values_list("uuid", flat=True)[0] except IndexError: # Otherwise it has not been shared yet. return None def get_latest_event( self, conditions: Sequence[Condition] | None = None, start: datetime | None = None, end: datetime | None = None, ) -> GroupEvent | None: """ Returns the latest/newest event given the conditions and time range. If no event is found, returns None. """ return get_oldest_or_latest_event( group=self, ordering=EventOrdering.LATEST, conditions=conditions, start=start, end=end, ) def get_latest_event_for_environments( self, environments: Sequence[str] = () ) -> GroupEvent | None: """ Legacy special case of `self.get_latest_event` for environments and no date range. Kept for compatability, but it's advised to use `self.get_latest_event` directly. """ conditions = ( [Condition(Column("environment"), Op.IN, environments)] if len(environments) > 0 else [] ) return self.get_latest_event(conditions=conditions) def get_oldest_event( self, conditions: Sequence[Condition] | None = None, start: datetime | None = None, end: datetime | None = None, ) -> GroupEvent | None: """ Returns the oldest event given the conditions and time range. If no event is found, returns None. """ return get_oldest_or_latest_event( group=self, ordering=EventOrdering.OLDEST, conditions=conditions, start=start, end=end, ) def get_oldest_event_for_environments( self, environments: Sequence[str] = () ) -> GroupEvent | None: """ Legacy special case of `self.get_oldest_event` for environments and no date range. Kept for compatability, but it's advised to use `self.get_oldest_event` directly. """ conditions = ( [Condition(Column("environment"), Op.IN, environments)] if len(environments) > 0 else [] ) return self.get_oldest_event(conditions=conditions) def get_recommended_event( self, conditions: Sequence[Condition] | None = None, start: datetime | None = None, end: datetime | None = None, ) -> GroupEvent | None: """ Returns a recommended event given the conditions and time range. If a helpful recommendation is not found, it will fallback to the latest event. If neither are found, returns None. """ maybe_event = get_recommended_event( group=self, conditions=conditions, start=start, end=end, ) return ( maybe_event if maybe_event else self.get_latest_event(conditions=conditions, start=start, end=end) ) def get_recommended_event_for_environments( self, environments: Sequence[Environment] = (), conditions: Sequence[Condition] | None = None, ) -> GroupEvent | None: """ Legacy special case of `self.get_recommended_event` for environments and no date range. Kept for compatability, but it's advised to use `self.get_recommended_event` directly. """ all_conditions: list[Condition] = list(conditions) if conditions else [] if len(environments) > 0: all_conditions.append( Condition(Column("environment"), Op.IN, [e.name for e in environments]) ) return self.get_recommended_event(conditions=all_conditions) def get_suspect_commit(self) -> Commit | None: from sentry.models.groupowner import GroupOwner, GroupOwnerType suspect_commit_owner = ( GroupOwner.objects.filter( group_id=self.id, project_id=self.project_id, type=GroupOwnerType.SUSPECT_COMMIT.value, context__isnull=False, ) .order_by("-date_added") .first() ) if not suspect_commit_owner: return None commit_id = suspect_commit_owner.context.get("commitId") if not commit_id: return None commit = Commit.objects.filter(id=commit_id) return commit.first() def get_first_release(self, environment_names: list[str] | None = None) -> str | None: from sentry.models.release import Release if self.first_release and not environment_names: return self.first_release.version return Release.objects.get_group_release_version( self.project_id, self.id, environment_names ) def get_last_release( self, environment_names: list[str] | None = None, use_cache: bool = True ) -> str | None: from sentry.models.release import Release return Release.objects.get_group_release_version( project_id=self.project_id, group_id=self.id, environment_names=environment_names, first=False, use_cache=use_cache, ) def get_event_type(self): """ Return the type of this issue. See ``sentry.eventtypes``. """ return self.data.get("type", "default") def get_event_metadata(self) -> dict[str, Any]: """ Return the metadata of this issue. See ``sentry.eventtypes``. """ return self.data["metadata"] @property def title(self) -> str: title = self.data.get("title") event_type = self.get_event_type() # TODO: It may be that we don't have to restrict this to just default and error types if title and event_type in ["default", "error"]: return title event_type_instance = eventtypes.get(event_type)() return event_type_instance.get_title(self.get_event_metadata()) def location(self): et = eventtypes.get(self.get_event_type())() return et.get_location(self.get_event_metadata()) @property def message_short(self): warnings.warn("Group.message_short is deprecated, use Group.title", DeprecationWarning) return self.title @property def organization(self): return self.project.organization @property def sdk(self) -> str | None: """returns normalized SDK name""" try: return self.get_event_metadata()["sdk"]["name_normalized"] except KeyError: return None @property def checksum(self): warnings.warn("Group.checksum is no longer used", DeprecationWarning) return "" def get_email_subject(self) -> str: return f"{self.qualified_short_id} - {self.title}" def count_users_seen( self, referrer=Referrer.TAGSTORE_GET_GROUPS_USER_COUNTS.value, environment_ids: list[int] | None = None, ): return tagstore.backend.get_groups_user_counts( [self.project_id], [self.id], environment_ids=environment_ids, start=self.first_seen, tenant_ids={"organization_id": self.project.organization_id}, referrer=referrer, )[self.id] def get_assignee(self) -> Team | RpcUser | None: from sentry.models.groupassignee import GroupAssignee try: group_assignee = GroupAssignee.objects.get(group=self) except GroupAssignee.DoesNotExist: return None assigned_actor: Actor = group_assignee.assigned_actor() return assigned_actor.resolve() @property def times_seen_with_pending(self) -> int: """ Returns `times_seen` with any additional pending updates from `buffers` added on. This value must be set first. """ return self.times_seen + self.times_seen_pending @property def times_seen_pending(self) -> int: assert hasattr(self, "_times_seen_pending") if not hasattr(self, "_times_seen_pending"): logger.error("Attempted to fetch pending `times_seen` value without first setting it") return getattr(self, "_times_seen_pending", 0) @times_seen_pending.setter def times_seen_pending(self, times_seen: int): self._times_seen_pending = times_seen @property def issue_type(self): return get_group_type_by_type_id(self.type) @property def issue_category(self): return GroupCategory(self.issue_type.category) @property def issue_category_v2(self): return GroupCategory(self.issue_type.category_v2) @receiver(pre_save, sender=Group, dispatch_uid="pre_save_group_default_substatus", weak=False) def pre_save_group_default_substatus(instance, sender, *args, **kwargs): # TODO(snigdha): Replace the logging with a ValueError once we are confident that this is working as expected. if instance: if instance.status == GroupStatus.IGNORED: if instance.substatus not in IGNORED_SUBSTATUS_CHOICES: logger.error( "Invalid substatus for IGNORED group.", extra={"substatus": instance.substatus}, ) elif instance.status == GroupStatus.UNRESOLVED: if instance.substatus not in UNRESOLVED_SUBSTATUS_CHOICES: logger.error( "Invalid substatus for UNRESOLVED group", extra={"substatus": instance.substatus}, ) # We only support substatuses for UNRESOLVED and IGNORED groups elif instance.substatus is not None: logger.error( "No substatus allowed for group", extra={"status": instance.status, "substatus": instance.substatus}, )
Group
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 488234, "end": 488626 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field(CheckAnnotation, graphql_name="node") """The item at the end of the edge."""
CheckAnnotationEdge
python
getsentry__sentry
src/sentry/replays/usecases/query/conditions/event_ids.py
{ "start": 4141, "end": 4687 }
class ____(ComputedBase): @staticmethod def visit_eq(value: UUID) -> Condition: return contains(ErrorIdScalar.visit_eq(value)) @staticmethod def visit_neq(value: UUID) -> Condition: return does_not_contain(ErrorIdScalar.visit_eq(value)) @staticmethod def visit_in(value: list[UUID]) -> Condition: return contains(ErrorIdScalar.visit_in(value)) @staticmethod def visit_not_in(value: list[UUID]) -> Condition: return does_not_contain(ErrorIdScalar.visit_in(value))
SumOfErrorIdScalar
python
langchain-ai__langchain
libs/core/langchain_core/outputs/generation.py
{ "start": 201, "end": 1611 }
class ____(Serializable): """A single text generation output. Generation represents the response from an "old-fashioned" LLM (string-in, string-out) that generates regular text (not chat messages). This model is used internally by chat model and will eventually be mapped to a more general `LLMResult` object, and then projected into an `AIMessage` object. LangChain users working with chat models will usually access information via `AIMessage` (returned from runnable interfaces) or `LLMResult` (available via callbacks). Please refer to `AIMessage` and `LLMResult` for more information. """ text: str """Generated text output.""" generation_info: dict[str, Any] | None = None """Raw response from the provider. May include things like the reason for finishing or token log probabilities. """ type: Literal["Generation"] = "Generation" """Type is used exclusively for serialization purposes. Set to "Generation" for this class. """ @classmethod def is_lc_serializable(cls) -> bool: """Return `True` as this class is serializable.""" return True @classmethod def get_lc_namespace(cls) -> list[str]: """Get the namespace of the LangChain object. Returns: `["langchain", "schema", "output"]` """ return ["langchain", "schema", "output"]
Generation
python
FactoryBoy__factory_boy
factory/utils.py
{ "start": 1012, "end": 1821 }
class ____: """An iterator wrapper that can be 'reset()' to its start.""" def __init__(self, iterator, **kwargs): super().__init__(**kwargs) self.iterator = iter(iterator) self.past_elements = collections.deque() self.next_elements = collections.deque() def __iter__(self): while True: if self.next_elements: yield self.next_elements.popleft() else: try: value = next(self.iterator) except StopIteration: break else: self.past_elements.append(value) yield value def reset(self): self.next_elements.clear() self.next_elements.extend(self.past_elements)
ResetableIterator
python
allegroai__clearml
clearml/backend_api/services/v2_13/events.py
{ "start": 106204, "end": 109396 }
class ____(Request): """ Get histogram data of all the vector metrics and variants in the task :param task: Task ID :type task: str :param samples: The amount of histogram points to return (0 to return all the points). Optional, the default value is 6000. :type samples: int :param key: Histogram x axis to use: iter - iteration number iso_time - event time as ISO formatted string timestamp - event timestamp as milliseconds since epoch :type key: ScalarKeyEnum """ _service = "events" _action = "scalar_metrics_iter_histogram" _version = "2.13" _schema = { "definitions": { "scalar_key_enum": { "enum": ["iter", "timestamp", "iso_time"], "type": "string", } }, "properties": { "key": { "$ref": "#/definitions/scalar_key_enum", "description": "\n Histogram x axis to use:\n iter - iteration number\n iso_time - event time as ISO formatted string\n timestamp - event timestamp as milliseconds since epoch\n ", }, "samples": { "description": "The amount of histogram points to return (0 to return all the points). Optional, the default value is 6000.", "type": "integer", }, "task": {"description": "Task ID", "type": "string"}, }, "required": ["task"], "type": "object", } def __init__(self, task: str, samples: Optional[int] = None, key: Any = None, **kwargs: Any) -> None: super(ScalarMetricsIterHistogramRequest, self).__init__(**kwargs) self.task = task self.samples = samples self.key = key @schema_property("task") def task(self) -> str: return self._property_task @task.setter def task(self, value: str) -> None: if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("samples") def samples(self) -> Optional[int]: return self._property_samples @samples.setter def samples(self, value: Optional[int]) -> None: if value is None: self._property_samples = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "samples", six.integer_types) self._property_samples = value @schema_property("key") def key(self) -> Any: return self._property_key @key.setter def key(self, value: Any) -> None: if value is None: self._property_key = None return if isinstance(value, six.string_types): try: value = ScalarKeyEnum(value) except ValueError: pass else: self.assert_isinstance(value, "key", enum.Enum) self._property_key = value
ScalarMetricsIterHistogramRequest
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_glacier.py
{ "start": 1221, "end": 3337 }
class ____: def setup_method(self): self.default_op_kwargs = dict( task_id="test_athena_sensor", vault_name="airflow", job_id="1a2b3c4d", poke_interval=60 * 20, ) self.op = GlacierJobOperationSensor(**self.default_op_kwargs, aws_conn_id=None) def test_base_aws_op_attributes(self): op = GlacierJobOperationSensor(**self.default_op_kwargs) assert op.hook.aws_conn_id == "aws_default" assert op.hook._region_name is None assert op.hook._verify is None assert op.hook._config is None op = GlacierJobOperationSensor( **self.default_op_kwargs, aws_conn_id="aws-test-custom-conn", region_name="eu-west-1", verify=False, botocore_config={"read_timeout": 42}, ) assert op.hook.aws_conn_id == "aws-test-custom-conn" assert op.hook._region_name == "eu-west-1" assert op.hook._verify is False assert op.hook._config is not None assert op.hook._config.read_timeout == 42 def test_poke_succeeded(self, mocked_describe_job): mocked_describe_job.side_effect = [{"Action": "", "StatusCode": JobStatus.SUCCEEDED.value}] assert self.op.poke(None) def test_poke_in_progress(self, mocked_describe_job): mocked_describe_job.side_effect = [{"Action": "", "StatusCode": JobStatus.IN_PROGRESS.value}] assert not self.op.poke(None) def test_poke_fail(self, mocked_describe_job): mocked_describe_job.side_effect = [{"Action": "", "StatusCode": ""}] with pytest.raises(AirflowException, match="Sensor failed"): self.op.poke(None) def test_fail_poke(self, mocked_describe_job): response = {"Action": "some action", "StatusCode": "Failed"} message = f"Sensor failed. Job status: {response['Action']}, code status: {response['StatusCode']}" mocked_describe_job.return_value = response with pytest.raises(AirflowException, match=message): self.op.poke(context={})
TestAmazonGlacierSensor
python
keras-team__keras
keras/src/backend/torch/core.py
{ "start": 22700, "end": 23020 }
class ____: """Decorator for custom gradients. Args: forward_fn: Forward pass function. """ def __init__(self, forward_fn): self.forward_fn = forward_fn def __call__(self, *args, **kwargs): return CustomGradientFunction.apply(self.forward_fn, *args, **kwargs)
custom_gradient
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/metrics_test.py
{ "start": 155988, "end": 165469 }
class ____(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() @test_util.run_deprecated_v1 def testVars(self): metrics.mean_per_class_accuracy( predictions=array_ops.ones([10, 1]), labels=array_ops.ones([10, 1]), num_classes=2) _assert_metric_variables(self, ('mean_accuracy/count:0', 'mean_accuracy/total:0')) @test_util.run_deprecated_v1 def testMetricsCollections(self): my_collection_name = '__metrics__' mean_accuracy, _ = metrics.mean_per_class_accuracy( predictions=array_ops.ones([10, 1]), labels=array_ops.ones([10, 1]), num_classes=2, metrics_collections=[my_collection_name]) self.assertListEqual( ops.get_collection(my_collection_name), [mean_accuracy]) @test_util.run_deprecated_v1 def testUpdatesCollection(self): my_collection_name = '__updates__' _, update_op = metrics.mean_per_class_accuracy( predictions=array_ops.ones([10, 1]), labels=array_ops.ones([10, 1]), num_classes=2, updates_collections=[my_collection_name]) self.assertListEqual(ops.get_collection(my_collection_name), [update_op]) @test_util.run_deprecated_v1 def testPredictionsAndLabelsOfDifferentSizeRaisesValueError(self): predictions = array_ops.ones([10, 3]) labels = array_ops.ones([10, 4]) with self.assertRaises(ValueError): metrics.mean_per_class_accuracy(labels, predictions, num_classes=2) @test_util.run_deprecated_v1 def testLabelsAndWeightsOfDifferentSizeRaisesValueError(self): predictions = array_ops.ones([10]) labels = array_ops.ones([10]) weights = array_ops.zeros([9]) with self.assertRaises(ValueError): metrics.mean_per_class_accuracy( labels, predictions, num_classes=2, weights=weights) @test_util.run_deprecated_v1 def testValueTensorIsIdempotent(self): num_classes = 3 predictions = random_ops.random_uniform( [10], maxval=num_classes, dtype=dtypes_lib.int64, seed=1) labels = random_ops.random_uniform( [10], maxval=num_classes, dtype=dtypes_lib.int64, seed=1) mean_accuracy, update_op = metrics.mean_per_class_accuracy( labels, predictions, num_classes=num_classes) with self.cached_session(): self.evaluate(variables.local_variables_initializer()) # Run several updates. for _ in range(10): self.evaluate(update_op) # Then verify idempotency. initial_mean_accuracy = self.evaluate(mean_accuracy) for _ in range(10): self.assertEqual(initial_mean_accuracy, self.evaluate(mean_accuracy)) num_classes = 3 with self.cached_session() as sess: # Create the queue that populates the predictions. preds_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [2]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) predictions = preds_queue.dequeue() # Create the queue that populates the labels. labels_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [2]) _enqueue_vector(sess, labels_queue, [1]) labels = labels_queue.dequeue() mean_accuracy, update_op = metrics.mean_per_class_accuracy( labels, predictions, num_classes) self.evaluate(variables.local_variables_initializer()) for _ in range(5): self.evaluate(update_op) desired_output = np.mean([1.0, 1.0 / 3.0, 0.0]) self.assertAlmostEqual(desired_output, self.evaluate(mean_accuracy)) @test_util.run_deprecated_v1 def testMultipleUpdatesWithWeights(self): num_classes = 2 with self.cached_session() as sess: # Create the queue that populates the predictions. preds_queue = data_flow_ops.FIFOQueue( 6, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) predictions = preds_queue.dequeue() # Create the queue that populates the labels. labels_queue = data_flow_ops.FIFOQueue( 6, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) labels = labels_queue.dequeue() # Create the queue that populates the weights. weights_queue = data_flow_ops.FIFOQueue( 6, dtypes=dtypes_lib.float32, shapes=(1, 1)) _enqueue_vector(sess, weights_queue, [1.0]) _enqueue_vector(sess, weights_queue, [0.5]) _enqueue_vector(sess, weights_queue, [1.0]) _enqueue_vector(sess, weights_queue, [0.0]) _enqueue_vector(sess, weights_queue, [1.0]) _enqueue_vector(sess, weights_queue, [0.0]) weights = weights_queue.dequeue() mean_accuracy, update_op = metrics.mean_per_class_accuracy( labels, predictions, num_classes, weights=weights) variables.local_variables_initializer().run() for _ in range(6): self.evaluate(update_op) desired_output = np.mean([2.0 / 2.0, 0.5 / 1.5]) self.assertAlmostEqual(desired_output, self.evaluate(mean_accuracy)) @test_util.run_deprecated_v1 def testMultipleUpdatesWithMissingClass(self): # Test the case where there are no predictions and labels for # one class, and thus there is one row and one column with # zero entries in the confusion matrix. num_classes = 3 with self.cached_session() as sess: # Create the queue that populates the predictions. # There is no prediction for class 2. preds_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, preds_queue, [0]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [1]) _enqueue_vector(sess, preds_queue, [0]) predictions = preds_queue.dequeue() # Create the queue that populates the labels. # There is label for class 2. labels_queue = data_flow_ops.FIFOQueue( 5, dtypes=dtypes_lib.int32, shapes=(1, 1)) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [1]) _enqueue_vector(sess, labels_queue, [0]) _enqueue_vector(sess, labels_queue, [1]) labels = labels_queue.dequeue() mean_accuracy, update_op = metrics.mean_per_class_accuracy( labels, predictions, num_classes) self.evaluate(variables.local_variables_initializer()) for _ in range(5): self.evaluate(update_op) desired_output = np.mean([1.0 / 2.0, 2.0 / 3.0, 0.]) self.assertAlmostEqual(desired_output, self.evaluate(mean_accuracy)) @test_util.run_deprecated_v1 def testAllCorrect(self): predictions = array_ops.zeros([40]) labels = array_ops.zeros([40]) num_classes = 1 with self.cached_session(): mean_accuracy, update_op = metrics.mean_per_class_accuracy( labels, predictions, num_classes) self.evaluate(variables.local_variables_initializer()) self.assertEqual(1.0, self.evaluate(update_op)[0]) self.assertEqual(1.0, self.evaluate(mean_accuracy)) @test_util.run_deprecated_v1 def testAllWrong(self): predictions = array_ops.zeros([40]) labels = array_ops.ones([40]) num_classes = 2 with self.cached_session(): mean_accuracy, update_op = metrics.mean_per_class_accuracy( labels, predictions, num_classes) self.evaluate(variables.local_variables_initializer()) self.assertAllEqual([0.0, 0.0], update_op) self.assertEqual(0., self.evaluate(mean_accuracy)) @test_util.run_deprecated_v1 def testResultsWithSomeMissing(self): predictions = array_ops.concat([ constant_op.constant(0, shape=[5]), constant_op.constant(1, shape=[5]) ], 0) labels = array_ops.concat([ constant_op.constant(0, shape=[3]), constant_op.constant(1, shape=[7]) ], 0) num_classes = 2 weights = array_ops.concat([ constant_op.constant(0, shape=[1]), constant_op.constant(1, shape=[8]), constant_op.constant(0, shape=[1]) ], 0) with self.cached_session(): mean_accuracy, update_op = metrics.mean_per_class_accuracy( labels, predictions, num_classes, weights=weights) self.evaluate(variables.local_variables_initializer()) desired_accuracy = np.array([2. / 2., 4. / 6.], dtype=np.float32) self.assertAllEqual(desired_accuracy, update_op) desired_mean_accuracy = np.mean(desired_accuracy) self.assertAlmostEqual(desired_mean_accuracy, self.evaluate(mean_accuracy))
MeanPerClassAccuracyTest
python
numpy__numpy
numpy/_core/tests/test_dtype.py
{ "start": 70505, "end": 77388 }
class ____: @staticmethod def check(ctype, dtype): dtype = np.dtype(dtype) assert np.dtype(ctype) == dtype assert np.dtype(ctype()) == dtype assert ctypes.sizeof(ctype) == dtype.itemsize def test_array(self): c8 = ctypes.c_uint8 self.check( 3 * c8, (np.uint8, (3,))) self.check( 1 * c8, (np.uint8, (1,))) self.check( 0 * c8, (np.uint8, (0,))) self.check(1 * (3 * c8), ((np.uint8, (3,)), (1,))) self.check(3 * (1 * c8), ((np.uint8, (1,)), (3,))) def test_padded_structure(self): class PaddedStruct(ctypes.Structure): _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16) ] expected = np.dtype([ ('a', np.uint8), ('b', np.uint16) ], align=True) self.check(PaddedStruct, expected) def test_bit_fields(self): class BitfieldStruct(ctypes.Structure): _fields_ = [ ('a', ctypes.c_uint8, 7), ('b', ctypes.c_uint8, 1) ] assert_raises(TypeError, np.dtype, BitfieldStruct) assert_raises(TypeError, np.dtype, BitfieldStruct()) def test_pointer(self): p_uint8 = ctypes.POINTER(ctypes.c_uint8) assert_raises(TypeError, np.dtype, p_uint8) def test_size_t(self): assert np.dtype(np.uintp) is np.dtype("N") self.check(ctypes.c_size_t, np.uintp) def test_void_pointer(self): self.check(ctypes.c_void_p, "P") def test_union(self): class Union(ctypes.Union): _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16), ] expected = np.dtype({ "names": ['a', 'b'], "formats": [np.uint8, np.uint16], "offsets": [0, 0], "itemsize": 2 }) self.check(Union, expected) def test_union_with_struct_packed(self): class Struct(ctypes.Structure): _pack_ = 1 _fields_ = [ ('one', ctypes.c_uint8), ('two', ctypes.c_uint32) ] class Union(ctypes.Union): _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16), ('c', ctypes.c_uint32), ('d', Struct), ] expected = np.dtype({ "names": ['a', 'b', 'c', 'd'], "formats": ['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]], "offsets": [0, 0, 0, 0], "itemsize": ctypes.sizeof(Union) }) self.check(Union, expected) def test_union_packed(self): class Struct(ctypes.Structure): _fields_ = [ ('one', ctypes.c_uint8), ('two', ctypes.c_uint32) ] _pack_ = 1 class Union(ctypes.Union): _pack_ = 1 _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16), ('c', ctypes.c_uint32), ('d', Struct), ] expected = np.dtype({ "names": ['a', 'b', 'c', 'd'], "formats": ['u1', np.uint16, np.uint32, [('one', 'u1'), ('two', np.uint32)]], "offsets": [0, 0, 0, 0], "itemsize": ctypes.sizeof(Union) }) self.check(Union, expected) def test_packed_structure(self): class PackedStructure(ctypes.Structure): _pack_ = 1 _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16) ] expected = np.dtype([ ('a', np.uint8), ('b', np.uint16) ]) self.check(PackedStructure, expected) def test_large_packed_structure(self): class PackedStructure(ctypes.Structure): _pack_ = 2 _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16), ('c', ctypes.c_uint8), ('d', ctypes.c_uint16), ('e', ctypes.c_uint32), ('f', ctypes.c_uint32), ('g', ctypes.c_uint8) ] expected = np.dtype({ "formats": [np.uint8, np.uint16, np.uint8, np.uint16, np.uint32, np.uint32, np.uint8], "offsets": [0, 2, 4, 6, 8, 12, 16], "names": ['a', 'b', 'c', 'd', 'e', 'f', 'g'], "itemsize": 18}) self.check(PackedStructure, expected) def test_big_endian_structure_packed(self): class BigEndStruct(ctypes.BigEndianStructure): _fields_ = [ ('one', ctypes.c_uint8), ('two', ctypes.c_uint32) ] _pack_ = 1 expected = np.dtype([('one', 'u1'), ('two', '>u4')]) self.check(BigEndStruct, expected) def test_little_endian_structure_packed(self): class LittleEndStruct(ctypes.LittleEndianStructure): _fields_ = [ ('one', ctypes.c_uint8), ('two', ctypes.c_uint32) ] _pack_ = 1 expected = np.dtype([('one', 'u1'), ('two', '<u4')]) self.check(LittleEndStruct, expected) def test_little_endian_structure(self): class PaddedStruct(ctypes.LittleEndianStructure): _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16) ] expected = np.dtype([ ('a', '<B'), ('b', '<H') ], align=True) self.check(PaddedStruct, expected) def test_big_endian_structure(self): class PaddedStruct(ctypes.BigEndianStructure): _fields_ = [ ('a', ctypes.c_uint8), ('b', ctypes.c_uint16) ] expected = np.dtype([ ('a', '>B'), ('b', '>H') ], align=True) self.check(PaddedStruct, expected) def test_simple_endian_types(self): self.check(ctypes.c_uint16.__ctype_le__, np.dtype('<u2')) self.check(ctypes.c_uint16.__ctype_be__, np.dtype('>u2')) self.check(ctypes.c_uint8.__ctype_le__, np.dtype('u1')) self.check(ctypes.c_uint8.__ctype_be__, np.dtype('u1')) all_types = set(np.typecodes['All']) all_pairs = permutations(all_types, 2) @pytest.mark.parametrize("pair", all_pairs) def test_pairs(self, pair): """ Check that np.dtype('x,y') matches [np.dtype('x'), np.dtype('y')] Example: np.dtype('d,I') -> dtype([('f0', '<f8'), ('f1', '<u4')]) """ # gh-5645: check that np.dtype('i,L') can be used pair_type = np.dtype('{},{}'.format(*pair)) expected = np.dtype([('f0', pair[0]), ('f1', pair[1])]) assert_equal(pair_type, expected)
TestFromCTypes
python
scipy__scipy
scipy/sparse/tests/test_base.py
{ "start": 6849, "end": 7682 }
class ____: # Custom type to test binary operations on sparse matrices # with object which has shape attribute. def __init__(self,shape): self._shape = shape def shape(self): return self._shape def ndim(self): return len(self._shape) def __add__(self, mat): return "matrix on the right" def __mul__(self, mat): return "matrix on the right" def __sub__(self, mat): return "matrix on the right" def __radd__(self, mat): return "matrix on the left" def __rmul__(self, mat): return "matrix on the left" def __rsub__(self, mat): return "matrix on the left" def __matmul__(self, mat): return "matrix on the right" def __rmatmul__(self, mat): return "matrix on the left"
BinopTester_with_shape
python
sympy__sympy
sympy/integrals/risch.py
{ "start": 5397, "end": 32071 }
class ____: """ A container for all the information relating to a differential extension. Explanation =========== The attributes of this object are (see also the docstring of __init__): - f: The original (Expr) integrand. - x: The variable of integration. - T: List of variables in the extension. - D: List of derivations in the extension; corresponds to the elements of T. - fa: Poly of the numerator of the integrand. - fd: Poly of the denominator of the integrand. - Tfuncs: Lambda() representations of each element of T (except for x). For back-substitution after integration. - backsubs: A (possibly empty) list of further substitutions to be made on the final integral to make it look more like the integrand. - exts: - extargs: - cases: List of string representations of the cases of T. - t: The top level extension variable, as defined by the current level (see level below). - d: The top level extension derivation, as defined by the current derivation (see level below). - case: The string representation of the case of self.d. (Note that self.T and self.D will always contain the complete extension, regardless of the level. Therefore, you should ALWAYS use DE.t and DE.d instead of DE.T[-1] and DE.D[-1]. If you want to have a list of the derivations or variables only up to the current level, use DE.D[:len(DE.D) + DE.level + 1] and DE.T[:len(DE.T) + DE.level + 1]. Note that, in particular, the derivation() function does this.) The following are also attributes, but will probably not be useful other than in internal use: - newf: Expr form of fa/fd. - level: The number (between -1 and -len(self.T)) such that self.T[self.level] == self.t and self.D[self.level] == self.d. Use the methods self.increment_level() and self.decrement_level() to change the current level. """ # __slots__ is defined mainly so we can iterate over all the attributes # of the class easily (the memory use doesn't matter too much, since we # only create one DifferentialExtension per integration). Also, it's nice # to have a safeguard when debugging. __slots__ = ('f', 'x', 'T', 'D', 'fa', 'fd', 'Tfuncs', 'backsubs', 'exts', 'extargs', 'cases', 'case', 't', 'd', 'newf', 'level', 'ts', 'dummy') def __init__(self, f=None, x=None, handle_first='log', dummy=False, extension=None, rewrite_complex=None): """ Tries to build a transcendental extension tower from ``f`` with respect to ``x``. Explanation =========== If it is successful, creates a DifferentialExtension object with, among others, the attributes fa, fd, D, T, Tfuncs, and backsubs such that fa and fd are Polys in T[-1] with rational coefficients in T[:-1], fa/fd == f, and D[i] is a Poly in T[i] with rational coefficients in T[:i] representing the derivative of T[i] for each i from 1 to len(T). Tfuncs is a list of Lambda objects for back replacing the functions after integrating. Lambda() is only used (instead of lambda) to make them easier to test and debug. Note that Tfuncs corresponds to the elements of T, except for T[0] == x, but they should be back-substituted in reverse order. backsubs is a (possibly empty) back-substitution list that should be applied on the completed integral to make it look more like the original integrand. If it is unsuccessful, it raises NotImplementedError. You can also create an object by manually setting the attributes as a dictionary to the extension keyword argument. You must include at least D. Warning, any attribute that is not given will be set to None. The attributes T, t, d, cases, case, x, and level are set automatically and do not need to be given. The functions in the Risch Algorithm will NOT check to see if an attribute is None before using it. This also does not check to see if the extension is valid (non-algebraic) or even if it is self-consistent. Therefore, this should only be used for testing/debugging purposes. """ # XXX: If you need to debug this function, set the break point here if extension: if 'D' not in extension: raise ValueError("At least the key D must be included with " "the extension flag to DifferentialExtension.") for attr in extension: setattr(self, attr, extension[attr]) self._auto_attrs() return elif f is None or x is None: raise ValueError("Either both f and x or a manual extension must " "be given.") if handle_first not in ('log', 'exp'): raise ValueError("handle_first must be 'log' or 'exp', not %s." % str(handle_first)) # f will be the original function, self.f might change if we reset # (e.g., we pull out a constant from an exponential) self.f = f self.x = x # setting the default value 'dummy' self.dummy = dummy self.reset() exp_new_extension, log_new_extension = True, True # case of 'automatic' choosing if rewrite_complex is None: rewrite_complex = I in self.f.atoms() if rewrite_complex: rewritables = { (sin, cos, cot, tan, sinh, cosh, coth, tanh): exp, (asin, acos, acot, atan): log, } # rewrite the trigonometric components for candidates, rule in rewritables.items(): self.newf = self.newf.rewrite(candidates, rule) self.newf = cancel(self.newf) else: if any(i.has(x) for i in self.f.atoms(sin, cos, tan, atan, asin, acos)): raise NotImplementedError("Trigonometric extensions are not " "supported (yet!)") exps = set() pows = set() numpows = set() sympows = set() logs = set() symlogs = set() while True: if self.newf.is_rational_function(*self.T): break if not exp_new_extension and not log_new_extension: # We couldn't find a new extension on the last pass, so I guess # we can't do it. raise NotImplementedError("Couldn't find an elementary " "transcendental extension for %s. Try using a " % str(f) + "manual extension with the extension flag.") exps, pows, numpows, sympows, log_new_extension = \ self._rewrite_exps_pows(exps, pows, numpows, sympows, log_new_extension) logs, symlogs = self._rewrite_logs(logs, symlogs) if handle_first == 'exp' or not log_new_extension: exp_new_extension = self._exp_part(exps) if exp_new_extension is None: # reset and restart self.f = self.newf self.reset() exp_new_extension = True continue if handle_first == 'log' or not exp_new_extension: log_new_extension = self._log_part(logs) self.fa, self.fd = frac_in(self.newf, self.t) self._auto_attrs() return def __getattr__(self, attr): # Avoid AttributeErrors when debugging if attr not in self.__slots__: raise AttributeError("%s has no attribute %s" % (repr(self), repr(attr))) return None def _rewrite_exps_pows(self, exps, pows, numpows, sympows, log_new_extension): """ Rewrite exps/pows for better processing. """ from .prde import is_deriv_k # Pre-preparsing. ################# # Get all exp arguments, so we can avoid ahead of time doing # something like t1 = exp(x), t2 = exp(x/2) == sqrt(t1). # Things like sqrt(exp(x)) do not automatically simplify to # exp(x/2), so they will be viewed as algebraic. The easiest way # to handle this is to convert all instances of exp(a)**Rational # to exp(Rational*a) before doing anything else. Note that the # _exp_part code can generate terms of this form, so we do need to # do this at each pass (or else modify it to not do that). ratpows = [i for i in self.newf.atoms(Pow) if (isinstance(i.base, exp) and i.exp.is_Rational)] ratpows_repl = [ (i, i.base.base**(i.exp*i.base.exp)) for i in ratpows] self.backsubs += [(j, i) for i, j in ratpows_repl] self.newf = self.newf.xreplace(dict(ratpows_repl)) # To make the process deterministic, the args are sorted # so that functions with smaller op-counts are processed first. # Ties are broken with the default_sort_key. # XXX Although the method is deterministic no additional work # has been done to guarantee that the simplest solution is # returned and that it would be affected be using different # variables. Though it is possible that this is the case # one should know that it has not been done intentionally, so # further improvements may be possible. # TODO: This probably doesn't need to be completely recomputed at # each pass. exps = update_sets(exps, self.newf.atoms(exp), lambda i: i.exp.is_rational_function(*self.T) and i.exp.has(*self.T)) pows = update_sets(pows, self.newf.atoms(Pow), lambda i: i.exp.is_rational_function(*self.T) and i.exp.has(*self.T)) numpows = update_sets(numpows, set(pows), lambda i: not i.base.has(*self.T)) sympows = update_sets(sympows, set(pows) - set(numpows), lambda i: i.base.is_rational_function(*self.T) and not i.exp.is_Integer) # The easiest way to deal with non-base E powers is to convert them # into base E, integrate, and then convert back. for i in ordered(pows): old = i new = exp(i.exp*log(i.base)) # If exp is ever changed to automatically reduce exp(x*log(2)) # to 2**x, then this will break. The solution is to not change # exp to do that :) if i in sympows: if i.exp.is_Rational: raise NotImplementedError("Algebraic extensions are " "not supported (%s)." % str(i)) # We can add a**b only if log(a) in the extension, because # a**b == exp(b*log(a)). basea, based = frac_in(i.base, self.t) A = is_deriv_k(basea, based, self) if A is None: # Nonelementary monomial (so far) # TODO: Would there ever be any benefit from just # adding log(base) as a new monomial? # ANSWER: Yes, otherwise we can't integrate x**x (or # rather prove that it has no elementary integral) # without first manually rewriting it as exp(x*log(x)) self.newf = self.newf.xreplace({old: new}) self.backsubs += [(new, old)] log_new_extension = self._log_part([log(i.base)]) exps = update_sets(exps, self.newf.atoms(exp), lambda i: i.exp.is_rational_function(*self.T) and i.exp.has(*self.T)) continue ans, u, const = A newterm = exp(i.exp*(log(const) + u)) # Under the current implementation, exp kills terms # only if they are of the form a*log(x), where a is a # Number. This case should have already been killed by the # above tests. Again, if this changes to kill more than # that, this will break, which maybe is a sign that you # shouldn't be changing that. Actually, if anything, this # auto-simplification should be removed. See # https://groups.google.com/group/sympy/browse_thread/thread/a61d48235f16867f self.newf = self.newf.xreplace({i: newterm}) elif i not in numpows: continue else: # i in numpows newterm = new # TODO: Just put it in self.Tfuncs self.backsubs.append((new, old)) self.newf = self.newf.xreplace({old: newterm}) exps.append(newterm) return exps, pows, numpows, sympows, log_new_extension def _rewrite_logs(self, logs, symlogs): """ Rewrite logs for better processing. """ atoms = self.newf.atoms(log) logs = update_sets(logs, atoms, lambda i: i.args[0].is_rational_function(*self.T) and i.args[0].has(*self.T)) symlogs = update_sets(symlogs, atoms, lambda i: i.has(*self.T) and i.args[0].is_Pow and i.args[0].base.is_rational_function(*self.T) and not i.args[0].exp.is_Integer) # We can handle things like log(x**y) by converting it to y*log(x) # This will fix not only symbolic exponents of the argument, but any # non-Integer exponent, like log(sqrt(x)). The exponent can also # depend on x, like log(x**x). for i in ordered(symlogs): # Unlike in the exponential case above, we do not ever # potentially add new monomials (above we had to add log(a)). # Therefore, there is no need to run any is_deriv functions # here. Just convert log(a**b) to b*log(a) and let # log_new_extension() handle it from there. lbase = log(i.args[0].base) logs.append(lbase) new = i.args[0].exp*lbase self.newf = self.newf.xreplace({i: new}) self.backsubs.append((new, i)) # remove any duplicates logs = sorted(set(logs), key=default_sort_key) return logs, symlogs def _auto_attrs(self): """ Set attributes that are generated automatically. """ if not self.T: # i.e., when using the extension flag and T isn't given self.T = [i.gen for i in self.D] if not self.x: self.x = self.T[0] self.cases = [get_case(d, t) for d, t in zip(self.D, self.T)] self.level = -1 self.t = self.T[self.level] self.d = self.D[self.level] self.case = self.cases[self.level] def _exp_part(self, exps): """ Try to build an exponential extension. Returns ======= Returns True if there was a new extension, False if there was no new extension but it was able to rewrite the given exponentials in terms of the existing extension, and None if the entire extension building process should be restarted. If the process fails because there is no way around an algebraic extension (e.g., exp(log(x)/2)), it will raise NotImplementedError. """ from .prde import is_log_deriv_k_t_radical new_extension = False restart = False expargs = [i.exp for i in exps] ip = integer_powers(expargs) for arg, others in ip: # Minimize potential problems with algebraic substitution others.sort(key=lambda i: i[1]) arga, argd = frac_in(arg, self.t) A = is_log_deriv_k_t_radical(arga, argd, self) if A is not None: ans, u, n, const = A # if n is 1 or -1, it's algebraic, but we can handle it if n == -1: # This probably will never happen, because # Rational.as_numer_denom() returns the negative term in # the numerator. But in case that changes, reduce it to # n == 1. n = 1 u **= -1 const *= -1 ans = [(i, -j) for i, j in ans] if n == 1: # Example: exp(x + x**2) over QQ(x, exp(x), exp(x**2)) self.newf = self.newf.xreplace({exp(arg): exp(const)*Mul(*[ u**power for u, power in ans])}) self.newf = self.newf.xreplace({exp(p*exparg): exp(const*p) * Mul(*[u**power for u, power in ans]) for exparg, p in others}) # TODO: Add something to backsubs to put exp(const*p) # back together. continue else: # Bad news: we have an algebraic radical. But maybe we # could still avoid it by choosing a different extension. # For example, integer_powers() won't handle exp(x/2 + 1) # over QQ(x, exp(x)), but if we pull out the exp(1), it # will. Or maybe we have exp(x + x**2/2), over # QQ(x, exp(x), exp(x**2)), which is exp(x)*sqrt(exp(x**2)), # but if we use QQ(x, exp(x), exp(x**2/2)), then they will # all work. # # So here is what we do: If there is a non-zero const, pull # it out and retry. Also, if len(ans) > 1, then rewrite # exp(arg) as the product of exponentials from ans, and # retry that. If const == 0 and len(ans) == 1, then we # assume that it would have been handled by either # integer_powers() or n == 1 above if it could be handled, # so we give up at that point. For example, you can never # handle exp(log(x)/2) because it equals sqrt(x). if const or len(ans) > 1: rad = Mul(*[term**(power/n) for term, power in ans]) self.newf = self.newf.xreplace({exp(p*exparg): exp(const*p)*rad for exparg, p in others}) self.newf = self.newf.xreplace(dict(list(zip(reversed(self.T), reversed([f(self.x) for f in self.Tfuncs]))))) restart = True break else: # TODO: give algebraic dependence in error string raise NotImplementedError("Cannot integrate over " "algebraic extensions.") else: arga, argd = frac_in(arg, self.t) darga = (argd*derivation(Poly(arga, self.t), self) - arga*derivation(Poly(argd, self.t), self)) dargd = argd**2 darga, dargd = darga.cancel(dargd, include=True) darg = darga.as_expr()/dargd.as_expr() self.t = next(self.ts) self.T.append(self.t) self.extargs.append(arg) self.exts.append('exp') self.D.append(darg.as_poly(self.t, expand=False)*Poly(self.t, self.t, expand=False)) if self.dummy: i = Dummy("i") else: i = Symbol('i') self.Tfuncs += [Lambda(i, exp(arg.subs(self.x, i)))] self.newf = self.newf.xreplace( {exp(exparg): self.t**p for exparg, p in others}) new_extension = True if restart: return None return new_extension def _log_part(self, logs): """ Try to build a logarithmic extension. Returns ======= Returns True if there was a new extension and False if there was no new extension but it was able to rewrite the given logarithms in terms of the existing extension. Unlike with exponential extensions, there is no way that a logarithm is not transcendental over and cannot be rewritten in terms of an already existing extension in a non-algebraic way, so this function does not ever return None or raise NotImplementedError. """ from .prde import is_deriv_k new_extension = False logargs = [i.args[0] for i in logs] for arg in ordered(logargs): # The log case is easier, because whenever a logarithm is algebraic # over the base field, it is of the form a1*t1 + ... an*tn + c, # which is a polynomial, so we can just replace it with that. # In other words, we don't have to worry about radicals. arga, argd = frac_in(arg, self.t) A = is_deriv_k(arga, argd, self) if A is not None: ans, u, const = A newterm = log(const) + u self.newf = self.newf.xreplace({log(arg): newterm}) continue else: arga, argd = frac_in(arg, self.t) darga = (argd*derivation(Poly(arga, self.t), self) - arga*derivation(Poly(argd, self.t), self)) dargd = argd**2 darg = darga.as_expr()/dargd.as_expr() self.t = next(self.ts) self.T.append(self.t) self.extargs.append(arg) self.exts.append('log') self.D.append(cancel(darg.as_expr()/arg).as_poly(self.t, expand=False)) if self.dummy: i = Dummy("i") else: i = Symbol('i') self.Tfuncs += [Lambda(i, log(arg.subs(self.x, i)))] self.newf = self.newf.xreplace({log(arg): self.t}) new_extension = True return new_extension @property def _important_attrs(self): """ Returns some of the more important attributes of self. Explanation =========== Used for testing and debugging purposes. The attributes are (fa, fd, D, T, Tfuncs, backsubs, exts, extargs). """ return (self.fa, self.fd, self.D, self.T, self.Tfuncs, self.backsubs, self.exts, self.extargs) # NOTE: this printing doesn't follow the Python's standard # eval(repr(DE)) == DE, where DE is the DifferentialExtension object, # also this printing is supposed to contain all the important # attributes of a DifferentialExtension object def __repr__(self): # no need to have GeneratorType object printed in it r = [(attr, getattr(self, attr)) for attr in self.__slots__ if not isinstance(getattr(self, attr), GeneratorType)] return self.__class__.__name__ + '(dict(%r))' % (r) # fancy printing of DifferentialExtension object def __str__(self): return (self.__class__.__name__ + '({fa=%s, fd=%s, D=%s})' % (self.fa, self.fd, self.D)) # should only be used for debugging purposes, internally # f1 = f2 = log(x) at different places in code execution # may return D1 != D2 as True, since 'level' or other attribute # may differ def __eq__(self, other): for attr in self.__class__.__slots__: d1, d2 = getattr(self, attr), getattr(other, attr) if not (isinstance(d1, GeneratorType) or d1 == d2): return False return True def reset(self): """ Reset self to an initial state. Used by __init__. """ self.t = self.x self.T = [self.x] self.D = [Poly(1, self.x)] self.level = -1 self.exts = [None] self.extargs = [None] if self.dummy: self.ts = numbered_symbols('t', cls=Dummy) else: # For testing self.ts = numbered_symbols('t') # For various things that we change to make things work that we need to # change back when we are done. self.backsubs = [] self.Tfuncs = [] self.newf = self.f def indices(self, extension): """ Parameters ========== extension : str Represents a valid extension type. Returns ======= list: A list of indices of 'exts' where extension of type 'extension' is present. Examples ======== >>> from sympy.integrals.risch import DifferentialExtension >>> from sympy import log, exp >>> from sympy.abc import x >>> DE = DifferentialExtension(log(x) + exp(x), x, handle_first='exp') >>> DE.indices('log') [2] >>> DE.indices('exp') [1] """ return [i for i, ext in enumerate(self.exts) if ext == extension] def increment_level(self): """ Increment the level of self. Explanation =========== This makes the working differential extension larger. self.level is given relative to the end of the list (-1, -2, etc.), so we do not need do worry about it when building the extension. """ if self.level >= -1: raise ValueError("The level of the differential extension cannot " "be incremented any further.") self.level += 1 self.t = self.T[self.level] self.d = self.D[self.level] self.case = self.cases[self.level] return None def decrement_level(self): """ Decrease the level of self. Explanation =========== This makes the working differential extension smaller. self.level is given relative to the end of the list (-1, -2, etc.), so we do not need do worry about it when building the extension. """ if self.level <= -len(self.T): raise ValueError("The level of the differential extension cannot " "be decremented any further.") self.level -= 1 self.t = self.T[self.level] self.d = self.D[self.level] self.case = self.cases[self.level] return None def update_sets(seq, atoms, func): s = set(seq) s = atoms.intersection(s) new = atoms - s s.update(list(filter(func, new))) return list(s)
DifferentialExtension
python
kamyu104__LeetCode-Solutions
Python/find-peak-element.py
{ "start": 32, "end": 421 }
class ____(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ left, right = 0, len(nums) - 1 while left < right: mid = left + (right - left) / 2 if nums[mid] > nums[mid + 1]: right = mid else: left = mid + 1 return left
Solution
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 23568, "end": 23759 }
class ____(ProjectNotificationsMixin, CreateView): template_name = "projects/project_notifications_form.html" success_message = _("Notification created")
ProjectEmailNotificationsCreate
python
PrefectHQ__prefect
src/prefect/cli/cloud/__init__.py
{ "start": 2257, "end": 2305 }
class ____(BaseModel): reason: str
LoginFailed
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_exceptions.py
{ "start": 71204, "end": 74517 }
class ____(__TestCase): def test_attributes(self): # Setting 'name' and 'path' should not be a problem. exc = ImportError('test') self.assertIsNone(exc.name) self.assertIsNone(exc.path) exc = ImportError('test', name='somemodule') self.assertEqual(exc.name, 'somemodule') self.assertIsNone(exc.path) exc = ImportError('test', path='somepath') self.assertEqual(exc.path, 'somepath') self.assertIsNone(exc.name) exc = ImportError('test', path='somepath', name='somename') self.assertEqual(exc.name, 'somename') self.assertEqual(exc.path, 'somepath') msg = r"ImportError\(\) got an unexpected keyword argument 'invalid'" with self.assertRaisesRegex(TypeError, msg): ImportError('test', invalid='keyword') with self.assertRaisesRegex(TypeError, msg): ImportError('test', name='name', invalid='keyword') with self.assertRaisesRegex(TypeError, msg): ImportError('test', path='path', invalid='keyword') with self.assertRaisesRegex(TypeError, msg): ImportError(invalid='keyword') with self.assertRaisesRegex(TypeError, msg): ImportError('test', invalid='keyword', another=True) def test_reset_attributes(self): exc = ImportError('test', name='name', path='path') self.assertEqual(exc.args, ('test',)) self.assertEqual(exc.msg, 'test') self.assertEqual(exc.name, 'name') self.assertEqual(exc.path, 'path') # Reset not specified attributes exc.__init__() self.assertEqual(exc.args, ()) self.assertEqual(exc.msg, None) self.assertEqual(exc.name, None) self.assertEqual(exc.path, None) def test_non_str_argument(self): # Issue #15778 with check_warnings(('', BytesWarning), quiet=True): arg = b'abc' exc = ImportError(arg) self.assertEqual(str(arg), str(exc)) def test_copy_pickle(self): for kwargs in (dict(), dict(name='somename'), dict(path='somepath'), dict(name='somename', path='somepath')): orig = ImportError('test', **kwargs) for proto in range(pickle.HIGHEST_PROTOCOL + 1): exc = pickle.loads(pickle.dumps(orig, proto)) self.assertEqual(exc.args, ('test',)) self.assertEqual(exc.msg, 'test') self.assertEqual(exc.name, orig.name) self.assertEqual(exc.path, orig.path) for c in copy.copy, copy.deepcopy: exc = c(orig) self.assertEqual(exc.args, ('test',)) self.assertEqual(exc.msg, 'test') self.assertEqual(exc.name, orig.name) self.assertEqual(exc.path, orig.path) def run_script(source): if isinstance(source, str): with open(TESTFN, 'w', encoding='utf-8') as testfile: testfile.write(dedent(source)) else: with open(TESTFN, 'wb') as testfile: testfile.write(source) _rc, _out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN) return err.decode('utf-8').splitlines()
ImportErrorTests
python
kamyu104__LeetCode-Solutions
Python/rank-transform-of-an-array.py
{ "start": 33, "end": 253 }
class ____(object): def arrayRankTransform(self, arr): """ :type arr: List[int] :rtype: List[int] """ return map({x: i+1 for i, x in enumerate(sorted(set(arr)))}.get, arr)
Solution
python
jupyterlab__jupyterlab
jupyterlab/tests/test_app.py
{ "start": 2697, "end": 4016 }
class ____: """Set Jupyter path variables to a temporary directory Useful as a context manager or with explicit start/stop """ def start(self): self.test_dir = td = TemporaryDirectory() self.env_patch = patch.dict( os.environ, { "JUPYTER_CONFIG_DIR": pjoin(td.name, "jupyter"), "JUPYTER_DATA_DIR": pjoin(td.name, "jupyter_data"), "JUPYTER_RUNTIME_DIR": pjoin(td.name, "jupyter_runtime"), "IPYTHONDIR": pjoin(td.name, "ipython"), }, ) self.env_patch.start() self.path_patch = patch.multiple( jupyter_core.paths, SYSTEM_JUPYTER_PATH=[pjoin(td.name, "share", "jupyter")], ENV_JUPYTER_PATH=[pjoin(td.name, "env", "share", "jupyter")], SYSTEM_CONFIG_PATH=[pjoin(td.name, "etc", "jupyter")], ENV_CONFIG_PATH=[pjoin(td.name, "env", "etc", "jupyter")], ) self.path_patch.start() def stop(self): self.env_patch.stop() self.path_patch.stop() try: self.test_dir.cleanup() except OSError: pass def __enter__(self): self.start() return self.test_dir.name def __exit__(self, *exc_info): self.stop()
TestEnv
python
doocs__leetcode
solution/1000-1099/1011.Capacity To Ship Packages Within D Days/Solution.py
{ "start": 0, "end": 428 }
class ____: def shipWithinDays(self, weights: List[int], days: int) -> int: def check(mx): ws, cnt = 0, 1 for w in weights: ws += w if ws > mx: cnt += 1 ws = w return cnt <= days left, right = max(weights), sum(weights) + 1 return left + bisect_left(range(left, right), True, key=check)
Solution
python
coleifer__peewee
tests/expressions.py
{ "start": 173, "end": 223 }
class ____(TestModel): name = CharField()
Person
python
numba__numba
numba/cuda/simulator/kernelapi.py
{ "start": 3628, "end": 6068 }
class ____(object): def add(self, array, index, val): with addlock: old = array[index] array[index] += val return old def sub(self, array, index, val): with sublock: old = array[index] array[index] -= val return old def and_(self, array, index, val): with andlock: old = array[index] array[index] &= val return old def or_(self, array, index, val): with orlock: old = array[index] array[index] |= val return old def xor(self, array, index, val): with xorlock: old = array[index] array[index] ^= val return old def inc(self, array, index, val): with inclock: old = array[index] if old >= val: array[index] = 0 else: array[index] += 1 return old def dec(self, array, index, val): with declock: old = array[index] if (old == 0) or (old > val): array[index] = val else: array[index] -= 1 return old def exch(self, array, index, val): with exchlock: old = array[index] array[index] = val return old def max(self, array, index, val): with maxlock: old = array[index] array[index] = max(old, val) return old def min(self, array, index, val): with minlock: old = array[index] array[index] = min(old, val) return old def nanmax(self, array, index, val): with maxlock: old = array[index] array[index] = np.nanmax([array[index], val]) return old def nanmin(self, array, index, val): with minlock: old = array[index] array[index] = np.nanmin([array[index], val]) return old def compare_and_swap(self, array, old, val): with compare_and_swaplock: index = (0,) * array.ndim loaded = array[index] if loaded == old: array[index] = val return loaded def cas(self, array, index, old, val): with caslock: loaded = array[index] if loaded == old: array[index] = val return loaded
FakeCUDAAtomic
python
pdm-project__pdm
src/pdm/models/caches.py
{ "start": 1827, "end": 2860 }
class ____(JSONFileCache[Candidate, CandidateInfo]): """A cache manager that stores the candidate -> (dependencies, requires_python, summary) mapping. """ @staticmethod def get_url_part(link: Link) -> str: import base64 from pdm.utils import url_without_fragments url = url_without_fragments(link.split_auth()[1]) return base64.urlsafe_b64encode(url.encode()).decode() @classmethod def _get_key(cls, obj: Candidate) -> str: # Name and version are set when dependencies are resolved, # so use them for cache key. Local directories won't be cached. if not obj.name or not obj.version: raise KeyError("The package is missing a name or version") extras = "[{}]".format(",".join(sorted(obj.req.extras))) if obj.req.extras else "" version = obj.version if obj.link is not None and not obj.req.is_named: version = cls.get_url_part(obj.link) return f"{obj.name}{extras}-{version}"
CandidateInfoCache
python
django__django
django/forms/renderers.py
{ "start": 1582, "end": 1891 }
class ____(EngineMixin, BaseRenderer): """ Load Jinja2 templates from the built-in widget templates in django/forms/jinja2 and from apps' 'jinja2' directory. """ @cached_property def backend(self): from django.template.backends.jinja2 import Jinja2 return Jinja2
Jinja2
python
fastai__fastai
fastai/tabular/core.py
{ "start": 11738, "end": 13480 }
class ____(TabularProc): "Transform the categorical variables to something similar to `pd.Categorical`" order = 1 def setups(self, to): store_attr(classes={n:CategoryMap(to.iloc[:,n].items, add_na=(n in to.cat_names)) for n in to.cat_names}, but='to') def encodes(self, to): to.transform(to.cat_names, partial(_apply_cats, self.classes, 1)) def decodes(self, to): to.transform(to.cat_names, partial(_decode_cats, self.classes)) def __getitem__(self,k): return self.classes[k] # %% ../../nbs/40_tabular.core.ipynb 60 @Categorize def setups(self, to:Tabular): if len(to.y_names) > 0: if self.vocab is None: self.vocab = CategoryMap(getattr(to, 'train', to).iloc[:,to.y_names[0]].items, strict=True) else: self.vocab = CategoryMap(self.vocab, sort=False, add_na=self.add_na) self.c = len(self.vocab) return self(to) @Categorize def encodes(self, to:Tabular): to.transform(to.y_names, partial(_apply_cats, {n: self.vocab for n in to.y_names}, 0), all_col=False) return to @Categorize def decodes(self, to:Tabular): to.transform(to.y_names, partial(_decode_cats, {n: self.vocab for n in to.y_names}), all_col=False) return to # %% ../../nbs/40_tabular.core.ipynb 74 @Normalize def setups(self, to:Tabular): store_attr(but='to', means=dict(getattr(to, 'train', to).conts.mean()), stds=dict(getattr(to, 'train', to).conts.std(ddof=0)+1e-7)) return self(to) @Normalize def encodes(self, to:Tabular): to.conts = (to.conts-self.means) / self.stds return to @Normalize def decodes(self, to:Tabular): to.conts = (to.conts*self.stds ) + self.means return to # %% ../../nbs/40_tabular.core.ipynb 79
Categorify
python
facebook__pyre-check
scripts/compare_pysa_models_to_json.py
{ "start": 1147, "end": 1239 }
class ____(TypedDict): sources: Set[str] sinks: Set[str] tito: Set[str]
TaintModel
python
ipython__ipython
IPython/core/magics/namespace.py
{ "start": 1209, "end": 25293 }
class ____(Magics): """Magics to manage various aspects of the user's namespace. These include listing variables, introspecting into them, etc. """ @line_magic def pinfo(self, parameter_s='', namespaces=None): """Provide detailed information about an object. '%pinfo object' is just a synonym for object? or ?object.""" # print('pinfo par: <%s>' % parameter_s) # dbg # detail_level: 0 -> obj? , 1 -> obj?? detail_level = 0 # We need to detect if we got called as 'pinfo pinfo foo', which can # happen if the user types 'pinfo foo?' at the cmd line. pinfo,qmark1,oname,qmark2 = \ re.match(r'(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() if pinfo or qmark1 or qmark2: detail_level = 1 if "*" in oname: self.psearch(oname) else: self.shell._inspect('pinfo', oname, detail_level=detail_level, namespaces=namespaces) @line_magic def pinfo2(self, parameter_s='', namespaces=None): """Provide extra detailed information about an object. '%pinfo2 object' is just a synonym for object?? or ??object.""" self.shell._inspect('pinfo', parameter_s, detail_level=1, namespaces=namespaces) @skip_doctest @line_magic def pdef(self, parameter_s='', namespaces=None): """Print the call signature for any callable object. If the object is a class, print the constructor information. Examples -------- :: In [3]: %pdef urllib.urlopen urllib.urlopen(url, data=None, proxies=None) """ self.shell._inspect('pdef',parameter_s, namespaces) @line_magic def pdoc(self, parameter_s='', namespaces=None): """Print the docstring for an object. If the given object is a class, it will print both the class and the constructor docstrings.""" self.shell._inspect('pdoc',parameter_s, namespaces) @line_magic def psource(self, parameter_s='', namespaces=None): """Print (or run through pager) the source code for an object.""" if not parameter_s: raise UsageError('Missing object name.') self.shell._inspect('psource',parameter_s, namespaces) @line_magic def pfile(self, parameter_s='', namespaces=None): """Print (or run through pager) the file where an object is defined. The file opens at the line where the object definition begins. IPython will honor the environment variable PAGER if set, and otherwise will do its best to print the file in a convenient form. If the given argument is not an object currently defined, IPython will try to interpret it as a filename (automatically adding a .py extension if needed). You can thus use %pfile as a syntax highlighting code viewer.""" # first interpret argument as an object name out = self.shell._inspect('pfile',parameter_s, namespaces) # if not, try the input as a filename if out == 'not found': try: filename = get_py_filename(parameter_s) except IOError as msg: print(msg) return page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False))) @line_magic def psearch(self, parameter_s=''): """Search for object in namespaces by wildcard. %psearch [options] PATTERN [OBJECT TYPE] Note: ? can be used as a synonym for %psearch, at the beginning or at the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the rest of the command line must be unchanged (options come first), so for example the following forms are equivalent %psearch -i a* function -i a* function? ?-i a* function Arguments: PATTERN where PATTERN is a string containing * as a wildcard similar to its use in a shell. The pattern is matched in all namespaces on the search path. By default objects starting with a single _ are not matched, many IPython generated objects have a single underscore. The default is case insensitive matching. Matching is also done on the attributes of objects and not only on the objects in a module. [OBJECT TYPE] Is the name of a python type from the types module. The name is given in lowercase without the ending type, ex. StringType is written string. By adding a type here only objects matching the given type are matched. Using all here makes the pattern match all types (this is the default). Options: -a: makes the pattern match even objects whose names start with a single underscore. These names are normally omitted from the search. -i/-c: make the pattern case insensitive/sensitive. If neither of these options are given, the default is read from your configuration file, with the option ``InteractiveShell.wildcards_case_sensitive``. If this option is not specified in your configuration file, IPython's internal default is to do a case sensitive search. -e/-s NAMESPACE: exclude/search a given namespace. The pattern you specify can be searched in any of the following namespaces: 'builtin', 'user', 'user_global','internal', 'alias', where 'builtin' and 'user' are the search defaults. Note that you should not use quotes when specifying namespaces. -l: List all available object types for object matching. This function can be used without arguments. 'Builtin' contains the python module builtin, 'user' contains all user data, 'alias' only contain the shell aliases and no python objects, 'internal' contains objects used by IPython. The 'user_global' namespace is only used by embedded IPython instances, and it contains module-level globals. You can add namespaces to the search with -s or exclude them with -e (these options can be given more than once). Examples -------- :: %psearch a* -> objects beginning with an a %psearch -e builtin a* -> objects NOT in the builtin space starting in a %psearch a* function -> all functions beginning with an a %psearch re.e* -> objects beginning with an e in module re %psearch r*.e* -> objects that start with e in modules starting in r %psearch r*.* string -> all strings in modules beginning with r Case sensitive search:: %psearch -c a* list all object beginning with lower case a Show objects beginning with a single _:: %psearch -a _* list objects beginning with a single underscore List available objects:: %psearch -l list all available object types """ # default namespaces to be searched def_search = ['user_local', 'user_global', 'builtin'] # Process options/args opts,args = self.parse_options(parameter_s,'cias:e:l',list_all=True) opt = opts.get shell = self.shell psearch = shell.inspector.psearch # select list object types list_types = False if 'l' in opts: list_types = True # select case options if 'i' in opts: ignore_case = True elif 'c' in opts: ignore_case = False else: ignore_case = not shell.wildcards_case_sensitive # Build list of namespaces to search from user options def_search.extend(opt('s',[])) ns_exclude = ns_exclude=opt('e',[]) ns_search = [nm for nm in def_search if nm not in ns_exclude] # Call the actual search try: psearch(args,shell.ns_table,ns_search, show_all=opt('a'),ignore_case=ignore_case, list_types=list_types) except: shell.showtraceback() @skip_doctest @line_magic def who_ls(self, parameter_s=''): """Return a sorted list of all interactive variables. If arguments are given, only variables of types matching these arguments are returned. Examples -------- Define two variables and list them with who_ls:: In [1]: alpha = 123 In [2]: beta = 'test' In [3]: %who_ls Out[3]: ['alpha', 'beta'] In [4]: %who_ls int Out[4]: ['alpha'] In [5]: %who_ls str Out[5]: ['beta'] """ user_ns = self.shell.user_ns user_ns_hidden = self.shell.user_ns_hidden nonmatching = object() # This can never be in user_ns out = [ i for i in user_ns if not i.startswith('_') \ and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ] typelist = parameter_s.split() if typelist: typeset = set(typelist) out = [i for i in out if type(user_ns[i]).__name__ in typeset] out.sort() return out @skip_doctest @line_magic def who(self, parameter_s=''): """Print all interactive variables, with some minimal formatting. If any arguments are given, only variables whose type matches one of these are printed. For example:: %who function str will only list functions and strings, excluding all other types of variables. To find the proper type names, simply use type(var) at a command line to see how python prints type names. For example: :: In [1]: type('hello')\\ Out[1]: <type 'str'> indicates that the type name for strings is 'str'. ``%who`` always excludes executed names loaded through your configuration file and things which are internal to IPython. This is deliberate, as typically you may load many modules and the purpose of %who is to show you only what you've manually defined. Examples -------- Define two variables and list them with who:: In [1]: alpha = 123 In [2]: beta = 'test' In [3]: %who alpha beta In [4]: %who int alpha In [5]: %who str beta """ varlist = self.who_ls(parameter_s) if not varlist: if parameter_s: print('No variables match your requested type.') else: print('Interactive namespace is empty.') return # if we have variables, move on... count = 0 for i in varlist: print(i+'\t', end=' ') count += 1 if count > 8: count = 0 print() print() @skip_doctest @line_magic def whos(self, parameter_s=''): """Like %who, but gives some extra information about each variable. The same type filtering of %who can be applied here. For all variables, the type is printed. Additionally it prints: - For {},[],(): their length. - For numpy arrays, a summary with shape, number of elements, typecode and size in memory. - For DataFrame and Series types: their shape. - Everything else: a string representation, snipping their middle if too long. Examples -------- Define two variables and list them with whos:: In [1]: alpha = 123 In [2]: beta = 'test' In [3]: df = pd.DataFrame({"a": range(10), "b": range(10,20)}) In [4]: s = df["a"] In [5]: %whos Variable Type Data/Info -------------------------------- alpha int 123 beta str test df DataFrame Shape: (10, 2) s Series Shape: (10, ) """ varnames = self.who_ls(parameter_s) if not varnames: if parameter_s: print('No variables match your requested type.') else: print('Interactive namespace is empty.') return # if we have variables, move on... # for these types, show len() instead of data: seq_types = ['dict', 'list', 'tuple'] # for numpy arrays, display summary info ndarray_type = None if 'numpy' in sys.modules: try: from numpy import ndarray except ImportError: pass else: ndarray_type = ndarray.__name__ # Find all variable names and types so we can figure out column sizes # some types are well known and can be shorter abbrevs = {'IPython.core.macro.Macro' : 'Macro'} def type_name(v): tn = type(v).__name__ return abbrevs.get(tn,tn) varlist = [self.shell.user_ns[n] for n in varnames] typelist = [] for vv in varlist: tt = type_name(vv) if tt=='instance': typelist.append( abbrevs.get(str(vv.__class__), str(vv.__class__))) else: typelist.append(tt) # column labels and # of spaces as separator varlabel = 'Variable' typelabel = 'Type' datalabel = 'Data/Info' colsep = 3 # variable format strings vformat = "{0:<{varwidth}}{1:<{typewidth}}" aformat = "%s: %s elems, type `%s`, %s bytes" # find the size of the columns to format the output nicely varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep # table header print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)) # and the table itself kb = 1024 Mb = 1048576 # kb**2 for vname,var,vtype in zip(varnames,varlist,typelist): print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ') if vtype in seq_types: print("n="+str(len(var))) elif vtype == ndarray_type: vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] if vtype==ndarray_type: # numpy vsize = var.size vbytes = vsize*var.itemsize vdtype = var.dtype if vbytes < 100000: print(aformat % (vshape, vsize, vdtype, vbytes)) else: print(aformat % (vshape, vsize, vdtype, vbytes), end=' ') if vbytes < Mb: print("(%s kb)" % (vbytes / kb,)) else: print("(%s Mb)" % (vbytes / Mb,)) elif vtype in ["DataFrame", "Series"]: # Useful for DataFrames and Series # Ought to work for both pandas and polars print(f"Shape: {var.shape}") else: try: vstr = str(var) except UnicodeEncodeError: vstr = var.encode(DEFAULT_ENCODING, 'backslashreplace') except: vstr = "<object with id %d (str() failed)>" % id(var) vstr = vstr.replace('\n', '\\n') if len(vstr) < 50: print(vstr) else: print(vstr[:25] + "<...>" + vstr[-25:]) @line_magic def reset(self, parameter_s=''): """Resets the namespace by removing all names defined by the user, if called without arguments, or by removing some types of objects, such as everything currently in IPython's In[] and Out[] containers (see the parameters for details). Parameters ---------- -f force reset without asking for confirmation. -s 'Soft' reset: Only clears your namespace, leaving history intact. References to objects may be kept. By default (without this option), we do a 'hard' reset, giving you a new session and removing all references to objects from the current session. --aggressive Try to aggressively remove modules from sys.modules ; this may allow you to reimport Python modules that have been updated and pick up changes, but can have unintended consequences. in reset input history out reset output history dhist reset directory history array reset only variables that are NumPy arrays See Also -------- reset_selective : invoked as ``%reset_selective`` Examples -------- :: In [6]: a = 1 In [7]: a Out[7]: 1 In [8]: 'a' in get_ipython().user_ns Out[8]: True In [9]: %reset -f In [1]: 'a' in get_ipython().user_ns Out[1]: False In [2]: %reset -f in Flushing input history In [3]: %reset -f dhist in Flushing directory history Flushing input history Notes ----- Calling this magic from clients that do not implement standard input, such as the ipython notebook interface, will reset the namespace without confirmation. """ opts, args = self.parse_options(parameter_s, "sf", "aggressive", mode="list") if "f" in opts: ans = True else: try: ans = self.shell.ask_yes_no( "Once deleted, variables cannot be recovered. Proceed (y/[n])?", default='n') except StdinNotImplementedError: ans = True if not ans: print('Nothing done.') return if 's' in opts: # Soft reset user_ns = self.shell.user_ns for i in self.who_ls(): del(user_ns[i]) elif len(args) == 0: # Hard reset self.shell.reset(new_session=False, aggressive=("aggressive" in opts)) # reset in/out/dhist/array: previously extensinions/clearcmd.py ip = self.shell user_ns = self.shell.user_ns # local lookup, heavily used for target in args: target = target.lower() # make matches case insensitive if target == 'out': print("Flushing output cache (%d entries)" % len(user_ns['_oh'])) self.shell.displayhook.flush() elif target == 'in': print("Flushing input history") pc = self.shell.displayhook.prompt_count + 1 for n in range(1, pc): key = '_i'+repr(n) user_ns.pop(key,None) user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) hm = ip.history_manager # don't delete these, as %save and %macro depending on the # length of these lists to be preserved hm.input_hist_parsed[:] = [''] * pc hm.input_hist_raw[:] = [''] * pc # hm has internal machinery for _i,_ii,_iii, clear it out hm._i = hm._ii = hm._iii = hm._i00 = u'' elif target == 'array': # Support cleaning up numpy arrays try: from numpy import ndarray # This must be done with items and not iteritems because # we're going to modify the dict in-place. for x,val in list(user_ns.items()): if isinstance(val,ndarray): del user_ns[x] except ImportError: print("reset array only works if Numpy is available.") elif target == 'dhist': print("Flushing directory history") del user_ns['_dh'][:] else: print("Don't know how to reset ", end=' ') print(target + ", please run `%reset?` for details") gc.collect() @line_magic def reset_selective(self, parameter_s=''): """Resets the namespace by removing names defined by the user. Input/Output history are left around in case you need them. %reset_selective [-f] regex No action is taken if regex is not included Options -f : force reset without asking for confirmation. See Also -------- reset : invoked as ``%reset`` Examples -------- We first fully reset the namespace so your output looks identical to this example for pedagogical reasons; in practice you do not need a full reset:: In [1]: %reset -f Now, with a clean namespace we can make a few variables and use ``%reset_selective`` to only delete names that match our regexp:: In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 In [3]: who_ls Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] In [4]: %reset_selective -f b[2-3]m In [5]: who_ls Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] In [6]: %reset_selective -f d In [7]: who_ls Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] In [8]: %reset_selective -f c In [9]: who_ls Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] In [10]: %reset_selective -f b In [11]: who_ls Out[11]: ['a'] Notes ----- Calling this magic from clients that do not implement standard input, such as the ipython notebook interface, will reset the namespace without confirmation. """ opts, regex = self.parse_options(parameter_s,'f') if 'f' in opts: ans = True else: try: ans = self.shell.ask_yes_no( "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n') except StdinNotImplementedError: ans = True if not ans: print('Nothing done.') return user_ns = self.shell.user_ns if not regex: print('No regex pattern specified. Nothing done.') return else: try: m = re.compile(regex) except TypeError as e: raise TypeError('regex must be a string or compiled pattern') from e for i in self.who_ls(): if m.search(i): del(user_ns[i]) @line_magic def xdel(self, parameter_s=''): """Delete a variable, trying to clear it from anywhere that IPython's machinery has references to it. By default, this uses the identity of the named object in the user namespace to remove references held under other names. The object is also removed from the output history. Options -n : Delete the specified name from all namespaces, without checking their identity. """ opts, varname = self.parse_options(parameter_s,'n') try: self.shell.del_var(varname, ('n' in opts)) except (NameError, ValueError) as e: print(type(e).__name__ +": "+ str(e))
NamespaceMagics
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/auto_contrast_test.py
{ "start": 121, "end": 3181 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_layer(self): self.run_layer_test( layers.AutoContrast, init_kwargs={ "value_range": (20, 200), }, input_shape=(8, 3, 4, 3), supports_masking=False, expected_output_shape=(8, 3, 4, 3), ) def test_constant_channels_dont_get_nanned(self): img = np.array([1, 1], dtype="float32") img = np.expand_dims(img, axis=-1) img = np.expand_dims(img, axis=-1) img = np.expand_dims(img, axis=0) layer = layers.AutoContrast(value_range=(0, 255)) ys = layer(img) self.assertTrue(np.any(ops.convert_to_numpy(ys[0]) == 1.0)) self.assertTrue(np.any(ops.convert_to_numpy(ys[0]) == 1.0)) def test_auto_contrast_expands_value_range(self): img = np.array([0, 128], dtype="float32") img = np.expand_dims(img, axis=-1) img = np.expand_dims(img, axis=-1) img = np.expand_dims(img, axis=0) layer = layers.AutoContrast(value_range=(0, 255)) ys = layer(img) self.assertTrue(np.any(ops.convert_to_numpy(ys[0]) == 0.0)) self.assertTrue(np.any(ops.convert_to_numpy(ys[0]) == 255.0)) def test_auto_contrast_different_values_per_channel(self): img = np.array( [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], dtype="float32", ) img = np.expand_dims(img, axis=0) layer = layers.AutoContrast(value_range=(0, 255)) ys = layer(img) self.assertTrue(np.any(ops.convert_to_numpy(ys[0, ..., 0]) == 0.0)) self.assertTrue(np.any(ops.convert_to_numpy(ys[0, ..., 1]) == 0.0)) self.assertTrue(np.any(ops.convert_to_numpy(ys[0, ..., 0]) == 255.0)) self.assertTrue(np.any(ops.convert_to_numpy(ys[0, ..., 1]) == 255.0)) self.assertAllClose( ys, [ [ [[0.0, 0.0, 0.0], [85.0, 85.0, 85.0]], [[170.0, 170.0, 170.0], [255.0, 255.0, 255.0]], ] ], ) def test_auto_contrast_expands_value_range_uint8(self): img = np.array([0, 128], dtype="uint8") img = np.expand_dims(img, axis=-1) img = np.expand_dims(img, axis=-1) img = np.expand_dims(img, axis=0) layer = layers.AutoContrast(value_range=(0, 255)) ys = layer(img) self.assertTrue(np.any(ops.convert_to_numpy(ys[0]) == 0.0)) self.assertTrue(np.any(ops.convert_to_numpy(ys[0]) == 255.0)) def test_auto_contrast_properly_converts_value_range(self): img = np.array([0, 0.5], dtype="float32") img = np.expand_dims(img, axis=-1) img = np.expand_dims(img, axis=-1) img = np.expand_dims(img, axis=0) layer = layers.AutoContrast(value_range=(0, 1)) ys = layer(img) self.assertAllClose( ops.convert_to_numpy(ys[0]), np.array([[[0.0]], [[1]]]) )
AutoContrastTest
python
numpy__numpy
numpy/_core/tests/test_dtype.py
{ "start": 47623, "end": 48209 }
class ____: def test_dtype_non_writable_attributes_deletion(self): dt = np.dtype(np.double) attr = ["subdtype", "descr", "str", "name", "base", "shape", "isbuiltin", "isnative", "isalignedstruct", "fields", "metadata", "hasobject"] for s in attr: assert_raises(AttributeError, delattr, dt, s) def test_dtype_writable_attributes_deletion(self): dt = np.dtype(np.double) attr = ["names"] for s in attr: assert_raises(AttributeError, delattr, dt, s)
TestDtypeAttributeDeletion
python
getsentry__sentry
src/sentry/middleware/stats.py
{ "start": 817, "end": 3115 }
class ____(MiddlewareMixin): allowed_methods = ("POST", "GET", "PUT", "DELETE") allowed_paths = getattr( settings, "SENTRY_REQUEST_METRIC_ALLOWED_PATHS", ("sentry.web.api", "sentry.api.endpoints") ) # Store endpoints def process_view( self, request: Request, view_func: ViewFunc, view_args: Any, view_kwargs: Any, ) -> Response | None: if request.method not in self.allowed_methods: return None path = get_path(view_func) if path and path.startswith(self.allowed_paths): setattr(request, "_view_path", path) setattr(request, "_start_time", time.time()) return None def process_response(self, request: Request, response: Response) -> Response: self._record_time(request, response.status_code) return response def process_exception(self, request: Request, exception: Exception) -> None: self._record_time(request, 500) @staticmethod def _record_time(request: Request, status_code: int) -> None: view_path = getattr(request, "_view_path", None) if not view_path: return if request.resolver_match is None or request.resolver_match.url_name is None: url_name = "unreachable-unknown" else: url_name = request.resolver_match.url_name rate_limit_type = getattr( getattr(request, "rate_limit_metadata", None), "rate_limit_type", None ) tags = { "method": request.method, "status_code": status_code, "ui_request": is_frontend_request(request), "rate_limit_type": ( getattr(rate_limit_type, "value", None) if rate_limit_type else None ), "url_name": url_name, } metrics.incr("view.response", instance=view_path, tags=tags, skip_internal=False) start_time = getattr(request, "_start_time", None) if not start_time: return ms = int((time.time() - start_time) * 1000) metrics.distribution( "view.duration", ms, instance=view_path, tags={"method": request.method}, unit="millisecond", )
RequestTimingMiddleware
python
numpy__numpy
numpy/lib/tests/test_function_base.py
{ "start": 116746, "end": 143190 }
class ____: def test_basic(self): x = np.arange(8) * 0.5 assert_equal(np.percentile(x, 0), 0.) assert_equal(np.percentile(x, 100), 3.5) assert_equal(np.percentile(x, 50), 1.75) x[1] = np.nan assert_equal(np.percentile(x, 0), np.nan) assert_equal(np.percentile(x, 0, method='nearest'), np.nan) assert_equal(np.percentile(x, 0, method='inverted_cdf'), np.nan) assert_equal( np.percentile(x, 0, method='inverted_cdf', weights=np.ones_like(x)), np.nan, ) def test_fraction(self): x = [Fraction(i, 2) for i in range(8)] p = np.percentile(x, Fraction(0)) assert_equal(p, Fraction(0)) assert_equal(type(p), Fraction) p = np.percentile(x, Fraction(100)) assert_equal(p, Fraction(7, 2)) assert_equal(type(p), Fraction) p = np.percentile(x, Fraction(50)) assert_equal(p, Fraction(7, 4)) assert_equal(type(p), Fraction) p = np.percentile(x, [Fraction(50)]) assert_equal(p, np.array([Fraction(7, 4)])) assert_equal(type(p), np.ndarray) def test_api(self): d = np.ones(5) np.percentile(d, 5, None, None, False) np.percentile(d, 5, None, None, False, 'linear') o = np.ones((1,)) np.percentile(d, 5, None, o, False, 'linear') def test_complex(self): arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='G') assert_raises(TypeError, np.percentile, arr_c, 0.5) arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='D') assert_raises(TypeError, np.percentile, arr_c, 0.5) arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='F') assert_raises(TypeError, np.percentile, arr_c, 0.5) def test_2D(self): x = np.array([[1, 1, 1], [1, 1, 1], [4, 4, 3], [1, 1, 1], [1, 1, 1]]) assert_array_equal(np.percentile(x, 50, axis=0), [1, 1, 1]) @pytest.mark.parametrize("dtype", np.typecodes["Float"]) def test_linear_nan_1D(self, dtype): # METHOD 1 of H&F arr = np.asarray([15.0, np.nan, 35.0, 40.0, 50.0], dtype=dtype) res = np.percentile( arr, 40.0, method="linear") np.testing.assert_equal(res, np.nan) np.testing.assert_equal(res.dtype, arr.dtype) H_F_TYPE_CODES = [(int_type, np.float64) for int_type in np.typecodes["AllInteger"] ] + [(np.float16, np.float16), (np.float32, np.float32), (np.float64, np.float64), (np.longdouble, np.longdouble), (np.dtype("O"), np.float64)] @pytest.mark.parametrize(["function", "quantile"], [(np.quantile, 0.4), (np.percentile, 40.0)]) @pytest.mark.parametrize(["input_dtype", "expected_dtype"], H_F_TYPE_CODES) @pytest.mark.parametrize(["method", "weighted", "expected"], [("inverted_cdf", False, 20), ("inverted_cdf", True, 20), ("averaged_inverted_cdf", False, 27.5), ("closest_observation", False, 20), ("interpolated_inverted_cdf", False, 20), ("hazen", False, 27.5), ("weibull", False, 26), ("linear", False, 29), ("median_unbiased", False, 27), ("normal_unbiased", False, 27.125), ]) def test_linear_interpolation(self, function, quantile, method, weighted, expected, input_dtype, expected_dtype): expected_dtype = np.dtype(expected_dtype) arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=input_dtype) weights = np.ones_like(arr) if weighted else None if input_dtype is np.longdouble: if function is np.quantile: # 0.4 is not exactly representable and it matters # for "averaged_inverted_cdf", so we need to cheat. quantile = input_dtype("0.4") # We want to use nulp, but that does not work for longdouble test_function = np.testing.assert_almost_equal else: test_function = np.testing.assert_array_almost_equal_nulp actual = function(arr, quantile, method=method, weights=weights) test_function(actual, expected_dtype.type(expected)) if method in ["inverted_cdf", "closest_observation"]: if input_dtype == "O": np.testing.assert_equal(np.asarray(actual).dtype, np.float64) else: np.testing.assert_equal(np.asarray(actual).dtype, np.dtype(input_dtype)) else: np.testing.assert_equal(np.asarray(actual).dtype, np.dtype(expected_dtype)) TYPE_CODES = np.typecodes["AllInteger"] + np.typecodes["Float"] + "O" @pytest.mark.parametrize("dtype", TYPE_CODES) def test_lower_higher(self, dtype): assert_equal(np.percentile(np.arange(10, dtype=dtype), 50, method='lower'), 4) assert_equal(np.percentile(np.arange(10, dtype=dtype), 50, method='higher'), 5) @pytest.mark.parametrize("dtype", TYPE_CODES) def test_midpoint(self, dtype): assert_equal(np.percentile(np.arange(10, dtype=dtype), 51, method='midpoint'), 4.5) assert_equal(np.percentile(np.arange(9, dtype=dtype) + 1, 50, method='midpoint'), 5) assert_equal(np.percentile(np.arange(11, dtype=dtype), 51, method='midpoint'), 5.5) assert_equal(np.percentile(np.arange(11, dtype=dtype), 50, method='midpoint'), 5) @pytest.mark.parametrize("dtype", TYPE_CODES) def test_nearest(self, dtype): assert_equal(np.percentile(np.arange(10, dtype=dtype), 51, method='nearest'), 5) assert_equal(np.percentile(np.arange(10, dtype=dtype), 49, method='nearest'), 4) def test_linear_interpolation_extrapolation(self): arr = np.random.rand(5) actual = np.percentile(arr, 100) np.testing.assert_equal(actual, arr.max()) actual = np.percentile(arr, 0) np.testing.assert_equal(actual, arr.min()) def test_sequence(self): x = np.arange(8) * 0.5 assert_equal(np.percentile(x, [0, 100, 50]), [0, 3.5, 1.75]) def test_axis(self): x = np.arange(12).reshape(3, 4) assert_equal(np.percentile(x, (25, 50, 100)), [2.75, 5.5, 11.0]) r0 = [[2, 3, 4, 5], [4, 5, 6, 7], [8, 9, 10, 11]] assert_equal(np.percentile(x, (25, 50, 100), axis=0), r0) r1 = [[0.75, 1.5, 3], [4.75, 5.5, 7], [8.75, 9.5, 11]] assert_equal(np.percentile(x, (25, 50, 100), axis=1), np.array(r1).T) # ensure qth axis is always first as with np.array(old_percentile(..)) x = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6) assert_equal(np.percentile(x, (25, 50)).shape, (2,)) assert_equal(np.percentile(x, (25, 50, 75)).shape, (3,)) assert_equal(np.percentile(x, (25, 50), axis=0).shape, (2, 4, 5, 6)) assert_equal(np.percentile(x, (25, 50), axis=1).shape, (2, 3, 5, 6)) assert_equal(np.percentile(x, (25, 50), axis=2).shape, (2, 3, 4, 6)) assert_equal(np.percentile(x, (25, 50), axis=3).shape, (2, 3, 4, 5)) assert_equal( np.percentile(x, (25, 50, 75), axis=1).shape, (3, 3, 5, 6)) assert_equal(np.percentile(x, (25, 50), method="higher").shape, (2,)) assert_equal(np.percentile(x, (25, 50, 75), method="higher").shape, (3,)) assert_equal(np.percentile(x, (25, 50), axis=0, method="higher").shape, (2, 4, 5, 6)) assert_equal(np.percentile(x, (25, 50), axis=1, method="higher").shape, (2, 3, 5, 6)) assert_equal(np.percentile(x, (25, 50), axis=2, method="higher").shape, (2, 3, 4, 6)) assert_equal(np.percentile(x, (25, 50), axis=3, method="higher").shape, (2, 3, 4, 5)) assert_equal(np.percentile(x, (25, 50, 75), axis=1, method="higher").shape, (3, 3, 5, 6)) def test_scalar_q(self): # test for no empty dimensions for compatibility with old percentile x = np.arange(12).reshape(3, 4) assert_equal(np.percentile(x, 50), 5.5) assert_(np.isscalar(np.percentile(x, 50))) r0 = np.array([4., 5., 6., 7.]) assert_equal(np.percentile(x, 50, axis=0), r0) assert_equal(np.percentile(x, 50, axis=0).shape, r0.shape) r1 = np.array([1.5, 5.5, 9.5]) assert_almost_equal(np.percentile(x, 50, axis=1), r1) assert_equal(np.percentile(x, 50, axis=1).shape, r1.shape) out = np.empty(1) assert_equal(np.percentile(x, 50, out=out), 5.5) assert_equal(out, 5.5) out = np.empty(4) assert_equal(np.percentile(x, 50, axis=0, out=out), r0) assert_equal(out, r0) out = np.empty(3) assert_equal(np.percentile(x, 50, axis=1, out=out), r1) assert_equal(out, r1) # test for no empty dimensions for compatibility with old percentile x = np.arange(12).reshape(3, 4) assert_equal(np.percentile(x, 50, method='lower'), 5.) assert_(np.isscalar(np.percentile(x, 50))) r0 = np.array([4., 5., 6., 7.]) c0 = np.percentile(x, 50, method='lower', axis=0) assert_equal(c0, r0) assert_equal(c0.shape, r0.shape) r1 = np.array([1., 5., 9.]) c1 = np.percentile(x, 50, method='lower', axis=1) assert_almost_equal(c1, r1) assert_equal(c1.shape, r1.shape) out = np.empty((), dtype=x.dtype) c = np.percentile(x, 50, method='lower', out=out) assert_equal(c, 5) assert_equal(out, 5) out = np.empty(4, dtype=x.dtype) c = np.percentile(x, 50, method='lower', axis=0, out=out) assert_equal(c, r0) assert_equal(out, r0) out = np.empty(3, dtype=x.dtype) c = np.percentile(x, 50, method='lower', axis=1, out=out) assert_equal(c, r1) assert_equal(out, r1) def test_exception(self): assert_raises(ValueError, np.percentile, [1, 2], 56, method='foobar') assert_raises(ValueError, np.percentile, [1], 101) assert_raises(ValueError, np.percentile, [1], -1) assert_raises(ValueError, np.percentile, [1], list(range(50)) + [101]) assert_raises(ValueError, np.percentile, [1], list(range(50)) + [-0.1]) def test_percentile_list(self): assert_equal(np.percentile([1, 2, 3], 0), 1) @pytest.mark.parametrize( "percentile, with_weights", [ (np.percentile, False), (partial(np.percentile, method="inverted_cdf"), True), ] ) def test_percentile_out(self, percentile, with_weights): out_dtype = int if with_weights else float x = np.array([1, 2, 3]) y = np.zeros((3,), dtype=out_dtype) p = (1, 2, 3) weights = np.ones_like(x) if with_weights else None r = percentile(x, p, out=y, weights=weights) assert r is y assert_equal(percentile(x, p, weights=weights), y) x = np.array([[1, 2, 3], [4, 5, 6]]) y = np.zeros((3, 3), dtype=out_dtype) weights = np.ones_like(x) if with_weights else None r = percentile(x, p, axis=0, out=y, weights=weights) assert r is y assert_equal(percentile(x, p, weights=weights, axis=0), y) y = np.zeros((3, 2), dtype=out_dtype) percentile(x, p, axis=1, out=y, weights=weights) assert_equal(percentile(x, p, weights=weights, axis=1), y) x = np.arange(12).reshape(3, 4) # q.dim > 1, float if with_weights: r0 = np.array([[0, 1, 2, 3], [4, 5, 6, 7]]) else: r0 = np.array([[2., 3., 4., 5.], [4., 5., 6., 7.]]) out = np.empty((2, 4), dtype=out_dtype) weights = np.ones_like(x) if with_weights else None assert_equal( percentile(x, (25, 50), axis=0, out=out, weights=weights), r0 ) assert_equal(out, r0) r1 = np.array([[0.75, 4.75, 8.75], [1.5, 5.5, 9.5]]) out = np.empty((2, 3)) assert_equal(np.percentile(x, (25, 50), axis=1, out=out), r1) assert_equal(out, r1) # q.dim > 1, int r0 = np.array([[0, 1, 2, 3], [4, 5, 6, 7]]) out = np.empty((2, 4), dtype=x.dtype) c = np.percentile(x, (25, 50), method='lower', axis=0, out=out) assert_equal(c, r0) assert_equal(out, r0) r1 = np.array([[0, 4, 8], [1, 5, 9]]) out = np.empty((2, 3), dtype=x.dtype) c = np.percentile(x, (25, 50), method='lower', axis=1, out=out) assert_equal(c, r1) assert_equal(out, r1) def test_percentile_empty_dim(self): # empty dims are preserved d = np.arange(11 * 2).reshape(11, 1, 2, 1) assert_array_equal(np.percentile(d, 50, axis=0).shape, (1, 2, 1)) assert_array_equal(np.percentile(d, 50, axis=1).shape, (11, 2, 1)) assert_array_equal(np.percentile(d, 50, axis=2).shape, (11, 1, 1)) assert_array_equal(np.percentile(d, 50, axis=3).shape, (11, 1, 2)) assert_array_equal(np.percentile(d, 50, axis=-1).shape, (11, 1, 2)) assert_array_equal(np.percentile(d, 50, axis=-2).shape, (11, 1, 1)) assert_array_equal(np.percentile(d, 50, axis=-3).shape, (11, 2, 1)) assert_array_equal(np.percentile(d, 50, axis=-4).shape, (1, 2, 1)) assert_array_equal(np.percentile(d, 50, axis=2, method='midpoint').shape, (11, 1, 1)) assert_array_equal(np.percentile(d, 50, axis=-2, method='midpoint').shape, (11, 1, 1)) assert_array_equal(np.array(np.percentile(d, [10, 50], axis=0)).shape, (2, 1, 2, 1)) assert_array_equal(np.array(np.percentile(d, [10, 50], axis=1)).shape, (2, 11, 2, 1)) assert_array_equal(np.array(np.percentile(d, [10, 50], axis=2)).shape, (2, 11, 1, 1)) assert_array_equal(np.array(np.percentile(d, [10, 50], axis=3)).shape, (2, 11, 1, 2)) def test_percentile_no_overwrite(self): a = np.array([2, 3, 4, 1]) np.percentile(a, [50], overwrite_input=False) assert_equal(a, np.array([2, 3, 4, 1])) a = np.array([2, 3, 4, 1]) np.percentile(a, [50]) assert_equal(a, np.array([2, 3, 4, 1])) def test_no_p_overwrite(self): p = np.linspace(0., 100., num=5) np.percentile(np.arange(100.), p, method="midpoint") assert_array_equal(p, np.linspace(0., 100., num=5)) p = np.linspace(0., 100., num=5).tolist() np.percentile(np.arange(100.), p, method="midpoint") assert_array_equal(p, np.linspace(0., 100., num=5).tolist()) def test_percentile_overwrite(self): a = np.array([2, 3, 4, 1]) b = np.percentile(a, [50], overwrite_input=True) assert_equal(b, np.array([2.5])) b = np.percentile([2, 3, 4, 1], [50], overwrite_input=True) assert_equal(b, np.array([2.5])) def test_extended_axis(self): o = np.random.normal(size=(71, 23)) x = np.dstack([o] * 10) assert_equal(np.percentile(x, 30, axis=(0, 1)), np.percentile(o, 30)) x = np.moveaxis(x, -1, 0) assert_equal(np.percentile(x, 30, axis=(-2, -1)), np.percentile(o, 30)) x = x.swapaxes(0, 1).copy() assert_equal(np.percentile(x, 30, axis=(0, -1)), np.percentile(o, 30)) x = x.swapaxes(0, 1).copy() assert_equal(np.percentile(x, [25, 60], axis=(0, 1, 2)), np.percentile(x, [25, 60], axis=None)) assert_equal(np.percentile(x, [25, 60], axis=(0,)), np.percentile(x, [25, 60], axis=0)) d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11)) np.random.shuffle(d.ravel()) assert_equal(np.percentile(d, 25, axis=(0, 1, 2))[0], np.percentile(d[:, :, :, 0].flatten(), 25)) assert_equal(np.percentile(d, [10, 90], axis=(0, 1, 3))[:, 1], np.percentile(d[:, :, 1, :].flatten(), [10, 90])) assert_equal(np.percentile(d, 25, axis=(3, 1, -4))[2], np.percentile(d[:, :, 2, :].flatten(), 25)) assert_equal(np.percentile(d, 25, axis=(3, 1, 2))[2], np.percentile(d[2, :, :, :].flatten(), 25)) assert_equal(np.percentile(d, 25, axis=(3, 2))[2, 1], np.percentile(d[2, 1, :, :].flatten(), 25)) assert_equal(np.percentile(d, 25, axis=(1, -2))[2, 1], np.percentile(d[2, :, :, 1].flatten(), 25)) assert_equal(np.percentile(d, 25, axis=(1, 3))[2, 2], np.percentile(d[2, :, 2, :].flatten(), 25)) def test_extended_axis_invalid(self): d = np.ones((3, 5, 7, 11)) assert_raises(AxisError, np.percentile, d, axis=-5, q=25) assert_raises(AxisError, np.percentile, d, axis=(0, -5), q=25) assert_raises(AxisError, np.percentile, d, axis=4, q=25) assert_raises(AxisError, np.percentile, d, axis=(0, 4), q=25) # each of these refers to the same axis twice assert_raises(ValueError, np.percentile, d, axis=(1, 1), q=25) assert_raises(ValueError, np.percentile, d, axis=(-1, -1), q=25) assert_raises(ValueError, np.percentile, d, axis=(3, -1), q=25) def test_keepdims(self): d = np.ones((3, 5, 7, 11)) assert_equal(np.percentile(d, 7, axis=None, keepdims=True).shape, (1, 1, 1, 1)) assert_equal(np.percentile(d, 7, axis=(0, 1), keepdims=True).shape, (1, 1, 7, 11)) assert_equal(np.percentile(d, 7, axis=(0, 3), keepdims=True).shape, (1, 5, 7, 1)) assert_equal(np.percentile(d, 7, axis=(1,), keepdims=True).shape, (3, 1, 7, 11)) assert_equal(np.percentile(d, 7, (0, 1, 2, 3), keepdims=True).shape, (1, 1, 1, 1)) assert_equal(np.percentile(d, 7, axis=(0, 1, 3), keepdims=True).shape, (1, 1, 7, 1)) assert_equal(np.percentile(d, [1, 7], axis=(0, 1, 3), keepdims=True).shape, (2, 1, 1, 7, 1)) assert_equal(np.percentile(d, [1, 7], axis=(0, 3), keepdims=True).shape, (2, 1, 5, 7, 1)) @pytest.mark.parametrize('q', [7, [1, 7]]) @pytest.mark.parametrize( argnames='axis', argvalues=[ None, 1, (1,), (0, 1), (-3, -1), ] ) def test_keepdims_out(self, q, axis): d = np.ones((3, 5, 7, 11)) if axis is None: shape_out = (1,) * d.ndim else: axis_norm = normalize_axis_tuple(axis, d.ndim) shape_out = tuple( 1 if i in axis_norm else d.shape[i] for i in range(d.ndim)) shape_out = np.shape(q) + shape_out out = np.empty(shape_out) result = np.percentile(d, q, axis=axis, keepdims=True, out=out) assert result is out assert_equal(result.shape, shape_out) def test_out(self): o = np.zeros((4,)) d = np.ones((3, 4)) assert_equal(np.percentile(d, 0, 0, out=o), o) assert_equal(np.percentile(d, 0, 0, method='nearest', out=o), o) o = np.zeros((3,)) assert_equal(np.percentile(d, 1, 1, out=o), o) assert_equal(np.percentile(d, 1, 1, method='nearest', out=o), o) o = np.zeros(()) assert_equal(np.percentile(d, 2, out=o), o) assert_equal(np.percentile(d, 2, method='nearest', out=o), o) @pytest.mark.parametrize("method, weighted", [ ("linear", False), ("nearest", False), ("inverted_cdf", False), ("inverted_cdf", True), ]) def test_out_nan(self, method, weighted): if weighted: kwargs = {"weights": np.ones((3, 4)), "method": method} else: kwargs = {"method": method} with warnings.catch_warnings(record=True): warnings.filterwarnings('always', '', RuntimeWarning) o = np.zeros((4,)) d = np.ones((3, 4)) d[2, 1] = np.nan assert_equal(np.percentile(d, 0, 0, out=o, **kwargs), o) o = np.zeros((3,)) assert_equal(np.percentile(d, 1, 1, out=o, **kwargs), o) o = np.zeros(()) assert_equal(np.percentile(d, 1, out=o, **kwargs), o) def test_nan_behavior(self): a = np.arange(24, dtype=float) a[2] = np.nan assert_equal(np.percentile(a, 0.3), np.nan) assert_equal(np.percentile(a, 0.3, axis=0), np.nan) assert_equal(np.percentile(a, [0.3, 0.6], axis=0), np.array([np.nan] * 2)) a = np.arange(24, dtype=float).reshape(2, 3, 4) a[1, 2, 3] = np.nan a[1, 1, 2] = np.nan # no axis assert_equal(np.percentile(a, 0.3), np.nan) assert_equal(np.percentile(a, 0.3).ndim, 0) # axis0 zerod b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 0) b[2, 3] = np.nan b[1, 2] = np.nan assert_equal(np.percentile(a, 0.3, 0), b) # axis0 not zerod b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), [0.3, 0.6], 0) b[:, 2, 3] = np.nan b[:, 1, 2] = np.nan assert_equal(np.percentile(a, [0.3, 0.6], 0), b) # axis1 zerod b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 1) b[1, 3] = np.nan b[1, 2] = np.nan assert_equal(np.percentile(a, 0.3, 1), b) # axis1 not zerod b = np.percentile( np.arange(24, dtype=float).reshape(2, 3, 4), [0.3, 0.6], 1) b[:, 1, 3] = np.nan b[:, 1, 2] = np.nan assert_equal(np.percentile(a, [0.3, 0.6], 1), b) # axis02 zerod b = np.percentile( np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, (0, 2)) b[1] = np.nan b[2] = np.nan assert_equal(np.percentile(a, 0.3, (0, 2)), b) # axis02 not zerod b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), [0.3, 0.6], (0, 2)) b[:, 1] = np.nan b[:, 2] = np.nan assert_equal(np.percentile(a, [0.3, 0.6], (0, 2)), b) # axis02 not zerod with method='nearest' b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), [0.3, 0.6], (0, 2), method='nearest') b[:, 1] = np.nan b[:, 2] = np.nan assert_equal(np.percentile( a, [0.3, 0.6], (0, 2), method='nearest'), b) def test_nan_q(self): # GH18830 with pytest.raises(ValueError, match="Percentiles must be in"): np.percentile([1, 2, 3, 4.0], np.nan) with pytest.raises(ValueError, match="Percentiles must be in"): np.percentile([1, 2, 3, 4.0], [np.nan]) q = np.linspace(1.0, 99.0, 16) q[0] = np.nan with pytest.raises(ValueError, match="Percentiles must be in"): np.percentile([1, 2, 3, 4.0], q) @pytest.mark.parametrize("dtype", ["m8[D]", "M8[s]"]) @pytest.mark.parametrize("pos", [0, 23, 10]) def test_nat_basic(self, dtype, pos): # TODO: Note that times have dubious rounding as of fixing NaTs! # NaT and NaN should behave the same, do basic tests for NaT: a = np.arange(0, 24, dtype=dtype) a[pos] = "NaT" res = np.percentile(a, 30) assert res.dtype == dtype assert np.isnat(res) res = np.percentile(a, [30, 60]) assert res.dtype == dtype assert np.isnat(res).all() a = np.arange(0, 24 * 3, dtype=dtype).reshape(-1, 3) a[pos, 1] = "NaT" res = np.percentile(a, 30, axis=0) assert_array_equal(np.isnat(res), [False, True, False]) @pytest.mark.parametrize("qtype", [np.float16, np.float32]) @pytest.mark.parametrize("method", quantile_methods) def test_percentile_gh_29003(self, qtype, method): # test that with float16 or float32 input we do not get overflow zero = qtype(0) one = qtype(1) a = np.zeros(65521, qtype) a[:20_000] = one z = np.percentile(a, 50, method=method) assert z == zero assert z.dtype == a.dtype z = np.percentile(a, 99, method=method) assert z == one assert z.dtype == a.dtype def test_percentile_gh_29003_Fraction(self): zero = Fraction(0) one = Fraction(1) a = np.array([zero] * 65521) a[:20_000] = one z = np.percentile(a, 50) assert z == zero z = np.percentile(a, Fraction(50)) assert z == zero assert np.array(z).dtype == a.dtype z = np.percentile(a, 99) assert z == one # test that with only Fraction input the return type is a Fraction z = np.percentile(a, Fraction(99)) assert z == one assert np.array(z).dtype == a.dtype
TestPercentile
python
gevent__gevent
src/gevent/_hub_local.py
{ "start": 537, "end": 4827 }
class ____(_thread._local): def __init__(self): # Use a class with an initializer so that we can test # for 'is None' instead of catching AttributeError, making # the code cleaner and possibly solving some corner cases # (like #687). # # However, under some weird circumstances, it _seems_ like the # __init__ method doesn't get called properly ("seems" is the # keyword). We've seen at least one instance # (https://github.com/gevent/gevent/issues/1961) of # ``AttributeError: '_Threadlocal' object has no attribute # 'hub'`` # which should be impossible unless: # # - Someone manually deletes the attribute # - The _threadlocal object itself is in the process of being # deleted. The C ``tp_clear`` slot for it deletes the ``__dict__`` # of each instance in each thread (and/or the ``tp_clear`` of ``dict`` itself # clears the instance). Now, how we could be getting # cleared while still being used is unclear, but clearing is part of # circular garbage collection, and in the bug report it looks like we're inside a # weakref finalizer or ``__del__`` method, which could suggest that # garbage collection is happening. # # See https://github.com/gevent/gevent/issues/1961 # and ``get_hub_if_exists()`` super(_Threadlocal, self).__init__() self.Hub = None self.loop = None self.hub = None _threadlocal = _Threadlocal() Hub = None # Set when gevent.hub is imported def get_hub_class(): """Return the type of hub to use for the current thread. If there's no type of hub for the current thread yet, 'gevent.hub.Hub' is used. """ try: hubtype = _threadlocal.Hub except AttributeError: hubtype = None if hubtype is None: hubtype = _threadlocal.Hub = Hub return hubtype def set_default_hub_class(hubtype): global Hub Hub = hubtype def get_hub(): """ Return the hub for the current thread. If a hub does not exist in the current thread, a new one is created of the type returned by :func:`get_hub_class`. .. deprecated:: 1.3b1 The ``*args`` and ``**kwargs`` arguments are deprecated. They were only used when the hub was created, and so were non-deterministic---to be sure they were used, *all* callers had to pass them, or they were order-dependent. Use ``set_hub`` instead. .. versionchanged:: 1.5a3 The *args* and *kwargs* arguments are now completely ignored. .. versionchanged:: 23.7.0 The long-deprecated ``args`` and ``kwargs`` parameters are no longer accepted. """ # See get_hub_if_exists try: hub = _threadlocal.hub except AttributeError: hub = None if hub is None: hubtype = get_hub_class() hub = _threadlocal.hub = hubtype() return hub # For Cython purposes, we need to duplicate get_hub into this function so it # can be directly called. def get_hub_noargs(): # See get_hub_if_exists try: hub = _threadlocal.hub except AttributeError: hub = None if hub is None: hubtype = get_hub_class() hub = _threadlocal.hub = hubtype() return hub def get_hub_if_exists(): """ Return the hub for the current thread. Return ``None`` if no hub has been created yet. """ # Attempt a band-aid for the poorly-understood behaviour # seen in https://github.com/gevent/gevent/issues/1961 # where the ``hub`` attribute has gone missing. try: return _threadlocal.hub except AttributeError: # XXX: I'd really like to report this, but I'm not sure how # that can be done safely (because I don't know how we get # here in the first place). We may be in a place where imports # are unsafe, or the interpreter is shutting down, or the # thread is exiting, or... return None def set_hub(hub): _threadlocal.hub = hub def get_loop(): return _threadlocal.loop def set_loop(loop): _threadlocal.loop = loop from gevent._util import import_c_accel import_c_accel(globals(), 'gevent.__hub_local')
_Threadlocal
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-sec-filings/llama_index/readers/sec_filings/prepline_sec_filings/api/section.py
{ "start": 1876, "end": 7367 }
class ____: def __init__(self, seconds=1, error_message="Timeout") -> None: self.seconds = seconds self.error_message = error_message def handle_timeout(self, signum, frame): raise TimeoutError(self.error_message) def __enter__(self) -> None: try: signal.signal(signal.SIGALRM, self.handle_timeout) signal.alarm(self.seconds) except ValueError: pass def __exit__(self, type, value, traceback) -> None: try: signal.alarm(0) except ValueError: pass def get_regex_enum(section_regex): class CustomSECSection(Enum): CUSTOM = re.compile(section_regex) @property def pattern(self): return self.value return CustomSECSection.CUSTOM def convert_to_isd_csv(results: dict) -> str: """ Returns the representation of document elements as an Initial Structured Document (ISD) in CSV Format. """ csv_fieldnames: List[str] = ["section", "element_type", "text"] new_rows = [] for section, section_narrative in results.items(): rows: List[Dict[str, str]] = convert_to_isd(section_narrative) for row in rows: new_row_item = {} new_row_item["section"] = section new_row_item["element_type"] = row["type"] new_row_item["text"] = row["text"] new_rows.append(new_row_item) with io.StringIO() as buffer: csv_writer = csv.DictWriter(buffer, fieldnames=csv_fieldnames) csv_writer.writeheader() csv_writer.writerows(new_rows) return buffer.getvalue() # List of valid response schemas LABELSTUDIO = "labelstudio" ISD = "isd" def pipeline_api( text, response_type="application/json", response_schema="isd", m_section=[], m_section_regex=[], ): """Many supported sections including: RISK_FACTORS, MANAGEMENT_DISCUSSION, and many more.""" validate_section_names(m_section) sec_document = SECDocument.from_string(text) if sec_document.filing_type not in VALID_FILING_TYPES: raise ValueError( f"SEC document filing type {sec_document.filing_type} is not supported, " f"must be one of {','.join(VALID_FILING_TYPES)}" ) results = {} if m_section == [ALL_SECTIONS]: filing_type = sec_document.filing_type if filing_type in REPORT_TYPES: if filing_type.startswith("10-K"): m_section = [enum.name for enum in SECTIONS_10K] elif filing_type.startswith("10-Q"): m_section = [enum.name for enum in SECTIONS_10Q] else: raise ValueError(f"Invalid report type: {filing_type}") else: m_section = [enum.name for enum in SECTIONS_S1] for section in m_section: results[section] = sec_document.get_section_narrative( section_string_to_enum[section] ) for i, section_regex in enumerate(m_section_regex): regex_enum = get_regex_enum(section_regex) with timeout(seconds=5): section_elements = sec_document.get_section_narrative(regex_enum) results[f"REGEX_{i}"] = section_elements if response_type == "application/json": if response_schema == LABELSTUDIO: return { section: stage_for_label_studio(section_narrative) for section, section_narrative in results.items() } elif response_schema == ISD: return { section: convert_to_isd(section_narrative) for section, section_narrative in results.items() } else: raise ValueError( f"output_schema '{response_schema}' is not supported for" f" {response_type}" ) elif response_type == "text/csv": if response_schema != ISD: raise ValueError( f"output_schema '{response_schema}' is not supported for" f" {response_type}" ) return convert_to_isd_csv(results) else: raise ValueError(f"response_type '{response_type}' is not supported") def get_validated_mimetype(file): """ Return a file's mimetype, either via the file.content_type or the mimetypes lib if that's too generic. If the user has set UNSTRUCTURED_ALLOWED_MIMETYPES, validate against this list and return HTTP 400 for an invalid type. """ content_type = file.content_type if not content_type or content_type == "application/octet-stream": content_type = mimetypes.guess_type(str(file.filename))[0] # Some filetypes missing for this library, just hardcode them for now if not content_type: if file.filename.endswith(".md"): content_type = "text/markdown" elif file.filename.endswith(".msg"): content_type = "message/rfc822" allowed_mimetypes_str = os.environ.get("UNSTRUCTURED_ALLOWED_MIMETYPES") if allowed_mimetypes_str is not None: allowed_mimetypes = allowed_mimetypes_str.split(",") if content_type not in allowed_mimetypes: raise HTTPException( status_code=400, detail=( f"Unable to process {file.filename}: " f"File type {content_type} is not supported." ), ) return content_type
timeout
python
dagster-io__dagster
python_modules/libraries/dagster-deltalake/dagster_deltalake/io_manager.py
{ "start": 5681, "end": 9358 }
class ____(DbClient): @staticmethod def delete_table_slice( context: OutputContext, table_slice: TableSlice, connection: TableConnection ) -> None: # deleting the table slice here is a no-op, since we use deltalake's internal mechanism # to overwrite table partitions. pass @staticmethod def ensure_schema_exists( context: OutputContext, table_slice: TableSlice, connection: TableConnection ) -> None: # schemas are just folders and automatically created on write. pass @staticmethod def get_select_statement(table_slice: TableSlice) -> str: # The select statement here is just for illustrative purposes, # and is never actually executed. It does however logically correspond # the operation being executed. col_str = ", ".join(table_slice.columns) if table_slice.columns else "*" if table_slice.partition_dimensions: query = f"SELECT {col_str} FROM {table_slice.schema}.{table_slice.table} WHERE\n" return query + _partition_where_clause(table_slice.partition_dimensions) else: return f"""SELECT {col_str} FROM {table_slice.schema}.{table_slice.table}""" @staticmethod @contextmanager def connect(context, table_slice: TableSlice) -> Iterator[TableConnection]: resource_config = cast("_DeltaTableIOManagerResourceConfig", context.resource_config) root_uri = resource_config["root_uri"].rstrip("/") storage_options = resource_config["storage_options"] if "local" in storage_options: storage_options = storage_options["local"] elif "s3" in storage_options: storage_options = storage_options["s3"] elif "azure" in storage_options: storage_options = storage_options["azure"] elif "gcs" in storage_options: storage_options = storage_options["gcs"] else: storage_options = {} client_options = resource_config.get("client_options") client_options = client_options or {} storage_options = { **{k: str(v) for k, v in storage_options.items() if v is not None}, **{k: str(v) for k, v in client_options.items() if v is not None}, } table_config = resource_config.get("table_config") table_uri = f"{root_uri}/{table_slice.schema}/{table_slice.table}" conn = TableConnection( table_uri=table_uri, storage_options=storage_options or {}, table_config=table_config, ) yield conn def _partition_where_clause( partition_dimensions: Sequence[TablePartitionDimension], ) -> str: return " AND\n".join( ( _time_window_where_clause(partition_dimension) if isinstance(partition_dimension.partitions, TimeWindow) else _static_where_clause(partition_dimension) ) for partition_dimension in partition_dimensions ) def _time_window_where_clause(table_partition: TablePartitionDimension) -> str: partition = cast("TimeWindow", table_partition.partitions) start_dt, end_dt = partition start_dt_str = start_dt.strftime(DELTA_DATETIME_FORMAT) end_dt_str = end_dt.strftime(DELTA_DATETIME_FORMAT) return f"""{table_partition.partition_expr} >= '{start_dt_str}' AND {table_partition.partition_expr} < '{end_dt_str}'""" def _static_where_clause(table_partition: TablePartitionDimension) -> str: partitions = ", ".join(f"'{partition}'" for partition in table_partition.partitions) return f"""{table_partition.partition_expr} in ({partitions})"""
DeltaLakeDbClient
python
readthedocs__readthedocs.org
readthedocs/redirects/migrations/0003_add_default_redirect_http_status_to_302.py
{ "start": 297, "end": 933 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("redirects", "0002_add_missing_model_change_migrations"), ] operations = [ migrations.RunPython(change_http_status), migrations.AlterField( model_name="redirect", name="http_status", field=models.SmallIntegerField( choices=[ (301, "301 - Permanent Redirect"), (302, "302 - Temporary Redirect"), ], default=302, verbose_name="HTTP Status", ), ), ]
Migration
python
encode__django-rest-framework
tests/schemas/test_coreapi.py
{ "start": 2019, "end": 2214 }
class ____(serializers.Serializer): a = serializers.ListField(child=serializers.IntegerField()) b = serializers.ListSerializer(child=serializers.CharField())
AnotherSerializerWithListFields
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol9.py
{ "start": 751, "end": 909 }
class ____: class CallableClass: def __call__(self) -> "ImplA": return ImplA() method1 = CallableClass() v1: ProtoA = ImplA()
ImplA
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/utils/eks_test_constants.py
{ "start": 6299, "end": 7433 }
class ____: """The compiled RegEx patterns used in testing.""" CLUSTER_ARN: Pattern = re.compile( r"""arn: (?P<partition>.+): eks: (?P<region>[-0-9a-zA-Z]+): (?P<account_id>[0-9]{12}): cluster/ (?P<cluster_name>.+)""", re.VERBOSE, ) FARGATE_PROFILE_ARN: Pattern = re.compile( r"""arn: (?P<partition>.+): eks: (?P<region>[-0-9a-zA-Z]+): (?P<account_id>[0-9]{12}): fargateprofile/ (?P<cluster_name>.+)/ (?P<fargate_name>.+)/""" + FARGATE_PROFILE_UUID_PATTERN, re.VERBOSE, ) NODEGROUP_ARN: Pattern = re.compile( r"""arn: (?P<partition>.+): eks: (?P<region>[-0-9a-zA-Z]+): (?P<account_id>[0-9]{12}): nodegroup/ (?P<cluster_name>.+)/ (?P<nodegroup_name>.+)/""" + NODEGROUP_UUID_PATTERN, re.VERBOSE, ) NODEGROUP_ASG_NAME_PATTERN: Pattern = re.compile(f"eks-{NODEGROUP_UUID_PATTERN}") NODEGROUP_SECURITY_GROUP_NAME_PATTERN: Pattern = re.compile(r"sg-([-0-9a-z]{17})")
RegExTemplates
python
google__jax
tests/lax_test.py
{ "start": 165620, "end": 167103 }
class ____: shape: tuple[int, ...] data: jax.Array def __init__(self, shape, data): assert data.shape == (*shape, 2) self.shape = shape self.data = data def __repr__(self) -> str: shape = ','.join(map(str, self.shape)) return f'foo[{shape}] with value\n{self.data}' size = property(lambda self: self.data.size // 2) ndim = property(lambda self: self.data.ndim - 1) def shard_foo_array_handler(xs, shardings, layouts, copy_semantics): results = [] for x, sharding in safe_zip(xs, shardings): device, = sharding._addressable_device_assignment aval = core.get_aval(x.data) results.append(pxla.batched_device_put( aval, jax.sharding.SingleDeviceSharding(device), [x.data], [device])) return results def foo_array_constant_handler(x, aval): return array._array_mlir_constant_handler(x.data, aval) def make_lowering(*, shape): return jnp.zeros((*shape, 2), 'uint32') def bake_lowering(k): return k.T def take_lowering(k): return jnp.broadcast_to(jnp.float32(k.size), k.shape) def jake_lowering(k): return jnp.ones((*k.shape, 2), 'uint32') def bake_vmap(batched_args, batch_dims): xs, = batched_args bdim_in, = batch_dims ys = bake(xs) perm = list(reversed(range(xs.ndim))) bdim_out = perm[bdim_in] return ys, bdim_out # All tests in this test class are thread-hostile because they add and remove # primitives from global maps. @jtu.thread_unsafe_test_class() # registration isn't thread-safe
FooArray
python
PrefectHQ__prefect
tests/test_task_engine.py
{ "start": 75529, "end": 80634 }
class ____: async def test_generator_task(self): """ Test for generator behavior including StopIteration """ @task async def g(): yield 1 yield 2 counter = 0 async for val in g(): if counter == 0: assert val == 1 if counter == 1: assert val == 2 assert counter <= 1 counter += 1 async def test_generator_task_requires_return_type_result(self): @task async def g(): yield 1 with pytest.raises( ValueError, match="The return_type for a generator task must be 'result'" ): async for i in g(return_state=True): pass async def test_generator_task_states( self, prefect_client: PrefectClient, events_pipeline ): """ Test for generator behavior including StopIteration """ @task async def g(): yield TaskRunContext.get().task_run.id async for val in g(): tr_id = val await events_pipeline.process_events() tr = await prefect_client.read_task_run(tr_id) assert tr.state.is_running() await events_pipeline.process_events() tr = await prefect_client.read_task_run(tr_id) assert tr.state.is_completed() async def test_generator_task_with_exception(self): @task async def g(): yield 1 raise ValueError("xyz") with pytest.raises(ValueError, match="xyz"): async for val in g(): assert val == 1 async def test_generator_task_with_exception_is_failed( self, prefect_client: PrefectClient, events_pipeline ): @task async def g(): yield TaskRunContext.get().task_run.id raise ValueError("xyz") with pytest.raises(ValueError, match="xyz"): async for val in g(): tr_id = val await events_pipeline.process_events() tr = await prefect_client.read_task_run(tr_id) assert tr.state.is_failed() async def test_generator_parent_tracking( self, prefect_client: PrefectClient, events_pipeline ): """ """ @task(task_run_name="gen-1000") async def g(): yield 1000 @task async def f(x): return TaskRunContext.get().task_run.id @flow async def parent_tracking(): async for val in g(): tr_id = await f(val) return tr_id tr_id = await parent_tracking() await events_pipeline.process_events() tr = await prefect_client.read_task_run(tr_id) assert "x" in tr.task_inputs assert "__parents__" in tr.task_inputs # the parent run and upstream 'x' run are the same assert tr.task_inputs["__parents__"][0].id == tr.task_inputs["x"][0].id # the parent run is "gen-1000" gen_id = tr.task_inputs["__parents__"][0].id await events_pipeline.process_events() gen_tr = await prefect_client.read_task_run(gen_id) assert gen_tr.name == "gen-1000" async def test_generator_retries(self): """ Test that a generator can retry and will re-emit its events """ @task(retries=2) async def g(): yield 1 yield 2 raise ValueError() values = [] try: async for v in g(): values.append(v) except ValueError: pass assert values == [1, 2, 1, 2, 1, 2] @pytest.mark.xfail( reason="Synchronous sleep in an async task is not interruptible by async timeout" ) async def test_generator_timeout_with_sync_sleep(self): """ Test that a generator can timeout """ @task(timeout_seconds=0.1) async def g(): yield 1 time.sleep(2) yield 2 values = [] with pytest.raises(TimeoutError): async for v in g(): values.append(v) assert values == [1] async def test_generator_timeout_with_async_sleep(self): """ Test that a generator can timeout """ @task(timeout_seconds=0.1) async def g(): yield 1 await asyncio.sleep(2) yield 2 values = [] with pytest.raises(TimeoutError): async for v in g(): values.append(v) assert values == [1] async def test_generator_doesnt_retry_on_generator_exception(self): """ Test that a generator doesn't retry for normal generator exceptions like StopIteration """ @task(retries=2) async def g(): yield 1 yield 2 values = [] try: async for v in g(): values.append(v) except ValueError: pass assert values == [1, 2]
TestAsyncGenerators
python
SmileyChris__easy-thumbnails
easy_thumbnails/widgets.py
{ "start": 193, "end": 2563 }
class ____(ClearableFileInput): """ Use this widget to show a thumbnail of the image next to the image file. If using the admin and :class:`~easy_thumbnails.fields.ThumbnailerField`, you can use this widget automatically with the following code:: class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { ThumbnailerField: {'widget': ImageClearableFileInput}, } """ template_with_initial = ( '%(clear_template)s<br />' '%(input_text)s: %(input)s' ) template_with_thumbnail = ( '%(template)s<br />' '<a href="%(source_url)s" target="_blank">%(thumb)s</a>' ) def __init__(self, thumbnail_options=None, attrs=None): """ Set up the thumbnail options for this widget. :param thumbnail_options: options used to generate the thumbnail. If no ``size`` is given, it'll be ``(80, 80)``. If not provided at all, default options will be used from the :attr:`~easy_thumbnails.conf.Settings.THUMBNAIL_WIDGET_OPTIONS` setting. """ thumbnail_options = ( thumbnail_options or settings.THUMBNAIL_WIDGET_OPTIONS) thumbnail_options = thumbnail_options.copy() if 'size' not in thumbnail_options: thumbnail_options['size'] = (80, 80) self.thumbnail_options = thumbnail_options super().__init__(attrs) def thumbnail_id(self, name): return '%s_thumb_id' % name def get_thumbnail(self, value): thumbnailer = get_thumbnailer(value, value.name) thumbnailer.source_storage = value.storage if hasattr(value, 'thumbnail_storage'): thumbnailer.thumbnail_storage = value.thumbnail_storage return thumbnailer.get_thumbnail(self.thumbnail_options) def render(self, name, value, attrs=None, renderer=None): output = super().render(name, value, attrs, renderer) if not value or not hasattr(value, 'storage'): return output thumb = self.get_thumbnail(value) substitution = { 'template': output, 'thumb': thumb.tag(id=self.thumbnail_id(name)), 'source_url': value.storage.url(value.name), } return mark_safe(self.template_with_thumbnail % substitution)
ImageClearableFileInput
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/types.py
{ "start": 39520, "end": 44449 }
class ____(st.SearchStrategy): def __init__(self, yields, returns): super().__init__() assert isinstance(yields, st.SearchStrategy) assert isinstance(returns, st.SearchStrategy) self.yields = yields self.returns = returns def __repr__(self) -> str: return f"<generators yields={self.yields!r} returns={self.returns!r}>" def do_draw(self, data): elements = conjecture_utils_many(data, min_size=0, max_size=100, average_size=5) while elements.more(): yield data.draw(self.yields) return data.draw(self.returns) @register(typing.Generator, GeneratorStrategy(st.none(), st.none())) def resolve_Generator(thing): yields, _, returns = thing.__args__ return GeneratorStrategy(st.from_type(yields), st.from_type(returns)) @register(typing.Callable, st.functions()) def resolve_Callable(thing): # Generated functions either accept no arguments, or arbitrary arguments. # This is looser than ideal, but anything tighter would generally break # use of keyword arguments and we'd rather not force positional-only. if not thing.__args__: # pragma: no cover # varies by minor version return st.functions() *args_types, return_type = thing.__args__ # Note that a list can only appear in __args__ under Python 3.9 with the # collections.abc version; see https://bugs.python.org/issue42195 if len(args_types) == 1 and isinstance(args_types[0], list): args_types = tuple(args_types[0]) # pragma: no cover pep612 = ConcatenateTypes + ParamSpecTypes for arg in args_types: # awkward dance because you can't use Concatenate in isistance or issubclass if getattr(arg, "__origin__", arg) in pep612 or type(arg) in pep612: raise InvalidArgument( "Hypothesis can't yet construct a strategy for instances of a " f"Callable type parametrized by {arg!r}. Consider using an " "explicit strategy, or opening an issue." ) if get_origin(return_type) in TypeGuardTypes: raise InvalidArgument( "Hypothesis cannot yet construct a strategy for callables which " f"are PEP-647 TypeGuards or PEP-742 TypeIs (got {return_type!r}). " "Consider using an explicit strategy, or opening an issue." ) if get_origin(thing) is collections.abc.Callable and return_type is None: return_type = type(None) return st.functions( like=(lambda *a, **k: None) if args_types else (lambda: None), returns=st.from_type(return_type), ) @register(typing.TypeVar) @register("TypeVar", module=typing_extensions) def resolve_TypeVar(thing): type_var_key = f"typevar={thing!r}" bound = getattr(thing, "__bound__", None) default = getattr(thing, "__default__", NoDefaults[0]) original_strategies = [] def resolve_strategies(typ): if isinstance(typ, typing.ForwardRef): # TODO: on Python 3.13 and later, we should work out what type_params # could be part of this type, and pass them in here. typ = _try_import_forward_ref(thing, typ, type_params=()) strat = unwrap_strategies(st.from_type(typ)) if not isinstance(strat, OneOfStrategy): original_strategies.append(strat) else: original_strategies.extend(strat.original_strategies) if bound is not None: resolve_strategies(bound) if default not in NoDefaults: # pragma: no cover # Coverage requires 3.13 or `typing_extensions` package. resolve_strategies(default) if original_strategies: # The bound / default was a union, or we resolved it as a union of subtypes, # so we need to unpack the strategy to ensure consistency across uses. # This incantation runs a sampled_from over the strategies inferred for # each part of the union, wraps that in shared so that we only generate # from one type per testcase, and flatmaps that back to instances. return st.shared( st.sampled_from(original_strategies), key=type_var_key ).flatmap(lambda s: s) builtin_scalar_types = [type(None), bool, int, float, str, bytes] return st.shared( st.sampled_from( # Constraints may be None or () on various Python versions. getattr(thing, "__constraints__", None) or builtin_scalar_types, ), key=type_var_key, ).flatmap(st.from_type) if sys.version_info[:2] >= (3, 14): # memoryview is newly generic in 3.14. see # https://github.com/python/cpython/issues/126012 # and https://docs.python.org/3/library/stdtypes.html#memoryview @register(memoryview, st.binary().map(memoryview)) def resolve_memoryview(thing): return st.from_type(thing.__args__[0]).map(memoryview)
GeneratorStrategy
python
jazzband__django-redis
django_redis/pool.py
{ "start": 4503, "end": 7172 }
class ____(ConnectionFactory): def __init__(self, options): # allow overriding the default SentinelConnectionPool class options.setdefault( "CONNECTION_POOL_CLASS", "redis.sentinel.SentinelConnectionPool", ) super().__init__(options) sentinels = options.get("SENTINELS") if not sentinels: error_message = "SENTINELS must be provided as a list of (host, port)." raise ImproperlyConfigured(error_message) # provide the connection pool kwargs to the sentinel in case it # needs to use the socket options for the sentinels themselves connection_kwargs = self.make_connection_params(None) connection_kwargs.pop("url") connection_kwargs.update(self.pool_cls_kwargs) self._sentinel = Sentinel( sentinels, sentinel_kwargs=options.get("SENTINEL_KWARGS"), **connection_kwargs, ) def get_connection_pool(self, params): """ Given a connection parameters, return a new sentinel connection pool for them. """ url = urlparse(params["url"]) # explicitly set service_name and sentinel_manager for the # SentinelConnectionPool constructor since will be called by from_url cp_params = dict(params) # convert "is_master" to a boolean if set on the URL, otherwise if not # provided it defaults to True. query_params = parse_qs(url.query) is_master = query_params.get("is_master") if is_master: cp_params["is_master"] = to_bool(is_master[0]) # then remove the "is_master" query string from the URL # so it doesn't interfere with the SentinelConnectionPool constructor if "is_master" in query_params: del query_params["is_master"] new_query = urlencode(query_params, doseq=True) new_url = urlunparse( (url.scheme, url.netloc, url.path, url.params, new_query, url.fragment), ) cp_params.update( service_name=url.hostname, sentinel_manager=self._sentinel, url=new_url, ) return super().get_connection_pool(cp_params) def get_connection_factory(path=None, options=None): if path is None: path = getattr( settings, "DJANGO_REDIS_CONNECTION_FACTORY", "django_redis.pool.ConnectionFactory", ) opt_conn_factory = options.get("CONNECTION_FACTORY") if opt_conn_factory: path = opt_conn_factory cls = import_string(path) return cls(options or {})
SentinelConnectionFactory
python
getsentry__sentry
src/sentry/hybridcloud/rpc/sig.py
{ "start": 656, "end": 819 }
class ____(_SerializableFunctionSignatureException): """Indicate that a serialized function call received an invalid value."""
SerializableFunctionValueException
python
ansible__ansible
test/units/module_utils/facts/test_utils.py
{ "start": 785, "end": 1427 }
class ____(unittest.TestCase): def test(self): mount_info = utils.get_mount_size('/dev/null/not/a/real/mountpoint') self.assertIsInstance(mount_info, dict) def test_proc(self): mount_info = utils.get_mount_size('/proc') self.assertIsInstance(mount_info, dict) @patch('ansible.module_utils.facts.utils.os.statvfs', side_effect=OSError('intentionally induced os error')) def test_oserror_on_statvfs(self, mock_statvfs): mount_info = utils.get_mount_size('/dev/null/doesnt/matter') self.assertIsInstance(mount_info, dict) self.assertDictEqual(mount_info, {})
TestGetMountSize