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
scikit-image__scikit-image
benchmarks/benchmark_registration.py
{ "start": 622, "end": 1121 }
class ____: """Benchmark for registration routines in scikit-image.""" param_names = ["dtype"] params = [(np.float32, np.float64)] def setup(self, *args): I0, I1, _ = data.stereo_motorcycle() self.I0 = rgb2gray(I0) self.I1 = rgb2gray(I1) def time_tvl1(self, dtype): registration.optical_flow_tvl1(self.I0, self.I1, dtype=dtype) def time_ilk(self, dtype): registration.optical_flow_ilk(self.I0, self.I1, dtype=dtype)
RegistrationSuite
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 272649, "end": 273155 }
class ____(sgqlc.types.Input): """Ways in which lists of releases can be ordered upon return.""" __schema__ = github_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field(sgqlc.types.non_null(ReleaseOrderField), graphql_name="field") """The field in which to order releases by.""" direction = sgqlc.types.Field(sgqlc.types.non_null(OrderDirection), graphql_name="direction") """The direction in which to order releases by the specified field."""
ReleaseOrder
python
ray-project__ray
rllib/env/wrappers/atari_wrappers.py
{ "start": 1464, "end": 1707 }
class ____(gym.RewardWrapper): def __init__(self, env): gym.RewardWrapper.__init__(self, env) def reward(self, reward): """Bin reward to {+1, 0, -1} by its sign.""" return np.sign(reward) @PublicAPI
ClipRewardEnv
python
airbytehq__airbyte
airbyte-integrations/connectors/source-salesforce/source_salesforce/rate_limiting.py
{ "start": 2894, "end": 13466 }
class ____(ErrorHandler): def __init__(self, stream_name: str = "<unknown stream>", sobject_options: Optional[Mapping[str, Any]] = None) -> None: self._stream_name = stream_name self._sobject_options: Mapping[str, Any] = sobject_options or {} @property def max_retries(self) -> Optional[int]: return 5 @property def max_time(self) -> Optional[int]: return 120 def interpret_response(self, response: Optional[Union[requests.Response, Exception]]) -> ErrorResolution: if isinstance(response, TRANSIENT_EXCEPTIONS): return ErrorResolution( ResponseAction.RETRY, FailureType.transient_error, f"Error of type {type(response)} is considered transient. Try again later. (full error message is {response})", ) elif isinstance(response, requests.Response): if response.ok: if self._is_bulk_job_status_check(response) and response.json().get("state") == "Failed": # Important: this means that there are no retry for Salesforce jobs that once they fail. If we want to enable retry, # we will need to be more granular by reading the `errorMessage` raise BulkNotSupportedException(f"Query job with id: `{response.json().get('id')}` failed") return ErrorResolution(ResponseAction.IGNORE, None, None) if not (400 <= response.status_code < 500) or response.status_code in _RETRYABLE_400_STATUS_CODES: return ErrorResolution( ResponseAction.RETRY, FailureType.transient_error, f"Response with status code {response.status_code} is considered transient. Try again later. (full error message is {response.content})", ) error_code, error_message = self._extract_error_code_and_message(response) if self._is_login_request(response): return ErrorResolution( ResponseAction.FAIL, FailureType.config_error, _AUTHENTICATION_ERROR_MESSAGE_MAPPING.get(error_message) if error_message in _AUTHENTICATION_ERROR_MESSAGE_MAPPING else f"An error occurred: {response.content.decode()}", ) if self._is_bulk_job_creation(response) and response.status_code in [codes.FORBIDDEN, codes.BAD_REQUEST]: return self._handle_bulk_job_creation_endpoint_specific_errors(response, error_code, error_message) if response.status_code == codes.too_many_requests or ( response.status_code == codes.forbidden and error_code == "REQUEST_LIMIT_EXCEEDED" ): # It is unclear as to why we don't retry on those. The rate limit window is 24 hours but it is rolling so we could end up being able to sync more records before 24 hours. Note that there is also a limit of concurrent long running requests which can fall in this bucket. return ErrorResolution( ResponseAction.FAIL, FailureType.transient_error, f"Request limit reached with HTTP status {response.status_code}. body: {response.text}", ) if ( "We can't complete the action because enabled transaction security policies took too long to complete." in error_message and error_code == "TXN_SECURITY_METERING_ERROR" ): return ErrorResolution( ResponseAction.FAIL, FailureType.config_error, 'A transient authentication error occurred. To prevent future syncs from failing, assign the "Exempt from Transaction Security" user permission to the authenticated user.', ) return ErrorResolution( ResponseAction.FAIL, FailureType.system_error, f"An error occurred: {response.content.decode()}", ) @staticmethod def _is_bulk_job_status_check(response: requests.Response) -> bool: """Regular string ensures format used only for job status: /services/data/vXX.X/jobs/query/<queryJobId>, see https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/query_get_one_job.htm""" return response.request.method == "GET" and bool(re.compile(r"/services/data/v\d{2}\.\d/jobs/query/[^/]+$").search(response.url)) @staticmethod def _is_bulk_job_creation(response: requests.Response) -> bool: # TODO comment on PR: I don't like that because it duplicates the format of the URL but with a test at least we should be fine to valide once it changes return response.request.method == "POST" and bool(re.compile(r"services/data/v\d{2}\.\d/jobs/query/?$").search(response.url)) def _handle_bulk_job_creation_endpoint_specific_errors( self, response: requests.Response, error_code: Optional[str], error_message: str ) -> ErrorResolution: # A part of streams can't be used by BULK API. Every API version can have a custom list of # these sobjects. Another part of them can be generated dynamically. That's why we can't track # them preliminarily and there is only one way is to except error with necessary messages about # their limitations. Now we know about 3 different reasons of similar errors: # 1) some SaleForce sobjects(streams) is not supported by the BULK API simply (as is). # 2) Access to a sobject(stream) is not available # 3) sobject is not queryable. It means this sobject can't be called directly. # We can call it as part of response from another sobject only. E.g.: # initial query: "Select Id, Subject from ActivityHistory" -> error # updated query: "Select Name, (Select Subject,ActivityType from ActivityHistories) from Contact" # The second variant forces customisation for every case (ActivityHistory, ActivityHistories etc). # And the main problem is these subqueries doesn't support CSV response format. if error_message == "Selecting compound data not supported in Bulk Query" or ( error_code == "INVALIDENTITY" and "is not supported by the Bulk API" in error_message ): logger.error( f"Cannot receive data for stream '{self._stream_name}' using BULK API, " f"sobject options: {self._sobject_options}, error message: '{error_message}'" ) raise BulkNotSupportedException() elif response.status_code == codes.BAD_REQUEST: if error_message.endswith("does not support query"): logger.error( f"The stream '{self._stream_name}' is not queryable, " f"sobject options: {self._sobject_options}, error message: '{error_message}'" ) raise BulkNotSupportedException() elif error_code == "API_ERROR" and error_message.startswith("Implementation restriction"): message = f"Unable to sync '{self._stream_name}'. To prevent future syncs from failing, ensure the authenticated user has \"View all Data\" permissions." return ErrorResolution(ResponseAction.FAIL, FailureType.config_error, message) elif error_code == "LIMIT_EXCEEDED": message = "Your API key for Salesforce has reached its limit for the 24-hour period. We will resume replication once the limit has elapsed." logger.error(message) raise BulkNotSupportedException() elif response.status_code == codes.FORBIDDEN: if error_code == "REQUEST_LIMIT_EXCEEDED": logger.error( f"Cannot receive data for stream '{self._stream_name}' ," f"sobject options: {self._sobject_options}, Error message: '{error_message}'" ) raise BulkNotSupportedException() else: logger.error( f"Cannot receive data for stream '{self._stream_name}' ," f"sobject options: {self._sobject_options}, error message: '{error_message}'" ) raise BulkNotSupportedException() return ErrorResolution(ResponseAction.FAIL, FailureType.system_error, error_message) @staticmethod def _extract_error_code_and_message(response: requests.Response) -> tuple[Optional[str], str]: try: error_data = response.json()[0] return error_data.get("errorCode"), error_data.get("message", "") except exceptions.JSONDecodeError: logger.warning(f"The response for `{response.request.url}` is not a JSON but was `{response.content}`") except (IndexError, KeyError): logger.warning( f"The response for `{response.request.url}` was expected to be a list with at least one element but was `{response.content}`" ) if "error" in response.json() and "error_description" in response.json(): return response.json()["error"], response.json()["error_description"] return None, f"Unknown error on response `{response.content}`" def _is_login_request(self, response: requests.Response) -> bool: return "salesforce.com/services/oauth2/token" in response.request.url def default_backoff_handler(max_tries: int, retry_on=None): if not retry_on: retry_on = TRANSIENT_EXCEPTIONS backoff_method = backoff.constant backoff_params = {"interval": 5} def log_retry_attempt(details): _, exc, _ = sys.exc_info() logger.info(str(exc)) logger.info(f"Caught retryable error after {details['tries']} tries. Waiting {details['wait']} seconds then retrying...") def should_give_up(exc): give_up = ( SalesforceErrorHandler().interpret_response(exc if exc.response is None else exc.response).response_action != ResponseAction.RETRY ) if give_up: logger.info(f"Giving up for returned HTTP status: {exc.response.status_code}, body: {exc.response.text}") return give_up return backoff.on_exception( backoff_method, retry_on, jitter=None, on_backoff=log_retry_attempt, giveup=should_give_up, max_tries=max_tries, **backoff_params, )
SalesforceErrorHandler
python
rapidsai__cudf
python/cudf_polars/cudf_polars/experimental/repartition.py
{ "start": 700, "end": 2307 }
class ____(IR): """ Repartition a DataFrame. Notes ----- Repartitioning means that we are not modifying any data, nor are we reordering or shuffling rows. We are only changing the overall partition count. For now, we only support an N -> [1...N] repartitioning (inclusive). The output partition count is tracked separately using PartitionInfo. """ __slots__ = () _non_child = ("schema",) def __init__(self, schema: Schema, df: IR): self.schema = schema self._non_child_args = () self.children = (df,) @generate_ir_tasks.register(Repartition) def _( ir: Repartition, partition_info: MutableMapping[IR, PartitionInfo], context: IRExecutionContext, ) -> MutableMapping[Any, Any]: # Repartition an IR node. # Only supports rapartitioning to fewer (for now). (child,) = ir.children count_in = partition_info[child].count count_out = partition_info[ir].count if count_out > count_in: # pragma: no cover raise NotImplementedError( f"Repartition {count_in} -> {count_out} not supported." ) key_name = get_key_name(ir) n, remainder = divmod(count_in, count_out) # Spread remainder evenly over the partitions. offsets = [0, *itertools.accumulate(n + (i < remainder) for i in range(count_out))] child_keys = tuple(partition_info[child].keys(child)) return { (key_name, i): ( partial(_concat, context=context), *child_keys[offsets[i] : offsets[i + 1]], ) for i in range(count_out) }
Repartition
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 100935, "end": 102438 }
class ____: @pytest.fixture(scope='function') def rng(self): return np.random.default_rng(1234) @pytest.mark.parametrize("dist", [stats.gumbel_r, stats.gumbel_l]) @pytest.mark.parametrize("loc_rvs", [-1, 0, 1]) @pytest.mark.parametrize("scale_rvs", [.1, 1, 5]) @pytest.mark.parametrize('fix_loc, fix_scale', ([True, False], [False, True])) def test_fit_comp_optimizer(self, dist, loc_rvs, scale_rvs, fix_loc, fix_scale, rng): data = dist.rvs(size=100, loc=loc_rvs, scale=scale_rvs, random_state=rng) kwds = dict() # the fixed location and scales are arbitrarily modified to not be # close to the true value. if fix_loc: kwds['floc'] = loc_rvs * 2 if fix_scale: kwds['fscale'] = scale_rvs * 2 # test that the gumbel_* fit method is better than super method _assert_less_or_close_loglike(dist, data, **kwds) @pytest.mark.parametrize("dist, sgn", [(stats.gumbel_r, 1), (stats.gumbel_l, -1)]) def test_fit(self, dist, sgn): z = sgn*np.array([3, 3, 3, 3, 3, 3, 3, 3.00000001]) loc, scale = dist.fit(z) # The expected values were computed with mpmath with 60 digits # of precision. assert_allclose(loc, sgn*3.0000000001667906) assert_allclose(scale, 1.2495222465145514e-09, rtol=1e-6)
TestGumbel_r_l
python
tensorflow__tensorflow
tensorflow/python/compiler/tensorrt/test/base_test.py
{ "start": 2630, "end": 4742 }
class ____(trt_test.TfTrtIntegrationTestBase): def GraphFn(self, inp): """Create a graph containing multiple segment.""" dtype = inp.dtype conv_filter = constant_op.constant( [[[[1., 0.5, 4., 6., 0.5, 1.], [1., 0.5, 1., 1., 0.5, 1.]]]], name="weights", dtype=dtype) conv = nn.conv2d( input=inp, filter=conv_filter, strides=[1, 2, 2, 1], padding="SAME", name="conv") c1 = constant_op.constant( np.random.randn(12, 12, 6), dtype=dtype, name="c1") p = math_ops.mul(conv, c1, name="mul") c2 = constant_op.constant( np.random.randn(12, 12, 6), dtype=dtype, name="c2") q = math_ops.div(conv, c2, name="div") edge = self.trt_incompatible_op(q, name="incompatible") one = constant_op.constant(1, name="one", dtype=dtype) edge = math_ops.sub(one, edge, name="one_sub") edge = math_ops.div(edge, edge, name="div1") r = math_ops.add(edge, edge, name="add") p = math_ops.sub(p, edge, name="sub") q = math_ops.mul(q, edge, name="mul1") s = math_ops.add(p, q, name="add1") s = math_ops.sub(s, r, name="sub1") return array_ops.squeeze(s, name="output_0") def GetParams(self): # TODO(aaroey): test graph with different dtypes. return self.BuildParams(self.GraphFn, dtypes.float32, [[100, 24, 24, 2]], [[100, 12, 12, 6]]) def ExpectedEnginesToBuild(self, run_params): """Return the expected engines to build.""" return { "TRTEngineOp_000": [ "add", "add1", "c1", "div1", "mul", "mul1", "sub", "sub1", "one", "one_sub" ], "TRTEngineOp_001": ["c2", "conv", "div", "weights"] } def setUp(self): super().setUp() # Disable layout optimizer, since it will convert BiasAdd with NHWC # format to NCHW format under four dimensional input. self.DisableNonTrtOptimizers() def ShouldRunTest(self, run_params): return ( trt_utils.is_linked_tensorrt_version_greater_equal(8), "Test is non-hermetic with TensorRT 7", )
SimpleMultiEnginesTest
python
numba__llvmlite
llvmlite/binding/orcjit.py
{ "start": 6749, "end": 8036 }
class ____(ffi.ObjectRef): """ A resource tracker is created for each loaded JIT library and keeps the module alive. OrcJIT supports unloading libraries that are no longer used. This resource tracker should be stored in any object that reference functions or constants for a JITted library. When all references to the resource tracker are dropped, this will trigger LLVM to unload the library and destroy any functions. Failure to keep resource trackers while calling a function or accessing a symbol can result in crashes or memory corruption. LLVM internally tracks references between different libraries, so only "leaf" libraries need to be tracked. """ def __init__(self, ptr, name, addresses): self.__addresses = addresses self.__name = name ffi.ObjectRef.__init__(self, ptr) def __getitem__(self, item): """ Get the address of an exported symbol as an integer """ return self.__addresses[item] @property def name(self): return self.__name def _dispose(self): with ffi.OutputString() as outerr: if self._capi.LLVMPY_LLJIT_Dylib_Tracker_Dispose(self, outerr): raise RuntimeError(str(outerr))
ResourceTracker
python
astropy__astropy
astropy/utils/masked/tests/test_functions.py
{ "start": 19129, "end": 19218 }
class ____(TestMaskedArrayBroadcast, LongitudeSetup): pass
TestMaskedLongitudeBroadcast
python
pypa__warehouse
warehouse/static.py
{ "start": 170, "end": 2989 }
class ____: def __init__(self): self.manifests = {} def __call__(self, path, url): manifest_path, manifest = self.get_manifest(url) if manifest_path is not None: manifest_dir = os.path.dirname(manifest_path) if os.path.commonpath([manifest_path, path]) == manifest_dir: if os.path.relpath(path, manifest_dir) in manifest: return True return False def add_manifest(self, manifest_path, prefix): self.manifests[prefix] = resolver.resolve(manifest_path).abspath() def get_manifest(self, url): for prefix, manifest_path in self.manifests.items(): if url.startswith(prefix): manifest_files = set() with open(manifest_path, encoding="utf8") as fp: data = json.load(fp) manifest_files.update(data.values()) return manifest_path, manifest_files return None, None def _create_whitenoise(app, config): wh_config = config.registry.settings.get("whitenoise", {}).copy() if wh_config: # Create our Manifest immutable file checker. manifest = ImmutableManifestFiles() for manifest_spec, prefix in config.registry.settings.get( "whitenoise.manifests", [] ): manifest.add_manifest(manifest_spec, prefix) # Wrap our WSGI application with WhiteNoise app = WhiteNoise(app, **wh_config, immutable_file_test=manifest) # Go through and add all of the files we were meant to add. for path, kwargs in config.registry.settings.get("whitenoise.files", []): app.add_files(resolver.resolve(path).abspath(), **kwargs) return app def whitenoise_serve_static(config, **kwargs): def register(): config.registry.settings["whitenoise"] = kwargs config.action(("whitenoise", "create instance"), register) def whitenoise_add_files(config, path, prefix=None): def add_files(): config.registry.settings.setdefault("whitenoise.files", []).append( (path, {"prefix": prefix}) ) config.action(("whitenoise", "add files", path, prefix), add_files) def whitenoise_add_manifest(config, manifest, prefix): def add_manifest(): config.registry.settings.setdefault("whitenoise.manifests", []).append( (manifest, prefix) ) config.action(("whitenoise", "add manifest", manifest), add_manifest) def includeme(config): config.add_wsgi_middleware(_create_whitenoise, config) config.add_directive("whitenoise_serve_static", whitenoise_serve_static) config.add_directive("whitenoise_add_files", whitenoise_add_files) config.add_directive("whitenoise_add_manifest", whitenoise_add_manifest)
ImmutableManifestFiles
python
google__jax
jax/_src/pallas/mosaic_gpu/primitives.py
{ "start": 80918, "end": 81137 }
class ____: shape: tuple[int, ...] dtype: jnp.dtype layout: SomeLayout inline_mgpu_p = jax_core.Primitive("inline_mgpu_p") inline_mgpu_p.multiple_results = True @dataclasses.dataclass(frozen=True)
ShapeDtypeStruct
python
apache__airflow
helm-tests/tests/helm_tests/airflow_core/test_triggerer.py
{ "start": 29385, "end": 29524 }
class ____(LogGroomerTestBase): """Triggerer log groomer.""" obj_name = "triggerer" folder = "triggerer"
TestTriggererLogGroomer
python
getsentry__sentry
tests/sentry/replays/endpoints/test_organization_replay_details.py
{ "start": 302, "end": 8304 }
class ____(APITestCase, ReplaysSnubaTestCase): endpoint = "sentry-api-0-organization-replay-details" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.replay_id = uuid4().hex self.url = reverse(self.endpoint, args=(self.organization.slug, self.replay_id)) def test_feature_flag_disabled(self) -> None: response = self.client.get(self.url) assert response.status_code == 404 def test_no_replay_found(self) -> None: with self.feature(REPLAYS_FEATURES): response = self.client.get(self.url) assert response.status_code == 404 def test_no_projects(self) -> None: with self.feature(REPLAYS_FEATURES): response = self.client.get(self.url) assert response.status_code == 404 def test_project_no_permissions(self) -> None: seq1_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=10) seq2_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=5) self.store_replays(mock_replay(seq1_timestamp, self.project.id, self.replay_id)) self.store_replays(mock_replay(seq2_timestamp, self.project.id, self.replay_id)) self.organization.flags.allow_joinleave = False self.organization.save() user = self.create_user(is_staff=False, is_superuser=False) member2 = self.create_member(organization=self.organization, user=user, role="member") with self.feature(REPLAYS_FEATURES): response = self.client.get(self.url) assert response.status_code == 200 self.login_as(member2) response = self.client.get(self.url) assert response.status_code == 404 def test_get_one_replay(self) -> None: """Test only one replay returned.""" replay1_id = self.replay_id replay2_id = uuid4().hex seq1_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=10) seq2_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=5) self.store_replays(mock_replay(seq1_timestamp, self.project.id, replay1_id)) self.store_replays(mock_replay(seq2_timestamp, self.project.id, replay1_id)) self.store_replays(mock_replay(seq1_timestamp, self.project.id, replay2_id)) self.store_replays(mock_replay(seq2_timestamp, self.project.id, replay2_id)) with self.feature(REPLAYS_FEATURES): # Replay 1. response = self.client.get(self.url) assert response.status_code == 200 response_data = response.json() assert "data" in response_data assert response_data["data"]["id"] == replay1_id # Replay 2. response = self.client.get( reverse(self.endpoint, args=(self.organization.slug, replay2_id)) ) assert response.status_code == 200 response_data = response.json() assert "data" in response_data assert response_data["data"]["id"] == replay2_id def test_get_replay_schema(self) -> None: """Test replay schema is well-formed.""" replay1_id = self.replay_id replay2_id = uuid4().hex seq1_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=25) seq2_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=7) seq3_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=4) trace_id_1 = uuid4().hex trace_id_2 = uuid4().hex # Assert values from this non-returned replay do not pollute the returned # replay. self.store_replays(mock_replay(seq1_timestamp, self.project.id, replay2_id)) self.store_replays(mock_replay(seq3_timestamp, self.project.id, replay2_id)) self.store_replays( mock_replay( seq1_timestamp, self.project.id, replay1_id, trace_ids=[trace_id_1], urls=["http://localhost:3000/"], ) ) self.store_replays( self.mock_event_links( seq1_timestamp, self.project.id, "error", replay1_id, "a3a62ef6ac86415b83c2416fc2f76db1", ) ) self.store_replays( mock_replay( seq2_timestamp, self.project.id, replay1_id, segment_id=1, trace_ids=[trace_id_2], urls=["http://www.sentry.io/"], error_ids=[], ) ) self.store_replays( mock_replay( seq3_timestamp, self.project.id, replay1_id, segment_id=2, trace_ids=[trace_id_2], urls=["http://localhost:3000/"], error_ids=[], ) ) with self.feature(REPLAYS_FEATURES): response = self.client.get(self.url) assert response.status_code == 200 response_data = response.json() assert "data" in response_data expected_response = mock_expected_response( self.project.id, replay1_id, seq1_timestamp, seq3_timestamp, trace_ids=[ trace_id_1, trace_id_2, ], urls=[ "http://localhost:3000/", "http://www.sentry.io/", "http://localhost:3000/", ], count_segments=3, activity=4, count_errors=1, ) assert_expected_response(response_data["data"], expected_response) def test_get_replay_varying_projects(self) -> None: """Test replay with varying project-ids returns its whole self.""" project2 = self.create_project() replay1_id = self.replay_id seq1_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=25) seq2_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=7) seq3_timestamp = datetime.datetime.now() - datetime.timedelta(seconds=4) self.store_replays(mock_replay(seq1_timestamp, self.project.id, replay1_id)) self.store_replays(mock_replay(seq2_timestamp, project2.id, replay1_id, segment_id=1)) self.store_replays(mock_replay(seq3_timestamp, project2.id, replay1_id, segment_id=2)) self.store_replays( self.mock_event_links( seq1_timestamp, self.project.id, "error", replay1_id, "a3a62ef6ac86415b83c2416fc2f76db1", ) ) self.store_replays( self.mock_event_links( seq1_timestamp, project2.id, "error", replay1_id, "e7052fca6e2e406b9dc2d6917932a4c9", ) ) with self.feature(REPLAYS_FEATURES): response = self.client.get(self.url) assert response.status_code == 200 response_data = response.json() assert "data" in response_data expected_response = mock_expected_response( self.project.id, replay1_id, seq1_timestamp, seq3_timestamp, count_segments=3, activity=5, error_ids=[ "a3a62ef6ac86415b83c2416fc2f76db1", "e7052fca6e2e406b9dc2d6917932a4c9", ], # Assert two errors returned even though one was on a different # project. count_errors=2, ) assert_expected_response(response_data["data"], expected_response)
OrganizationReplayDetailsTest
python
huggingface__transformers
src/transformers/models/rembert/modeling_rembert.py
{ "start": 21882, "end": 27438 }
class ____(RemBertPreTrainedModel): def __init__(self, config, add_pooling_layer=True): r""" add_pooling_layer (bool, *optional*, defaults to `True`): Whether to add a pooling layer """ super().__init__(config) self.config = config self.embeddings = RemBertEmbeddings(config) self.encoder = RemBertEncoder(config) self.pooler = RemBertPooler(config) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.LongTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, past_key_values: Optional[Cache] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.Tensor] = None, ) -> Union[tuple, BaseModelOutputWithPoolingAndCrossAttentions]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if self.config.is_decoder: use_cache = use_cache if use_cache is not None else self.config.use_cache else: use_cache = False if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask) input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") batch_size, seq_length = input_shape device = input_ids.device if input_ids is not None else inputs_embeds.device past_key_values_length = 0 if past_key_values is None else past_key_values.get_seq_length() if attention_mask is None: attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device) if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, 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: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape) # 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 self.config.is_decoder and encoder_hidden_states is not None: encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) if 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 = None embedding_output = self.embeddings( input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds, past_key_values_length=past_key_values_length, ) encoder_outputs = self.encoder( embedding_output, attention_mask=extended_attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) sequence_output = encoder_outputs[0] pooled_output = self.pooler(sequence_output) if self.pooler is not None else None if not return_dict: return (sequence_output, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, past_key_values=encoder_outputs.past_key_values, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, cross_attentions=encoder_outputs.cross_attentions, ) @auto_docstring
RemBertModel
python
google__jax
tests/custom_partitioning_sharding_rule_test.py
{ "start": 10603, "end": 22399 }
class ____(jtu.JaxTestCase): def run(self, result=None): with ir.Context() as ctx, ir.Location.unknown(ctx): sdy.register_dialect(ctx) stablehlo.register_dialect(ctx) module = ir.Module.create() with ir.InsertionPoint(module.body): super().run(result) def get_tensor_type(self, shape): return ir.RankedTensorType.get(shape, ir.F32Type.get()) def create_tensor_value(self, shape): return ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type(shape)], attributes=dict(call_target_name=ir.StringAttr.get("dummy_target")) ).result def test_conversion_rule_op_mismatch_in_operands_num(self): opnd0 = self.create_tensor_value((16, 32)) opnd1 = self.create_tensor_value((16, 32)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((16, 32))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo")),) rule = str_to_sdy_sharding_rule("i j-> i j") with self.assertRaisesRegex( ValueError, "Sharding rule has 1 operands, but the operation has 2 operands"): sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) def test_conversion_rule_op_mismatch_in_operands_rank(self): opnd0 = self.create_tensor_value((16, 32)) opnd1 = self.create_tensor_value((16, 32)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((16, 32))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo")),) rule = str_to_sdy_sharding_rule("i j, i j k-> i j") with self.assertRaisesRegex( ValueError, "Sharding rule 1th operand has rank 3, but the operation 1th " "operand has rank 2"): sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) def test_conversion_rule_op_mismatch_in_results_num(self): opnd0 = self.create_tensor_value((16, 32)) opnd1 = self.create_tensor_value((16, 32)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((16, 32))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo")),) rule = str_to_sdy_sharding_rule("i j, i j -> i j, i j") with self.assertRaisesRegex( ValueError, "Sharding rule has 2 results, but the operation has 1 results"): sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) def test_conversion_rule_op_mismatch_in_results_dim(self): opnd0 = self.create_tensor_value((16, 32)) opnd1 = self.create_tensor_value((16, 32)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((16, 32))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo"))) rule = str_to_sdy_sharding_rule("i j, i j -> i j k") with self.assertRaisesRegex( ValueError, "Sharding rule 0th result has rank 3, but the operation 0th " "result has rank 2"): sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) def test_conversion_factor_with_multiple_sizes_use_smallest_size(self): opnd0 = self.create_tensor_value((16, 16)) opnd1 = self.create_tensor_value((16, 32)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((16, 8))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo"))) rule = str_to_sdy_sharding_rule("i j, i j -> i j") mlir_rule = sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) self.assertEqual( str(mlir_rule), "#sdy.op_sharding_rule<([i, j], [i, j])->([i, j]) {i=16, j=8}, custom>") def test_conversion_batching_dim_has_two_sizes(self): opnd0 = self.create_tensor_value((16, 32)) opnd1 = self.create_tensor_value((16, 32)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((16, 64))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo"))) rule = str_to_sdy_sharding_rule("..., ... -> ...") with self.assertRaisesRegex( ValueError, "Batching dimension 0_1 corresponds to two sizes: 32 and 64"): sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,],) def test_conversion_invalid_batching_dim(self): opnd0 = self.create_tensor_value((16, 32)) opnd1 = self.create_tensor_value((16, 32)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((16, 32))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo")),) rule = str_to_sdy_sharding_rule("... i j k, ... i j k -> ... i j k") with self.assertRaisesRegex( ValueError, "Sharding rule 0th operand has rank 3, but the operation 0th operand has rank 2"): sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) def test_conversion_compound_dimension_size_mismatch(self): opnd = self.create_tensor_value((2, 4)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((9,))], operands=[opnd,], attributes=dict(call_target_name=ir.StringAttr.get("foo"))) rule = str_to_sdy_sharding_rule("i j -> (i j)") with self.assertRaisesRegex( ValueError, "0th result actual size 9 doesn't match the size 8 derived from the" " compound factors"): sdy_sharding_rule_to_mlir(rule, [result.operands[0].type], [result.result.type,]) def test_conversion_elementwise_rule_mismatching_ellipsis_rank(self): opnd0 = self.create_tensor_value((16, 32)) opnd1 = self.create_tensor_value((16,)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((16, 32))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo"))) rule = str_to_sdy_sharding_rule("..., ... -> ...") with self.assertRaisesRegex( ValueError, "Ellipsis represents different number of leading dimensions 2 and 1"): sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) def test_conversion_compound_then_individual(self): opnd = self.create_tensor_value((8,)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((2,4))], operands=[opnd,], attributes=dict(call_target_name=ir.StringAttr.get("foo"))) rule = str_to_sdy_sharding_rule("(i j) -> i j") mlir_rule = sdy_sharding_rule_to_mlir(rule, [result.operands[0].type], [result.result.type,]) self.assertEqual( str(mlir_rule), "#sdy.op_sharding_rule<([ij])->([i, j]) {i=2, j=4}, custom>") def test_conversion_elementwise_rule_scalar_instance(self): opnd0 = self.create_tensor_value(()) opnd1 = self.create_tensor_value(()) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type(())], operands=[opnd0, opnd1], attributes=dict(call_target_name=ir.StringAttr.get("foo")),) rule = str_to_sdy_sharding_rule("..., ... -> ...") mlir_rule = sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) self.assertEqual( str(mlir_rule), "#sdy.op_sharding_rule<([], [])->([]), custom>") def test_conversion_elementwise_rule_2D_instance(self): opnd0 = self.create_tensor_value((16, 32)) opnd1 = self.create_tensor_value((16, 32)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((16, 32))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo")),) rule = str_to_sdy_sharding_rule("..., ... -> ...") mlir_rule = sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) self.assertEqual( str(mlir_rule), "#sdy.op_sharding_rule<([i, j], [i, j])->([i, j]) {i=16, j=32}, custom>") def test_conversion_vector_scalar_add_2D_instance(self): opnd0 = self.create_tensor_value((16, 32)) opnd1 = self.create_tensor_value(()) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((16, 32))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo")),) rule = str_to_sdy_sharding_rule("..., -> ...") mlir_rule = sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) self.assertEqual( str(mlir_rule), "#sdy.op_sharding_rule<([i, j], [])->([i, j]) {i=16, j=32}, custom>") def test_conversion_reshape_rule(self): opnd0 = self.create_tensor_value((2, 4)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((8,))], operands=[opnd0,], attributes=dict(call_target_name=ir.StringAttr.get("foo"))) rule = str_to_sdy_sharding_rule("i j -> (i j)") mlir_rule = sdy_sharding_rule_to_mlir(rule, [result.operands[0].type], [result.result.type,]) self.assertEqual( str(mlir_rule), "#sdy.op_sharding_rule<([i, j])->([ij]) {i=2, j=4}, custom>") def test_conversion_contracting_dim_matmul(self): opnd0 = self.create_tensor_value((16, 32)) opnd1 = self.create_tensor_value((32, 8)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((16, 8))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo"))) rule = str_to_sdy_sharding_rule("... contracting_dim, contracting_dim k -> ... k", reduction_factors=("contracting_dim",)) mlir_rule = sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) self.assertEqual( str(mlir_rule), "#sdy.op_sharding_rule<([i, j], [j, k])->([i, k]) {i=16, j=32, k=8} reduction={j}, custom>") def test_conversion_multiple_batching_groups(self): opnd0 = self.create_tensor_value((4, 5, 16, 32)) opnd1 = self.create_tensor_value((6, 7, 8, 32, 16)) result = ir.Operation.create( "stablehlo.custom_call", results=[self.get_tensor_type((4, 5, 32, 16))], operands=[opnd0, opnd1,], attributes=dict(call_target_name=ir.StringAttr.get("foo"))) rule = str_to_sdy_sharding_rule("... j i, ...1 i j -> ...i j") mlir_rule = sdy_sharding_rule_to_mlir(rule, [result.operands[0].type, result.operands[1].type], [result.result.type,]) self.assertEqual( str(mlir_rule), "#sdy.op_sharding_rule<([i, j, k, l], [m, n, o, l, k])->([i, j, l, k]) {i=4, j=5, k=16, l=32, m=6, n=7, o=8}, custom>") if __name__ == "__main__": absltest.main(testLoader=jtu.JaxTestLoader())
SdyShardingRuleConversionTest
python
pypa__warehouse
tests/unit/admin/views/test_organizations.py
{ "start": 62273, "end": 66315 }
class ____: @pytest.mark.usefixtures("_enable_organizations") def test_set_total_size_limit_with_integer(self, db_request): organization = OrganizationFactory.create(name="foo") db_request.route_path = pretend.call_recorder( lambda a, organization_id: "/admin/organizations/1/" ) db_request.session = pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None) ) db_request.matchdict["organization_id"] = organization.id db_request.POST = MultiDict({"total_size_limit": "150"}) result = views.set_total_size_limit(db_request) assert db_request.session.flash.calls == [ pretend.call("Total size limit set to 150.0GiB", queue="success") ] assert result.status_code == 303 assert result.location == "/admin/organizations/1/" assert organization.total_size_limit == 150 * views.ONE_GIB @pytest.mark.usefixtures("_enable_organizations") def test_set_total_size_limit_with_none(self, db_request): organization = OrganizationFactory.create(name="foo") organization.total_size_limit = 150 * views.ONE_GIB db_request.route_path = pretend.call_recorder( lambda a, organization_id: "/admin/organizations/1/" ) db_request.session = pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None) ) db_request.matchdict["organization_id"] = organization.id db_request.POST = MultiDict({"total_size_limit": ""}) result = views.set_total_size_limit(db_request) assert db_request.session.flash.calls == [ pretend.call("Total size limit set to (default)", queue="success") ] assert result.status_code == 303 assert result.location == "/admin/organizations/1/" assert organization.total_size_limit is None @pytest.mark.usefixtures("_enable_organizations") def test_set_total_size_limit_invalid_value(self, db_request): organization = OrganizationFactory.create(name="foo") db_request.route_path = pretend.call_recorder( lambda a, organization_id: "/admin/organizations/1/" ) db_request.session = pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None) ) db_request.matchdict["organization_id"] = organization.id db_request.POST = MultiDict({"total_size_limit": "not_an_integer"}) result = views.set_total_size_limit(db_request) assert db_request.session.flash.calls == [ pretend.call( "total_size_limit: Total size limit must be a valid integer or empty", queue="error", ) ] assert result.status_code == 303 @pytest.mark.usefixtures("_enable_organizations") def test_set_total_size_limit_not_found(self, db_request): db_request.matchdict["organization_id"] = "00000000-0000-0000-0000-000000000000" with pytest.raises(HTTPNotFound): views.set_total_size_limit(db_request) @pytest.mark.usefixtures("_enable_organizations") def test_set_total_size_limit_below_default(self, db_request): organization = OrganizationFactory.create(name="foo") db_request.route_path = pretend.call_recorder( lambda a, organization_id: "/admin/organizations/1/" ) db_request.session = pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None) ) db_request.matchdict["organization_id"] = organization.id db_request.POST = MultiDict({"total_size_limit": "5"}) # 5 GiB < 10 GiB default result = views.set_total_size_limit(db_request) assert db_request.session.flash.calls == [ pretend.call( "total_size_limit: Total organization size can not be less than " "10.0GiB", queue="error", ) ] assert result.status_code == 303
TestSetTotalSizeLimit
python
doocs__leetcode
lcof2/剑指 Offer II 051. 节点之和最大的路径/Solution.py
{ "start": 192, "end": 638 }
class ____: def maxPathSum(self, root: Optional[TreeNode]) -> int: def dfs(root: Optional[TreeNode]) -> int: if root is None: return 0 left = max(0, dfs(root.left)) right = max(0, dfs(root.right)) nonlocal ans ans = max(ans, root.val + left + right) return root.val + max(left, right) ans = -inf dfs(root) return ans
Solution
python
pypa__pipenv
pipenv/patched/pip/_internal/commands/list.py
{ "start": 1466, "end": 13484 }
class ____(IndexGroupCommand): """ List installed packages, including editables. Packages are listed in a case-insensitive sorted order. """ ignore_require_venv = True usage = """ %prog [options]""" def add_options(self) -> None: self.cmd_opts.add_option( "-o", "--outdated", action="store_true", default=False, help="List outdated packages", ) self.cmd_opts.add_option( "-u", "--uptodate", action="store_true", default=False, help="List uptodate packages", ) self.cmd_opts.add_option( "-e", "--editable", action="store_true", default=False, help="List editable projects.", ) self.cmd_opts.add_option( "-l", "--local", action="store_true", default=False, help=( "If in a virtualenv that has global access, do not list " "globally-installed packages." ), ) self.cmd_opts.add_option( "--user", dest="user", action="store_true", default=False, help="Only output packages installed in user-site.", ) self.cmd_opts.add_option(cmdoptions.list_path()) self.cmd_opts.add_option( "--pre", action="store_true", default=False, help=( "Include pre-release and development versions. By default, " "pip only finds stable versions." ), ) self.cmd_opts.add_option( "--format", action="store", dest="list_format", default="columns", choices=("columns", "freeze", "json"), help=( "Select the output format among: columns (default), freeze, or json. " "The 'freeze' format cannot be used with the --outdated option." ), ) self.cmd_opts.add_option( "--not-required", action="store_true", dest="not_required", help="List packages that are not dependencies of installed packages.", ) self.cmd_opts.add_option( "--exclude-editable", action="store_false", dest="include_editable", help="Exclude editable package from output.", ) self.cmd_opts.add_option( "--include-editable", action="store_true", dest="include_editable", help="Include editable package in output.", default=True, ) self.cmd_opts.add_option(cmdoptions.list_exclude()) index_opts = cmdoptions.make_option_group(cmdoptions.index_group, self.parser) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, self.cmd_opts) def handle_pip_version_check(self, options: Values) -> None: if options.outdated or options.uptodate: super().handle_pip_version_check(options) def _build_package_finder( self, options: Values, session: "PipSession" ) -> "PackageFinder": """ Create a package finder appropriate to this list command. """ # Lazy import the heavy index modules as most list invocations won't need 'em. from pipenv.patched.pip._internal.index.collector import LinkCollector from pipenv.patched.pip._internal.index.package_finder import PackageFinder link_collector = LinkCollector.create(session, options=options) # Pass allow_yanked=False to ignore yanked versions. selection_prefs = SelectionPreferences( allow_yanked=False, allow_all_prereleases=options.pre, ) return PackageFinder.create( link_collector=link_collector, selection_prefs=selection_prefs, ) def run(self, options: Values, args: List[str]) -> int: if options.outdated and options.uptodate: raise CommandError("Options --outdated and --uptodate cannot be combined.") if options.outdated and options.list_format == "freeze": raise CommandError( "List format 'freeze' cannot be used with the --outdated option." ) cmdoptions.check_list_path_option(options) skip = set(stdlib_pkgs) if options.excludes: skip.update(canonicalize_name(n) for n in options.excludes) packages: _ProcessedDists = [ cast("_DistWithLatestInfo", d) for d in get_environment(options.path).iter_installed_distributions( local_only=options.local, user_only=options.user, editables_only=options.editable, include_editables=options.include_editable, skip=skip, ) ] # get_not_required must be called firstly in order to find and # filter out all dependencies correctly. Otherwise a package # can't be identified as requirement because some parent packages # could be filtered out before. if options.not_required: packages = self.get_not_required(packages, options) if options.outdated: packages = self.get_outdated(packages, options) elif options.uptodate: packages = self.get_uptodate(packages, options) self.output_package_listing(packages, options) return SUCCESS def get_outdated( self, packages: "_ProcessedDists", options: Values ) -> "_ProcessedDists": return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version > dist.version ] def get_uptodate( self, packages: "_ProcessedDists", options: Values ) -> "_ProcessedDists": return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version == dist.version ] def get_not_required( self, packages: "_ProcessedDists", options: Values ) -> "_ProcessedDists": dep_keys = { canonicalize_name(dep.name) for dist in packages for dep in (dist.iter_dependencies() or ()) } # Create a set to remove duplicate packages, and cast it to a list # to keep the return type consistent with get_outdated and # get_uptodate return list({pkg for pkg in packages if pkg.canonical_name not in dep_keys}) def iter_packages_latest_infos( self, packages: "_ProcessedDists", options: Values ) -> Generator["_DistWithLatestInfo", None, None]: with self._build_session(options) as session: finder = self._build_package_finder(options, session) def latest_info( dist: "_DistWithLatestInfo", ) -> Optional["_DistWithLatestInfo"]: all_candidates = finder.find_all_candidates(dist.canonical_name) if not options.pre: # Remove prereleases all_candidates = [ candidate for candidate in all_candidates if not candidate.version.is_prerelease ] evaluator = finder.make_candidate_evaluator( project_name=dist.canonical_name, ) best_candidate = evaluator.sort_best_candidate(all_candidates) if best_candidate is None: return None remote_version = best_candidate.version if best_candidate.link.is_wheel: typ = "wheel" else: typ = "sdist" dist.latest_version = remote_version dist.latest_filetype = typ return dist for dist in map(latest_info, packages): if dist is not None: yield dist def output_package_listing( self, packages: "_ProcessedDists", options: Values ) -> None: packages = sorted( packages, key=lambda dist: dist.canonical_name, ) if options.list_format == "columns" and packages: data, header = format_for_columns(packages, options) self.output_package_listing_columns(data, header) elif options.list_format == "freeze": for dist in packages: if options.verbose >= 1: write_output( "%s==%s (%s)", dist.raw_name, dist.version, dist.location ) else: write_output("%s==%s", dist.raw_name, dist.version) elif options.list_format == "json": write_output(format_for_json(packages, options)) def output_package_listing_columns( self, data: List[List[str]], header: List[str] ) -> None: # insert the header first: we need to know the size of column names if len(data) > 0: data.insert(0, header) pkg_strings, sizes = tabulate(data) # Create and add a separator. if len(data) > 0: pkg_strings.insert(1, " ".join("-" * x for x in sizes)) for val in pkg_strings: write_output(val) def format_for_columns( pkgs: "_ProcessedDists", options: Values ) -> Tuple[List[List[str]], List[str]]: """ Convert the package data into something usable by output_package_listing_columns. """ header = ["Package", "Version"] running_outdated = options.outdated if running_outdated: header.extend(["Latest", "Type"]) def wheel_build_tag(dist: BaseDistribution) -> Optional[str]: try: wheel_file = dist.read_text("WHEEL") except FileNotFoundError: return None return Parser().parsestr(wheel_file).get("Build") build_tags = [wheel_build_tag(p) for p in pkgs] has_build_tags = any(build_tags) if has_build_tags: header.append("Build") if options.verbose >= 1: header.append("Location") if options.verbose >= 1: header.append("Installer") has_editables = any(x.editable for x in pkgs) if has_editables: header.append("Editable project location") data = [] for i, proj in enumerate(pkgs): # if we're working on the 'outdated' list, separate out the # latest_version and type row = [proj.raw_name, proj.raw_version] if running_outdated: row.append(str(proj.latest_version)) row.append(proj.latest_filetype) if has_build_tags: row.append(build_tags[i] or "") if has_editables: row.append(proj.editable_project_location or "") if options.verbose >= 1: row.append(proj.location or "") if options.verbose >= 1: row.append(proj.installer) data.append(row) return data, header def format_for_json(packages: "_ProcessedDists", options: Values) -> str: data = [] for dist in packages: info = { "name": dist.raw_name, "version": str(dist.version), } if options.verbose >= 1: info["location"] = dist.location or "" info["installer"] = dist.installer if options.outdated: info["latest_version"] = str(dist.latest_version) info["latest_filetype"] = dist.latest_filetype editable_project_location = dist.editable_project_location if editable_project_location: info["editable_project_location"] = editable_project_location data.append(info) return json.dumps(data)
ListCommand
python
pypa__warehouse
tests/unit/accounts/test_security_policy.py
{ "start": 475, "end": 5603 }
class ____: def test_verify(self): assert verifyClass( ISecurityPolicy, security_policy.BasicAuthSecurityPolicy, ) def test_noops(self): """Basically, anything that isn't `identity()` is a no-op.""" policy = security_policy.BasicAuthSecurityPolicy() with pytest.raises(NotImplementedError): policy.authenticated_userid(pretend.stub()) with pytest.raises(NotImplementedError): policy.permits(pretend.stub(), pretend.stub(), pretend.stub()) # These are no-ops, but they don't raise, used in MultiSecurityPolicy assert policy.forget(pretend.stub()) == [] assert policy.remember(pretend.stub(), pretend.stub()) == [] def test_identity_no_credentials(self, monkeypatch): extract_http_basic_credentials = pretend.call_recorder(lambda request: None) monkeypatch.setattr( security_policy, "extract_http_basic_credentials", extract_http_basic_credentials, ) policy = security_policy.BasicAuthSecurityPolicy() vary_cb = pretend.stub() add_vary_cb = pretend.call_recorder(lambda *v: vary_cb) monkeypatch.setattr(security_policy, "add_vary_callback", add_vary_cb) request = pretend.stub( add_response_callback=pretend.call_recorder(lambda cb: None), matched_route=pretend.stub(name="forklift.legacy.file_upload"), ) assert policy.identity(request) is None assert extract_http_basic_credentials.calls == [pretend.call(request)] assert add_vary_cb.calls == [pretend.call("Authorization")] assert request.add_response_callback.calls == [pretend.call(vary_cb)] def test_identity_credentials_fail(self, monkeypatch): creds = (pretend.stub(), pretend.stub()) extract_http_basic_credentials = pretend.call_recorder(lambda request: creds) monkeypatch.setattr( security_policy, "extract_http_basic_credentials", extract_http_basic_credentials, ) policy = security_policy.BasicAuthSecurityPolicy() vary_cb = pretend.stub() add_vary_cb = pretend.call_recorder(lambda *v: vary_cb) monkeypatch.setattr(security_policy, "add_vary_callback", add_vary_cb) request = pretend.stub( add_response_callback=pretend.call_recorder(lambda cb: None), help_url=lambda _anchor=None: "/help", matched_route=pretend.stub(name="forklift.legacy.file_upload"), ) with pytest.raises(HTTPForbidden): policy.identity(request) assert extract_http_basic_credentials.calls == [pretend.call(request)] assert add_vary_cb.calls == [pretend.call("Authorization")] assert request.add_response_callback.calls == [pretend.call(vary_cb)] @pytest.mark.parametrize( "fake_request", [ pretend.stub( matched_route=None, banned=pretend.stub(by_ip=lambda ip_address: False), remote_addr=REMOTE_ADDR, ), pretend.stub( matched_route=pretend.stub(name="an.invalid.route"), banned=pretend.stub(by_ip=lambda ip_address: False), remote_addr=REMOTE_ADDR, ), ], ) def test_invalid_request_fail(self, monkeypatch, fake_request): creds = (pretend.stub(), pretend.stub()) extract_http_basic_credentials = pretend.call_recorder(lambda request: creds) monkeypatch.setattr( security_policy, "extract_http_basic_credentials", extract_http_basic_credentials, ) policy = security_policy.BasicAuthSecurityPolicy() fake_request.add_response_callback = pretend.call_recorder(lambda cb: None) assert policy.identity(fake_request) is None def test_identity(self, monkeypatch): creds = ("__token__", pretend.stub()) extract_http_basic_credentials = pretend.call_recorder(lambda request: creds) monkeypatch.setattr( security_policy, "extract_http_basic_credentials", extract_http_basic_credentials, ) policy = security_policy.BasicAuthSecurityPolicy() vary_cb = pretend.stub() add_vary_cb = pretend.call_recorder(lambda *v: vary_cb) monkeypatch.setattr(security_policy, "add_vary_callback", add_vary_cb) request = pretend.stub( add_response_callback=pretend.call_recorder(lambda cb: None), help_url=lambda _anchor=None: "/help", matched_route=pretend.stub(name="forklift.legacy.file_upload"), ) assert policy.identity(request) is None assert request.authentication_method == AuthenticationMethod.BASIC_AUTH assert extract_http_basic_credentials.calls == [pretend.call(request)] assert add_vary_cb.calls == [pretend.call("Authorization")] assert request.add_response_callback.calls == [pretend.call(vary_cb)]
TestBasicAuthSecurityPolicy
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/relationships/tutorial001.py
{ "start": 263, "end": 425 }
class ____(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team")
Team
python
huggingface__transformers
src/transformers/models/conditional_detr/modeling_conditional_detr.py
{ "start": 32780, "end": 35878 }
class ____(nn.Module): def __init__(self, config: ConditionalDetrConfig): super().__init__() self.embed_dim = config.d_model self.self_attn = DetrAttention( embed_dim=self.embed_dim, num_heads=config.encoder_attention_heads, dropout=config.attention_dropout, ) 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, object_queries: Optional[torch.Tensor] = None, output_attentions: bool = False, ): """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative values. object_queries (`torch.FloatTensor`, *optional*): Object queries (also called content embeddings), to be added to the hidden states. 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 hidden_states, attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, object_queries=object_queries, 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
ConditionalDetrEncoderLayer
python
getsentry__sentry
tests/sentry/issue_detection/test_slow_db_span_detector.py
{ "start": 651, "end": 6638 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self._settings = get_detection_settings() def find_problems(self, event: dict[str, Any]) -> list[PerformanceProblem]: detector = SlowDBQueryDetector(self._settings, event) run_detector_on_data(detector, event) return list(detector.stored_problems.values()) def test_calls_detect_slow_span(self) -> None: no_slow_span_event = create_event([create_span("db", 499.0)] * 1) slow_not_allowed_op_span_event = create_event([create_span("random", 1001.0, "example")]) slow_span_event = create_event([create_span("db", 1001.0)] * 1) assert self.find_problems(no_slow_span_event) == [] assert self.find_problems(slow_not_allowed_op_span_event) == [] assert self.find_problems(slow_span_event) == [ PerformanceProblem( fingerprint="1-1001-da39a3ee5e6b4b0d3255bfef95601890afd80709", op="db", desc="SELECT count() FROM table WHERE id = %s", type=PerformanceSlowDBQueryGroupType, parent_span_ids=None, cause_span_ids=None, offender_span_ids=["bbbbbbbbbbbbbbbb"], evidence_data={ "op": "db", "parent_span_ids": None, "cause_span_ids": None, "offender_span_ids": ["bbbbbbbbbbbbbbbb"], }, evidence_display=[], ) ] def test_skip_queries_without_select(self) -> None: event = create_event([create_span("db", 100000.0, "DELETE FROM table WHERE id = %s")] * 1) assert self.find_problems(event) == [] def test_calls_slow_span_threshold(self) -> None: http_span_event = create_event( [create_span("http.client", 1001.0, "http://example.com")] * 1 ) db_span_event = create_event([create_span("db.query", 1001.0)] * 1) assert self.find_problems(http_span_event) == [] assert self.find_problems(db_span_event) == [ PerformanceProblem( fingerprint="1-1001-da39a3ee5e6b4b0d3255bfef95601890afd80709", op="db.query", desc="SELECT count() FROM table WHERE id = %s", type=PerformanceSlowDBQueryGroupType, parent_span_ids=[], cause_span_ids=[], offender_span_ids=["bbbbbbbbbbbbbbbb"], evidence_data={ "op": "db.query", "parent_span_ids": [], "cause_span_ids": [], "offender_span_ids": ["bbbbbbbbbbbbbbbb"], }, evidence_display=[], ) ] def test_detects_slow_span_in_solved_n_plus_one_query(self) -> None: n_plus_one_event = get_event("slow-db/solved-n-plus-one-in-django-index-view") assert self.find_problems(n_plus_one_event) == [ PerformanceProblem( fingerprint="1-1001-d02c8b2fd92a2d72011671feda429fa8ce2ac00f", op="db", desc="\n SELECT VERSION(),\n @@sql_mode,\n @@default_storage_engine,\n @@sql_auto_is_null,\n @@lower_case_table_names,\n CONVERT_TZ('2001-01-01 01:00:00', 'UTC', 'UTC') IS NOT NULL\n ", type=PerformanceSlowDBQueryGroupType, parent_span_ids=None, cause_span_ids=None, offender_span_ids=["a05754d3fde2db29"], evidence_data={ "op": "db", "parent_span_ids": None, "cause_span_ids": None, "offender_span_ids": ["a05754d3fde2db29"], }, evidence_display=[], ) ] def test_skips_truncated_queries(self) -> None: slow_span_event_with_truncated_query = create_event( [create_span("db", 1005, "SELECT `product`.`id` FROM `products` ...")] * 1 ) slow_span_event = create_event( [create_span("db", 1005, "SELECT `product`.`id` FROM `products`")] * 1 ) assert self.find_problems(slow_span_event_with_truncated_query) == [] assert self.find_problems(slow_span_event) == [ PerformanceProblem( fingerprint="1-1001-da39a3ee5e6b4b0d3255bfef95601890afd80709", op="db", desc="SELECT `product`.`id` FROM `products`", type=PerformanceSlowDBQueryGroupType, parent_span_ids=[], cause_span_ids=[], offender_span_ids=["bbbbbbbbbbbbbbbb"], evidence_data={ "op": "db", "parent_span_ids": [], "cause_span_ids": [], "offender_span_ids": ["bbbbbbbbbbbbbbbb"], }, evidence_display=[], ) ] def test_respects_project_option(self) -> None: project = self.create_project() slow_span_event = create_event( [create_span("db", 1005, "SELECT `product`.`id` FROM `products`")] * 1 ) slow_span_event["project_id"] = project.id settings = get_detection_settings(project.id) detector = SlowDBQueryDetector(settings, slow_span_event) assert detector.is_creation_allowed_for_project(project) ProjectOption.objects.set_value( project=project, key="sentry:performance_issue_settings", value={"slow_db_queries_detection_enabled": False}, ) settings = get_detection_settings(project.id) detector = SlowDBQueryDetector(settings, slow_span_event) assert not detector.is_creation_allowed_for_project(project)
SlowDBQueryDetectorTest
python
getsentry__sentry
src/sentry/utils/redis.py
{ "start": 3017, "end": 13067 }
class ____: def __init__(self, options_manager: OptionsManager) -> None: self._clusters_bytes: dict[str, RedisCluster[bytes] | StrictRedis[bytes]] = {} self._clusters_str: dict[str, RedisCluster[str] | StrictRedis[str]] = {} self._options_manager = options_manager def _supports(self, config: dict[str, Any]) -> bool: # supports two configurations: # * Explicitly configured with is_redis_cluster. This mode is for real redis-cluster. # * No is_redis_cluster, but only 1 host. This represents a singular node Redis running # in non-cluster mode. return config.get("is_redis_cluster", False) or len(config.get("hosts", [])) == 1 def _cfg(self, key: str) -> dict[str, Any]: # TODO: This would probably be safer with a lock, but I'm not sure # that it's necessary. cfg = self._options_manager.get("redis.clusters", {}).get(key) if cfg is None: raise KeyError(f"Invalid cluster name: {key}") if not self._supports(cfg): raise KeyError("Invalid cluster type, expected redis cluster") return cfg @overload def _factory( self, *, decode_responses: Literal[False], is_redis_cluster: bool = False, readonly_mode: bool = False, hosts: list[dict[Any, Any]] | dict[Any, Any] | None = None, client_args: dict[str, Any] | None = None, **config: Any, ) -> RedisCluster[bytes] | StrictRedis[bytes]: ... @overload def _factory( self, *, decode_responses: Literal[True], is_redis_cluster: bool = False, readonly_mode: bool = False, hosts: list[dict[Any, Any]] | dict[Any, Any] | None = None, client_args: dict[str, Any] | None = None, **config: Any, ) -> RedisCluster[str] | StrictRedis[str]: ... def _factory( self, *, decode_responses: bool, is_redis_cluster: bool = False, readonly_mode: bool = False, hosts: list[dict[Any, Any]] | dict[Any, Any] | None = None, client_args: dict[str, Any] | None = None, **config: Any, ) -> RedisCluster[bytes] | StrictRedis[bytes] | RedisCluster[str] | StrictRedis[str]: # StrictRedisCluster expects a list of { host, port } dicts. Coerce the # configuration into the correct format if necessary. if not hosts: hosts = [] hosts_list = list(hosts.values()) if isinstance(hosts, dict) else hosts # support for scaling reads using the readonly mode # https://redis.io/docs/reference/cluster-spec/#scaling-reads-using-replica-nodes if not client_args: client_args = {} client_args = {**_REDIS_DEFAULT_CLIENT_ARGS, **client_args} # Redis cluster does not wait to attempt to connect. We'd prefer to not # make TCP connections on boot. Wrap the client in a lazy proxy object. def cluster_factory() -> ( RedisCluster[bytes] | StrictRedis[bytes] | RedisCluster[str] | StrictRedis[str] ): if is_redis_cluster: return RetryingRedisCluster( # Intentionally copy hosts here because redis-cluster-py # mutates the inner dicts and this closure can be run # concurrently, as SimpleLazyObject is not threadsafe. This # is likely triggered by RetryingRedisCluster running # reset() after startup # # https://github.com/Grokzen/redis-py-cluster/blob/73f27edf7ceb4a408b3008ef7d82dac570ab9c6a/rediscluster/nodemanager.py#L385 startup_nodes=deepcopy(hosts_list), decode_responses=decode_responses, skip_full_coverage_check=True, max_connections=16, max_connections_per_node=True, readonly_mode=readonly_mode, **client_args, ) else: assert len(hosts_list) > 0, "Hosts should have at least 1 entry" host = dict(hosts_list[0]) host["decode_responses"] = decode_responses return FailoverRedis(**host, **client_args) # losing some type safety: SimpleLazyObject acts like the underlying type return SimpleLazyObject(cluster_factory) # type: ignore[return-value] def get(self, key: str) -> RedisCluster[str] | StrictRedis[str]: try: return self._clusters_str[key] except KeyError: pass # Do not access attributes of the `cluster` object to prevent # setup/init of lazy objects. ret = self._clusters_str[key] = self._factory(**self._cfg(key), decode_responses=True) return ret def get_binary(self, key: str) -> RedisCluster[bytes] | StrictRedis[bytes]: try: return self._clusters_bytes[key] except KeyError: pass # Do not access attributes of the `cluster` object to prevent # setup/init of lazy objects. ret = self._clusters_bytes[key] = self._factory(**self._cfg(key), decode_responses=False) return ret # TODO(epurkhiser): When migration of all rb cluster to true redis clusters has # completed, remove the rb ``clusters`` module variable and rename # redis_clusters to clusters. clusters = RBClusterManager(options.default_manager) redis_clusters = RedisClusterManager(options.default_manager) def get_cluster_from_options( setting: str, options: dict[str, Any], cluster_manager: RBClusterManager = clusters, ) -> tuple[rb.Cluster, dict[str, Any]]: cluster_option_name = "cluster" default_cluster_name = "default" cluster_constructor_option_names = frozenset(("hosts",)) options = options.copy() cluster_options = { key: options.pop(key) for key in set(options.keys()).intersection(cluster_constructor_option_names) } if cluster_options: if cluster_option_name in options: raise InvalidConfiguration( "Cannot provide both named cluster ({!r}) and cluster configuration ({}) options.".format( cluster_option_name, ", ".join(repr(name) for name in cluster_constructor_option_names), ) ) else: warnings.warn( DeprecatedSettingWarning( "{} parameter of {}".format( ", ".join(repr(name) for name in cluster_constructor_option_names), setting ), f'{setting}["{cluster_option_name}"]', removed_in_version="8.5", ), stacklevel=2, ) cluster = rb.Cluster(pool_cls=_shared_pool, **cluster_options) else: cluster = cluster_manager.get(options.pop(cluster_option_name, default_cluster_name)) return cluster, options def get_dynamic_cluster_from_options( setting: str, config: dict[str, Any] ) -> tuple[bool, RedisCluster[str] | StrictRedis[str] | rb.Cluster, dict[str, Any]]: cluster_name = config.get("cluster", "default") cluster_opts: dict[str, Any] | None = options.default_manager.get("redis.clusters").get( cluster_name ) if cluster_opts is not None and cluster_opts.get("is_redis_cluster"): # RedisCluster, StrictRedis return True, redis_clusters.get(cluster_name), config # RBCluster cluster, config = get_cluster_from_options(setting, config) return False, cluster, config def get_cluster_routing_client( cluster: RedisCluster[T] | rb.Cluster, is_redis_cluster: bool ) -> RedisCluster[T] | rb.RoutingClient: if is_instance_redis_cluster(cluster, is_redis_cluster): return cluster elif is_instance_rb_cluster(cluster, is_redis_cluster): return cluster.get_routing_client() else: raise AssertionError("unreachable") def is_instance_redis_cluster( val: rb.Cluster | RedisCluster[str], is_redis_cluster: bool ) -> TypeGuard[RedisCluster[str]]: return is_redis_cluster def is_instance_rb_cluster( val: rb.Cluster | RedisCluster[str], is_redis_cluster: bool ) -> TypeGuard[rb.Cluster]: return not is_redis_cluster def validate_dynamic_cluster( is_redis_cluster: bool, cluster: rb.Cluster | RedisCluster[str] ) -> None: try: if is_instance_redis_cluster(cluster, is_redis_cluster): cluster.ping() cluster.connection_pool.disconnect() elif is_instance_rb_cluster(cluster, is_redis_cluster): with cluster.all() as client: client.ping() cluster.disconnect_pools() else: raise AssertionError("unreachable") except Exception as e: raise InvalidConfiguration(str(e)) from e def check_cluster_versions( cluster: rb.Cluster, required: Version, recommended: Version | None = None, label: str | None = None, ) -> None: try: with cluster.all() as client: results = client.info() cluster.disconnect_pools() except Exception as e: # Any connection issues should be caught here. raise InvalidConfiguration(str(e)) from e versions = {} for id, info in results.value.items(): host = cluster.hosts[id] # NOTE: This assumes there is no routing magic going on here, and # all requests to this host are being served by the same database. key = f"{host.host}:{host.port}" versions[key] = Version([int(part) for part in info["redis_version"].split(".", 3)]) check_versions( "Redis" if label is None else f"Redis ({label})", versions, required, recommended ) def load_redis_script(path: str) -> Script: return Script( None, importlib.resources.files("sentry").joinpath("scripts", path).read_bytes(), )
RedisClusterManager
python
PyCQA__pylint
tests/functional/u/unexpected_special_method_signature.py
{ "start": 1183, "end": 1365 }
class ____: def __enter__(self): return self def __exit__(self, exc_type, value, tb, stack): # [unexpected-special-method-signature] pass
SecondBadContextManager
python
pytorch__pytorch
torch/testing/_internal/autograd_function_db.py
{ "start": 739, "end": 1700 }
class ____(torch.autograd.Function): @staticmethod def forward(input): input_np = to_numpy(input) dinput = torch.tensor(3 * input_np ** 2, device=input.device) return torch.tensor(input_np ** 3, device=input.device), dinput @staticmethod def setup_context(ctx, inputs, output): ctx.save_for_backward(inputs[0], output[1]) ctx.save_for_forward(inputs[0], output[1]) @staticmethod def backward(ctx, grad_output, grad_saved): input, dinput = ctx.saved_tensors return NumpyMul.apply(grad_output, dinput) + 6 * NumpyMul.apply(grad_saved, input) @staticmethod def vmap(info, in_dims, input): result = NumpyCube.apply(input) return result, (in_dims[0], in_dims[0]) @staticmethod def jvp(ctx, input_tangent): input, dinput = ctx.saved_tensors return NumpyMul.apply(input_tangent, dinput), 6 * NumpyMul.apply(input_tangent, input)
NumpyCube
python
pypa__pipenv
pipenv/patched/pip/_vendor/distlib/wheel.py
{ "start": 4732, "end": 43979 }
class ____(object): """ Class to build and install from Wheel files (PEP 427). """ wheel_version = (1, 1) hash_kind = 'sha256' def __init__(self, filename=None, sign=False, verify=False): """ Initialise an instance using a (valid) filename. """ self.sign = sign self.should_verify = verify self.buildver = '' self.pyver = [PYVER] self.abi = ['none'] self.arch = ['any'] self.dirname = os.getcwd() if filename is None: self.name = 'dummy' self.version = '0.1' self._filename = self.filename else: m = NAME_VERSION_RE.match(filename) if m: info = m.groupdict('') self.name = info['nm'] # Reinstate the local version separator self.version = info['vn'].replace('_', '-') self.buildver = info['bn'] self._filename = self.filename else: dirname, filename = os.path.split(filename) m = FILENAME_RE.match(filename) if not m: raise DistlibException('Invalid name or ' 'filename: %r' % filename) if dirname: self.dirname = os.path.abspath(dirname) self._filename = filename info = m.groupdict('') self.name = info['nm'] self.version = info['vn'] self.buildver = info['bn'] self.pyver = info['py'].split('.') self.abi = info['bi'].split('.') self.arch = info['ar'].split('.') @property def filename(self): """ Build and return a filename from the various components. """ if self.buildver: buildver = '-' + self.buildver else: buildver = '' pyver = '.'.join(self.pyver) abi = '.'.join(self.abi) arch = '.'.join(self.arch) # replace - with _ as a local version separator version = self.version.replace('-', '_') return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver, pyver, abi, arch) @property def exists(self): path = os.path.join(self.dirname, self.filename) return os.path.isfile(path) @property def tags(self): for pyver in self.pyver: for abi in self.abi: for arch in self.arch: yield pyver, abi, arch @cached_property def metadata(self): pathname = os.path.join(self.dirname, self.filename) name_ver = '%s-%s' % (self.name, self.version) info_dir = '%s.dist-info' % name_ver wrapper = codecs.getreader('utf-8') with ZipFile(pathname, 'r') as zf: self.get_wheel_metadata(zf) # wv = wheel_metadata['Wheel-Version'].split('.', 1) # file_version = tuple([int(i) for i in wv]) # if file_version < (1, 1): # fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME, # LEGACY_METADATA_FILENAME] # else: # fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME] fns = [WHEEL_METADATA_FILENAME, LEGACY_METADATA_FILENAME] result = None for fn in fns: try: metadata_filename = posixpath.join(info_dir, fn) with zf.open(metadata_filename) as bf: wf = wrapper(bf) result = Metadata(fileobj=wf) if result: break except KeyError: pass if not result: raise ValueError('Invalid wheel, because metadata is ' 'missing: looked in %s' % ', '.join(fns)) return result def get_wheel_metadata(self, zf): name_ver = '%s-%s' % (self.name, self.version) info_dir = '%s.dist-info' % name_ver metadata_filename = posixpath.join(info_dir, 'WHEEL') with zf.open(metadata_filename) as bf: wf = codecs.getreader('utf-8')(bf) message = message_from_file(wf) return dict(message) @cached_property def info(self): pathname = os.path.join(self.dirname, self.filename) with ZipFile(pathname, 'r') as zf: result = self.get_wheel_metadata(zf) return result def process_shebang(self, data): m = SHEBANG_RE.match(data) if m: end = m.end() shebang, data_after_shebang = data[:end], data[end:] # Preserve any arguments after the interpreter if b'pythonw' in shebang.lower(): shebang_python = SHEBANG_PYTHONW else: shebang_python = SHEBANG_PYTHON m = SHEBANG_DETAIL_RE.match(shebang) if m: args = b' ' + m.groups()[-1] else: args = b'' shebang = shebang_python + args data = shebang + data_after_shebang else: cr = data.find(b'\r') lf = data.find(b'\n') if cr < 0 or cr > lf: term = b'\n' else: if data[cr:cr + 2] == b'\r\n': term = b'\r\n' else: term = b'\r' data = SHEBANG_PYTHON + term + data return data def get_hash(self, data, hash_kind=None): if hash_kind is None: hash_kind = self.hash_kind try: hasher = getattr(hashlib, hash_kind) except AttributeError: raise DistlibException('Unsupported hash algorithm: %r' % hash_kind) result = hasher(data).digest() result = base64.urlsafe_b64encode(result).rstrip(b'=').decode('ascii') return hash_kind, result def write_record(self, records, record_path, archive_record_path): records = list(records) # make a copy, as mutated records.append((archive_record_path, '', '')) with CSVWriter(record_path) as writer: for row in records: writer.writerow(row) def write_records(self, info, libdir, archive_paths): records = [] distinfo, info_dir = info # hasher = getattr(hashlib, self.hash_kind) for ap, p in archive_paths: with open(p, 'rb') as f: data = f.read() digest = '%s=%s' % self.get_hash(data) size = os.path.getsize(p) records.append((ap, digest, size)) p = os.path.join(distinfo, 'RECORD') ap = to_posix(os.path.join(info_dir, 'RECORD')) self.write_record(records, p, ap) archive_paths.append((ap, p)) def build_zip(self, pathname, archive_paths): with ZipFile(pathname, 'w', zipfile.ZIP_DEFLATED) as zf: for ap, p in archive_paths: logger.debug('Wrote %s to %s in wheel', p, ap) zf.write(p, ap) def build(self, paths, tags=None, wheel_version=None): """ Build a wheel from files in specified paths, and use any specified tags when determining the name of the wheel. """ if tags is None: tags = {} libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0] if libkey == 'platlib': is_pure = 'false' default_pyver = [IMPVER] default_abi = [ABI] default_arch = [ARCH] else: is_pure = 'true' default_pyver = [PYVER] default_abi = ['none'] default_arch = ['any'] self.pyver = tags.get('pyver', default_pyver) self.abi = tags.get('abi', default_abi) self.arch = tags.get('arch', default_arch) libdir = paths[libkey] name_ver = '%s-%s' % (self.name, self.version) data_dir = '%s.data' % name_ver info_dir = '%s.dist-info' % name_ver archive_paths = [] # First, stuff which is not in site-packages for key in ('data', 'headers', 'scripts'): if key not in paths: continue path = paths[key] if os.path.isdir(path): for root, dirs, files in os.walk(path): for fn in files: p = fsdecode(os.path.join(root, fn)) rp = os.path.relpath(p, path) ap = to_posix(os.path.join(data_dir, key, rp)) archive_paths.append((ap, p)) if key == 'scripts' and not p.endswith('.exe'): with open(p, 'rb') as f: data = f.read() data = self.process_shebang(data) with open(p, 'wb') as f: f.write(data) # Now, stuff which is in site-packages, other than the # distinfo stuff. path = libdir distinfo = None for root, dirs, files in os.walk(path): if root == path: # At the top level only, save distinfo for later # and skip it for now for i, dn in enumerate(dirs): dn = fsdecode(dn) if dn.endswith('.dist-info'): distinfo = os.path.join(root, dn) del dirs[i] break assert distinfo, '.dist-info directory expected, not found' for fn in files: # comment out next suite to leave .pyc files in if fsdecode(fn).endswith(('.pyc', '.pyo')): continue p = os.path.join(root, fn) rp = to_posix(os.path.relpath(p, path)) archive_paths.append((rp, p)) # Now distinfo. Assumed to be flat, i.e. os.listdir is enough. files = os.listdir(distinfo) for fn in files: if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'): p = fsdecode(os.path.join(distinfo, fn)) ap = to_posix(os.path.join(info_dir, fn)) archive_paths.append((ap, p)) wheel_metadata = [ 'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version), 'Generator: distlib %s' % __version__, 'Root-Is-Purelib: %s' % is_pure, ] for pyver, abi, arch in self.tags: wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch)) p = os.path.join(distinfo, 'WHEEL') with open(p, 'w') as f: f.write('\n'.join(wheel_metadata)) ap = to_posix(os.path.join(info_dir, 'WHEEL')) archive_paths.append((ap, p)) # sort the entries by archive path. Not needed by any spec, but it # keeps the archive listing and RECORD tidier than they would otherwise # be. Use the number of path segments to keep directory entries together, # and keep the dist-info stuff at the end. def sorter(t): ap = t[0] n = ap.count('/') if '.dist-info' in ap: n += 10000 return (n, ap) archive_paths = sorted(archive_paths, key=sorter) # Now, at last, RECORD. # Paths in here are archive paths - nothing else makes sense. self.write_records((distinfo, info_dir), libdir, archive_paths) # Now, ready to build the zip file pathname = os.path.join(self.dirname, self.filename) self.build_zip(pathname, archive_paths) return pathname def skip_entry(self, arcname): """ Determine whether an archive entry should be skipped when verifying or installing. """ # The signature file won't be in RECORD, # and we don't currently don't do anything with it # We also skip directories, as they won't be in RECORD # either. See: # # https://github.com/pypa/wheel/issues/294 # https://github.com/pypa/wheel/issues/287 # https://github.com/pypa/wheel/pull/289 # return arcname.endswith(('/', '/RECORD.jws')) def install(self, paths, maker, **kwargs): """ Install a wheel to the specified paths. If kwarg ``warner`` is specified, it should be a callable, which will be called with two tuples indicating the wheel version of this software and the wheel version in the file, if there is a discrepancy in the versions. This can be used to issue any warnings to raise any exceptions. If kwarg ``lib_only`` is True, only the purelib/platlib files are installed, and the headers, scripts, data and dist-info metadata are not written. If kwarg ``bytecode_hashed_invalidation`` is True, written bytecode will try to use file-hash based invalidation (PEP-552) on supported interpreter versions (CPython 3.7+). The return value is a :class:`InstalledDistribution` instance unless ``options.lib_only`` is True, in which case the return value is ``None``. """ dry_run = maker.dry_run warner = kwargs.get('warner') lib_only = kwargs.get('lib_only', False) bc_hashed_invalidation = kwargs.get('bytecode_hashed_invalidation', False) pathname = os.path.join(self.dirname, self.filename) name_ver = '%s-%s' % (self.name, self.version) data_dir = '%s.data' % name_ver info_dir = '%s.dist-info' % name_ver metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME) wheel_metadata_name = posixpath.join(info_dir, 'WHEEL') record_name = posixpath.join(info_dir, 'RECORD') wrapper = codecs.getreader('utf-8') with ZipFile(pathname, 'r') as zf: with zf.open(wheel_metadata_name) as bwf: wf = wrapper(bwf) message = message_from_file(wf) wv = message['Wheel-Version'].split('.', 1) file_version = tuple([int(i) for i in wv]) if (file_version != self.wheel_version) and warner: warner(self.wheel_version, file_version) if message['Root-Is-Purelib'] == 'true': libdir = paths['purelib'] else: libdir = paths['platlib'] records = {} with zf.open(record_name) as bf: with CSVReader(stream=bf) as reader: for row in reader: p = row[0] records[p] = row data_pfx = posixpath.join(data_dir, '') info_pfx = posixpath.join(info_dir, '') script_pfx = posixpath.join(data_dir, 'scripts', '') # make a new instance rather than a copy of maker's, # as we mutate it fileop = FileOperator(dry_run=dry_run) fileop.record = True # so we can rollback if needed bc = not sys.dont_write_bytecode # Double negatives. Lovely! outfiles = [] # for RECORD writing # for script copying/shebang processing workdir = tempfile.mkdtemp() # set target dir later # we default add_launchers to False, as the # Python Launcher should be used instead maker.source_dir = workdir maker.target_dir = None try: for zinfo in zf.infolist(): arcname = zinfo.filename if isinstance(arcname, text_type): u_arcname = arcname else: u_arcname = arcname.decode('utf-8') if self.skip_entry(u_arcname): continue row = records[u_arcname] if row[2] and str(zinfo.file_size) != row[2]: raise DistlibException('size mismatch for ' '%s' % u_arcname) if row[1]: kind, value = row[1].split('=', 1) with zf.open(arcname) as bf: data = bf.read() _, digest = self.get_hash(data, kind) if digest != value: raise DistlibException('digest mismatch for ' '%s' % arcname) if lib_only and u_arcname.startswith((info_pfx, data_pfx)): logger.debug('lib_only: skipping %s', u_arcname) continue is_script = (u_arcname.startswith(script_pfx) and not u_arcname.endswith('.exe')) if u_arcname.startswith(data_pfx): _, where, rp = u_arcname.split('/', 2) outfile = os.path.join(paths[where], convert_path(rp)) else: # meant for site-packages. if u_arcname in (wheel_metadata_name, record_name): continue outfile = os.path.join(libdir, convert_path(u_arcname)) if not is_script: with zf.open(arcname) as bf: fileop.copy_stream(bf, outfile) # Issue #147: permission bits aren't preserved. Using # zf.extract(zinfo, libdir) should have worked, but didn't, # see https://www.thetopsites.net/article/53834422.shtml # So ... manually preserve permission bits as given in zinfo if os.name == 'posix': # just set the normal permission bits os.chmod(outfile, (zinfo.external_attr >> 16) & 0x1FF) outfiles.append(outfile) # Double check the digest of the written file if not dry_run and row[1]: with open(outfile, 'rb') as bf: data = bf.read() _, newdigest = self.get_hash(data, kind) if newdigest != digest: raise DistlibException('digest mismatch ' 'on write for ' '%s' % outfile) if bc and outfile.endswith('.py'): try: pyc = fileop.byte_compile(outfile, hashed_invalidation=bc_hashed_invalidation) outfiles.append(pyc) except Exception: # Don't give up if byte-compilation fails, # but log it and perhaps warn the user logger.warning('Byte-compilation failed', exc_info=True) else: fn = os.path.basename(convert_path(arcname)) workname = os.path.join(workdir, fn) with zf.open(arcname) as bf: fileop.copy_stream(bf, workname) dn, fn = os.path.split(outfile) maker.target_dir = dn filenames = maker.make(fn) fileop.set_executable_mode(filenames) outfiles.extend(filenames) if lib_only: logger.debug('lib_only: returning None') dist = None else: # Generate scripts # Try to get pydist.json so we can see if there are # any commands to generate. If this fails (e.g. because # of a legacy wheel), log a warning but don't give up. commands = None file_version = self.info['Wheel-Version'] if file_version == '1.0': # Use legacy info ep = posixpath.join(info_dir, 'entry_points.txt') try: with zf.open(ep) as bwf: epdata = read_exports(bwf) commands = {} for key in ('console', 'gui'): k = '%s_scripts' % key if k in epdata: commands['wrap_%s' % key] = d = {} for v in epdata[k].values(): s = '%s:%s' % (v.prefix, v.suffix) if v.flags: s += ' [%s]' % ','.join(v.flags) d[v.name] = s except Exception: logger.warning('Unable to read legacy script ' 'metadata, so cannot generate ' 'scripts') else: try: with zf.open(metadata_name) as bwf: wf = wrapper(bwf) commands = json.load(wf).get('extensions') if commands: commands = commands.get('python.commands') except Exception: logger.warning('Unable to read JSON metadata, so ' 'cannot generate scripts') if commands: console_scripts = commands.get('wrap_console', {}) gui_scripts = commands.get('wrap_gui', {}) if console_scripts or gui_scripts: script_dir = paths.get('scripts', '') if not os.path.isdir(script_dir): raise ValueError('Valid script path not ' 'specified') maker.target_dir = script_dir for k, v in console_scripts.items(): script = '%s = %s' % (k, v) filenames = maker.make(script) fileop.set_executable_mode(filenames) if gui_scripts: options = {'gui': True} for k, v in gui_scripts.items(): script = '%s = %s' % (k, v) filenames = maker.make(script, options) fileop.set_executable_mode(filenames) p = os.path.join(libdir, info_dir) dist = InstalledDistribution(p) # Write SHARED paths = dict(paths) # don't change passed in dict del paths['purelib'] del paths['platlib'] paths['lib'] = libdir p = dist.write_shared_locations(paths, dry_run) if p: outfiles.append(p) # Write RECORD dist.write_installed_files(outfiles, paths['prefix'], dry_run) return dist except Exception: # pragma: no cover logger.exception('installation failed.') fileop.rollback() raise finally: shutil.rmtree(workdir) def _get_dylib_cache(self): global cache if cache is None: # Use native string to avoid issues on 2.x: see Python #20140. base = os.path.join(get_cache_base(), str('dylib-cache'), '%s.%s' % sys.version_info[:2]) cache = Cache(base) return cache def _get_extensions(self): pathname = os.path.join(self.dirname, self.filename) name_ver = '%s-%s' % (self.name, self.version) info_dir = '%s.dist-info' % name_ver arcname = posixpath.join(info_dir, 'EXTENSIONS') wrapper = codecs.getreader('utf-8') result = [] with ZipFile(pathname, 'r') as zf: try: with zf.open(arcname) as bf: wf = wrapper(bf) extensions = json.load(wf) cache = self._get_dylib_cache() prefix = cache.prefix_to_dir(self.filename, use_abspath=False) cache_base = os.path.join(cache.base, prefix) if not os.path.isdir(cache_base): os.makedirs(cache_base) for name, relpath in extensions.items(): dest = os.path.join(cache_base, convert_path(relpath)) if not os.path.exists(dest): extract = True else: file_time = os.stat(dest).st_mtime file_time = datetime.datetime.fromtimestamp(file_time) info = zf.getinfo(relpath) wheel_time = datetime.datetime(*info.date_time) extract = wheel_time > file_time if extract: zf.extract(relpath, cache_base) result.append((name, dest)) except KeyError: pass return result def is_compatible(self): """ Determine if a wheel is compatible with the running system. """ return is_compatible(self) def is_mountable(self): """ Determine if a wheel is asserted as mountable by its metadata. """ return True # for now - metadata details TBD def mount(self, append=False): pathname = os.path.abspath(os.path.join(self.dirname, self.filename)) if not self.is_compatible(): msg = 'Wheel %s not compatible with this Python.' % pathname raise DistlibException(msg) if not self.is_mountable(): msg = 'Wheel %s is marked as not mountable.' % pathname raise DistlibException(msg) if pathname in sys.path: logger.debug('%s already in path', pathname) else: if append: sys.path.append(pathname) else: sys.path.insert(0, pathname) extensions = self._get_extensions() if extensions: if _hook not in sys.meta_path: sys.meta_path.append(_hook) _hook.add(pathname, extensions) def unmount(self): pathname = os.path.abspath(os.path.join(self.dirname, self.filename)) if pathname not in sys.path: logger.debug('%s not in path', pathname) else: sys.path.remove(pathname) if pathname in _hook.impure_wheels: _hook.remove(pathname) if not _hook.impure_wheels: if _hook in sys.meta_path: sys.meta_path.remove(_hook) def verify(self): pathname = os.path.join(self.dirname, self.filename) name_ver = '%s-%s' % (self.name, self.version) # data_dir = '%s.data' % name_ver info_dir = '%s.dist-info' % name_ver # metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME) wheel_metadata_name = posixpath.join(info_dir, 'WHEEL') record_name = posixpath.join(info_dir, 'RECORD') wrapper = codecs.getreader('utf-8') with ZipFile(pathname, 'r') as zf: with zf.open(wheel_metadata_name) as bwf: wf = wrapper(bwf) message_from_file(wf) # wv = message['Wheel-Version'].split('.', 1) # file_version = tuple([int(i) for i in wv]) # TODO version verification records = {} with zf.open(record_name) as bf: with CSVReader(stream=bf) as reader: for row in reader: p = row[0] records[p] = row for zinfo in zf.infolist(): arcname = zinfo.filename if isinstance(arcname, text_type): u_arcname = arcname else: u_arcname = arcname.decode('utf-8') # See issue #115: some wheels have .. in their entries, but # in the filename ... e.g. __main__..py ! So the check is # updated to look for .. in the directory portions p = u_arcname.split('/') if '..' in p: raise DistlibException('invalid entry in ' 'wheel: %r' % u_arcname) if self.skip_entry(u_arcname): continue row = records[u_arcname] if row[2] and str(zinfo.file_size) != row[2]: raise DistlibException('size mismatch for ' '%s' % u_arcname) if row[1]: kind, value = row[1].split('=', 1) with zf.open(arcname) as bf: data = bf.read() _, digest = self.get_hash(data, kind) if digest != value: raise DistlibException('digest mismatch for ' '%s' % arcname) def update(self, modifier, dest_dir=None, **kwargs): """ Update the contents of a wheel in a generic way. The modifier should be a callable which expects a dictionary argument: its keys are archive-entry paths, and its values are absolute filesystem paths where the contents the corresponding archive entries can be found. The modifier is free to change the contents of the files pointed to, add new entries and remove entries, before returning. This method will extract the entire contents of the wheel to a temporary location, call the modifier, and then use the passed (and possibly updated) dictionary to write a new wheel. If ``dest_dir`` is specified, the new wheel is written there -- otherwise, the original wheel is overwritten. The modifier should return True if it updated the wheel, else False. This method returns the same value the modifier returns. """ def get_version(path_map, info_dir): version = path = None key = '%s/%s' % (info_dir, LEGACY_METADATA_FILENAME) if key not in path_map: key = '%s/PKG-INFO' % info_dir if key in path_map: path = path_map[key] version = Metadata(path=path).version return version, path def update_version(version, path): updated = None try: NormalizedVersion(version) i = version.find('-') if i < 0: updated = '%s+1' % version else: parts = [int(s) for s in version[i + 1:].split('.')] parts[-1] += 1 updated = '%s+%s' % (version[:i], '.'.join(str(i) for i in parts)) except UnsupportedVersionError: logger.debug('Cannot update non-compliant (PEP-440) ' 'version %r', version) if updated: md = Metadata(path=path) md.version = updated legacy = path.endswith(LEGACY_METADATA_FILENAME) md.write(path=path, legacy=legacy) logger.debug('Version updated from %r to %r', version, updated) pathname = os.path.join(self.dirname, self.filename) name_ver = '%s-%s' % (self.name, self.version) info_dir = '%s.dist-info' % name_ver record_name = posixpath.join(info_dir, 'RECORD') with tempdir() as workdir: with ZipFile(pathname, 'r') as zf: path_map = {} for zinfo in zf.infolist(): arcname = zinfo.filename if isinstance(arcname, text_type): u_arcname = arcname else: u_arcname = arcname.decode('utf-8') if u_arcname == record_name: continue if '..' in u_arcname: raise DistlibException('invalid entry in ' 'wheel: %r' % u_arcname) zf.extract(zinfo, workdir) path = os.path.join(workdir, convert_path(u_arcname)) path_map[u_arcname] = path # Remember the version. original_version, _ = get_version(path_map, info_dir) # Files extracted. Call the modifier. modified = modifier(path_map, **kwargs) if modified: # Something changed - need to build a new wheel. current_version, path = get_version(path_map, info_dir) if current_version and (current_version == original_version): # Add or update local version to signify changes. update_version(current_version, path) # Decide where the new wheel goes. if dest_dir is None: fd, newpath = tempfile.mkstemp(suffix='.whl', prefix='wheel-update-', dir=workdir) os.close(fd) else: if not os.path.isdir(dest_dir): raise DistlibException('Not a directory: %r' % dest_dir) newpath = os.path.join(dest_dir, self.filename) archive_paths = list(path_map.items()) distinfo = os.path.join(workdir, info_dir) info = distinfo, info_dir self.write_records(info, workdir, archive_paths) self.build_zip(newpath, archive_paths) if dest_dir is None: shutil.copyfile(newpath, pathname) return modified def _get_glibc_version(): import platform ver = platform.libc_ver() result = [] if ver[0] == 'glibc': for s in ver[1].split('.'): result.append(int(s) if s.isdigit() else 0) result = tuple(result) return result def compatible_tags(): """ Return (pyver, abi, arch) tuples compatible with this Python. """ class _Version: def __init__(self, major, minor): self.major = major self.major_minor = (major, minor) self.string = ''.join((str(major), str(minor))) def __str__(self): return self.string versions = [ _Version(sys.version_info.major, minor_version) for minor_version in range(sys.version_info.minor, -1, -1) ] abis = [] for suffix in _get_suffixes(): if suffix.startswith('.abi'): abis.append(suffix.split('.', 2)[1]) abis.sort() if ABI != 'none': abis.insert(0, ABI) abis.append('none') result = [] arches = [ARCH] if sys.platform == 'darwin': m = re.match(r'(\w+)_(\d+)_(\d+)_(\w+)$', ARCH) if m: name, major, minor, arch = m.groups() minor = int(minor) matches = [arch] if arch in ('i386', 'ppc'): matches.append('fat') if arch in ('i386', 'ppc', 'x86_64'): matches.append('fat3') if arch in ('ppc64', 'x86_64'): matches.append('fat64') if arch in ('i386', 'x86_64'): matches.append('intel') if arch in ('i386', 'x86_64', 'intel', 'ppc', 'ppc64'): matches.append('universal') while minor >= 0: for match in matches: s = '%s_%s_%s_%s' % (name, major, minor, match) if s != ARCH: # already there arches.append(s) minor -= 1 # Most specific - our Python version, ABI and arch for i, version_object in enumerate(versions): version = str(version_object) add_abis = [] if i == 0: add_abis = abis if IMP_PREFIX == 'cp' and version_object.major_minor >= (3, 2): limited_api_abi = 'abi' + str(version_object.major) if limited_api_abi not in add_abis: add_abis.append(limited_api_abi) for abi in add_abis: for arch in arches: result.append((''.join((IMP_PREFIX, version)), abi, arch)) # manylinux if abi != 'none' and sys.platform.startswith('linux'): arch = arch.replace('linux_', '') parts = _get_glibc_version() if len(parts) == 2: if parts >= (2, 5): result.append((''.join((IMP_PREFIX, version)), abi, 'manylinux1_%s' % arch)) if parts >= (2, 12): result.append((''.join((IMP_PREFIX, version)), abi, 'manylinux2010_%s' % arch)) if parts >= (2, 17): result.append((''.join((IMP_PREFIX, version)), abi, 'manylinux2014_%s' % arch)) result.append((''.join( (IMP_PREFIX, version)), abi, 'manylinux_%s_%s_%s' % (parts[0], parts[1], arch))) # where no ABI / arch dependency, but IMP_PREFIX dependency for i, version_object in enumerate(versions): version = str(version_object) result.append((''.join((IMP_PREFIX, version)), 'none', 'any')) if i == 0: result.append((''.join((IMP_PREFIX, version[0])), 'none', 'any')) # no IMP_PREFIX, ABI or arch dependency for i, version_object in enumerate(versions): version = str(version_object) result.append((''.join(('py', version)), 'none', 'any')) if i == 0: result.append((''.join(('py', version[0])), 'none', 'any')) return set(result) COMPATIBLE_TAGS = compatible_tags() del compatible_tags def is_compatible(wheel, tags=None): if not isinstance(wheel, Wheel): wheel = Wheel(wheel) # assume it's a filename result = False if tags is None: tags = COMPATIBLE_TAGS for ver, abi, arch in tags: if ver in wheel.pyver and abi in wheel.abi and arch in wheel.arch: result = True break return result
Wheel
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/auto_materialize_asset_evaluations.py
{ "start": 9701, "end": 9923 }
class ____(graphene.ObjectType): records = non_null_list(GrapheneAutoMaterializeAssetEvaluationRecord) class Meta: name = "AutoMaterializeAssetEvaluationRecords"
GrapheneAutoMaterializeAssetEvaluationRecords
python
kamyu104__LeetCode-Solutions
Python/integer-break.py
{ "start": 49, "end": 1706 }
class ____(object): def integerBreak(self, n): """ :type n: int :rtype: int """ if n < 4: return n - 1 # Proof. # 1. Let n = a1 + a2 + ... + ak, product = a1 * a2 * ... * ak # - For each ai >= 4, we can always maximize the product by: # ai <= 2 * (ai - 2) # - For each aj >= 5, we can always maximize the product by: # aj <= 3 * (aj - 3) # # Conclusion 1: # - For n >= 4, the max of the product must be in the form of # 3^a * 2^b, s.t. 3a + 2b = n # # 2. To maximize the product = 3^a * 2^b s.t. 3a + 2b = n # - For each b >= 3, we can always maximize the product by: # 3^a * 2^b <= 3^(a+2) * 2^(b-3) s.t. 3(a+2) + 2(b-3) = n # # Conclusion 2: # - For n >= 4, the max of the product must be in the form of # 3^Q * 2^R, 0 <= R < 3 s.t. 3Q + 2R = n # i.e. # if n = 3Q + 0, the max of the product = 3^Q * 2^0 # if n = 3Q + 2, the max of the product = 3^Q * 2^1 # if n = 3Q + 2*2, the max of the product = 3^Q * 2^2 res = 0 if n % 3 == 0: # n = 3Q + 0, the max is 3^Q * 2^0 res = 3 ** (n // 3) elif n % 3 == 2: # n = 3Q + 2, the max is 3^Q * 2^1 res = 3 ** (n // 3) * 2 else: # n = 3Q + 4, the max is 3^Q * 2^2 res = 3 ** (n // 3 - 1) * 4 return res # Time: O(n) # Space: O(1) # DP solution.
Solution
python
pytorch__pytorch
torch/_inductor/codegen/rocm/rocm_template_buffer.py
{ "start": 208, "end": 827 }
class ____(TemplateBuffer): def __init__( self, layout: Layout, inputs: Sequence[Buffer], make_kernel_render: Callable[_P, _T], workspace_size: int, template: "ROCmTemplate", # type: ignore[name-defined] # noqa: F821 ) -> None: super().__init__(layout, inputs, make_kernel_render) # Global memory (in bytes) needed for this template. self.workspace_size = workspace_size self.template = template def get_workspace_size(self) -> int: return self.workspace_size if self.workspace_size is not None else 0
ROCmTemplateBuffer
python
ray-project__ray
rllib/examples/algorithms/sac/benchmark_sac_mujoco.py
{ "start": 1687, "end": 4491 }
class ____(Stopper): def __init__(self, benchmark_envs): self.benchmark_envs = benchmark_envs def __call__(self, trial_id, result): # Stop training if the mean reward is reached. if ( result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= self.benchmark_envs[result["env"]][ f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" ] ): return True # Otherwise check, if the total number of timesteps is exceeded. elif ( result[f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}"] >= self.benchmark_envs[result["env"]][f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}"] ): return True # Otherwise continue training. else: return False # Note, this needs to implemented b/c the parent class is abstract. def stop_all(self): return False config = ( SACConfig() .environment(env=tune.grid_search(list(benchmark_envs.keys()))) .env_runners( rollout_fragment_length=1, num_env_runners=0, ) .learners( # Note, we have a sample/train ratio of 1:1 and a small train # batch, so 1 learner with a single GPU should suffice. num_learners=1, num_gpus_per_learner=1, ) # TODO (simon): Adjust to new model_config_dict. .training( initial_alpha=1.001, # Choose a smaller learning rate for the actor (policy). actor_lr=3e-5, critic_lr=3e-4, alpha_lr=1e-4, target_entropy="auto", n_step=1, tau=0.005, train_batch_size=256, target_network_update_freq=1, replay_buffer_config={ "type": "PrioritizedEpisodeReplayBuffer", "capacity": 1000000, "alpha": 0.6, "beta": 0.4, }, num_steps_sampled_before_learning_starts=256, model={ "fcnet_hiddens": [256, 256], "fcnet_activation": "relu", "post_fcnet_hiddens": [], "post_fcnet_activation": None, "post_fcnet_weights_initializer": "orthogonal_", "post_fcnet_weights_initializer_config": {"gain": 0.01}, }, ) .reporting( metrics_num_episodes_for_smoothing=5, min_sample_timesteps_per_iteration=1000, ) .evaluation( evaluation_duration="auto", evaluation_interval=1, evaluation_num_env_runners=1, evaluation_parallel_to_training=True, evaluation_config={ "explore": False, }, ) ) tuner = tune.Tuner( "SAC", param_space=config, run_config=tune.RunConfig( stop=BenchmarkStopper(benchmark_envs=benchmark_envs), name="benchmark_sac_mujoco", ), ) tuner.fit()
BenchmarkStopper
python
ethereum__web3.py
tests/integration/test_ethereum_tester.py
{ "start": 7701, "end": 22692 }
class ____(EthModuleTest): test_eth_sign = not_implemented(EthModuleTest.test_eth_sign, MethodUnavailable) test_eth_sign_ens_names = not_implemented( EthModuleTest.test_eth_sign_ens_names, MethodUnavailable ) test_eth_sign_typed_data = not_implemented( EthModuleTest.test_eth_sign_typed_data, MethodUnavailable ) test_eth_sign_transaction_legacy = not_implemented( EthModuleTest.test_eth_sign_transaction_legacy, MethodUnavailable ) test_eth_sign_transaction = not_implemented( EthModuleTest.test_eth_sign_transaction, MethodUnavailable ) test_eth_sign_transaction_hex_fees = not_implemented( EthModuleTest.test_eth_sign_transaction_hex_fees, MethodUnavailable ) test_eth_sign_transaction_ens_names = not_implemented( EthModuleTest.test_eth_sign_transaction_ens_names, MethodUnavailable ) test_eth_get_raw_transaction = not_implemented( EthModuleTest.test_eth_get_raw_transaction, MethodUnavailable ) test_eth_get_raw_transaction_raises_error = not_implemented( EthModuleTest.test_eth_get_raw_transaction, MethodUnavailable ) test_eth_get_raw_transaction_by_block = not_implemented( EthModuleTest.test_eth_get_raw_transaction_by_block, MethodUnavailable ) test_eth_get_raw_transaction_by_block_raises_error = not_implemented( EthModuleTest.test_eth_get_raw_transaction_by_block, MethodUnavailable ) test_eth_call_with_override_param_type_check = not_implemented( EthModuleTest.test_eth_call_with_override_param_type_check, TypeError, ) test_eth_estimate_gas_with_override_param_type_check = not_implemented( EthModuleTest.test_eth_estimate_gas_with_override_param_type_check, TypeError, ) test_eth_create_access_list = not_implemented( EthModuleTest.test_eth_create_access_list, MethodUnavailable, ) test_eth_call_with_override_code = not_implemented( EthModuleTest.test_eth_call_with_override_code, TypeError, ) test_eth_getBlockReceipts_hash = not_implemented( EthModuleTest.test_eth_getBlockReceipts_hash, MethodUnavailable, ) test_eth_getBlockReceipts_not_found = not_implemented( EthModuleTest.test_eth_getBlockReceipts_not_found, MethodUnavailable, ) test_eth_getBlockReceipts_with_integer = not_implemented( EthModuleTest.test_eth_getBlockReceipts_with_integer, MethodUnavailable, ) test_eth_getBlockReceipts_safe = not_implemented( EthModuleTest.test_eth_getBlockReceipts_safe, MethodUnavailable, ) test_eth_getBlockReceipts_finalized = not_implemented( EthModuleTest.test_eth_getBlockReceipts_finalized, MethodUnavailable, ) test_eth_simulate_v1 = not_implemented( EthModuleTest.test_eth_simulate_v1, MethodUnavailable, ) def test_eth_getBlockByHash_pending(self, w3: "Web3") -> None: block = w3.eth.get_block("pending") assert block["hash"] is not None @disable_auto_mine def test_eth_get_transaction_receipt_unmined( self, eth_tester, w3, keyfile_account_address ): super().test_eth_get_transaction_receipt_unmined(w3, keyfile_account_address) @disable_auto_mine def test_eth_replace_transaction_legacy( self, eth_tester, w3, keyfile_account_address ): super().test_eth_replace_transaction_legacy(w3, keyfile_account_address) @disable_auto_mine def test_eth_replace_transaction(self, eth_tester, w3, keyfile_account_address): super().test_eth_replace_transaction(w3, keyfile_account_address) @disable_auto_mine @pytest.mark.xfail( reason="py-evm does not raise on EIP-1559 transaction underpriced" ) # TODO: This might also be an issue in py-evm worth looking into. See reason above. def test_eth_replace_transaction_underpriced( self, eth_tester, w3, keyfile_account_address ): super().test_eth_replace_transaction_underpriced(w3, keyfile_account_address) @disable_auto_mine def test_eth_replace_transaction_incorrect_nonce( self, eth_tester, w3, keyfile_account_address ): super().test_eth_replace_transaction_incorrect_nonce( w3, keyfile_account_address ) @disable_auto_mine def test_eth_replace_transaction_gas_price_too_low( self, eth_tester, w3, keyfile_account_address ): super().test_eth_replace_transaction_gas_price_too_low( w3, keyfile_account_address ) @disable_auto_mine def test_eth_replace_transaction_gas_price_defaulting_minimum( self, eth_tester, w3, keyfile_account_address ): super().test_eth_replace_transaction_gas_price_defaulting_minimum( w3, keyfile_account_address ) @disable_auto_mine def test_eth_replace_transaction_gas_price_defaulting_strategy_higher( self, eth_tester, w3, keyfile_account_address ): super().test_eth_replace_transaction_gas_price_defaulting_strategy_higher( w3, keyfile_account_address ) @disable_auto_mine def test_eth_replace_transaction_gas_price_defaulting_strategy_lower( self, eth_tester, w3, keyfile_account_address ): super().test_eth_replace_transaction_gas_price_defaulting_strategy_lower( w3, keyfile_account_address ) @disable_auto_mine def test_eth_modify_transaction_legacy( self, eth_tester, w3, keyfile_account_address ): super().test_eth_modify_transaction_legacy(w3, keyfile_account_address) @disable_auto_mine def test_eth_modify_transaction(self, eth_tester, w3, keyfile_account_address): super().test_eth_modify_transaction(w3, keyfile_account_address) @disable_auto_mine def test_eth_get_logs_without_logs( self, eth_tester, w3: "Web3", block_with_txn_with_log: BlockData ) -> None: # Note: This was the old way the test was written before geth started returning # an error when the `toBlock` was before the `fromBlock` # Test with block range filter_params = { "fromBlock": 0, "toBlock": block_with_txn_with_log["number"] - 1, } result = w3.eth.get_logs(filter_params) assert len(result) == 0 # the range is wrong filter_params = { "fromBlock": block_with_txn_with_log["number"], "toBlock": block_with_txn_with_log["number"] - 1, } result = w3.eth.get_logs(filter_params) assert len(result) == 0 # Test with `address` # filter with other address filter_params = { "fromBlock": 0, "address": UNKNOWN_ADDRESS, } result = w3.eth.get_logs(filter_params) assert len(result) == 0 # Test with multiple `address` # filter with other address filter_params = { "fromBlock": 0, "address": [UNKNOWN_ADDRESS, UNKNOWN_ADDRESS], } result = w3.eth.get_logs(filter_params) assert len(result) == 0 def test_eth_call_old_contract_state( self, eth_tester, w3, math_contract, keyfile_account_address ): super().test_eth_call_old_contract_state( w3, math_contract, keyfile_account_address ) def test_eth_chain_id(self, w3): chain_id = w3.eth.chain_id assert is_integer(chain_id) assert chain_id == 131277322940537 @disable_auto_mine def test_eth_wait_for_transaction_receipt_unmined( self, eth_tester, w3, keyfile_account_address_dual_type ): super().test_eth_wait_for_transaction_receipt_unmined( w3, keyfile_account_address_dual_type ) def test_eth_call_revert_with_msg( self, w3, revert_contract, keyfile_account_address ): txn_params = revert_contract._prepare_transaction( abi_element_identifier="revertWithMessage", transaction={ "from": keyfile_account_address, "to": revert_contract.address, }, ) with pytest.raises( TransactionFailed, match="execution reverted: Function has been reverted" ): w3.eth.call(txn_params) def test_eth_call_revert_without_msg( self, w3, revert_contract, keyfile_account_address ): txn_params = revert_contract._prepare_transaction( abi_element_identifier="revertWithoutMessage", transaction={ "from": keyfile_account_address, "to": revert_contract.address, }, ) with pytest.raises(TransactionFailed, match="execution reverted"): w3.eth.call(txn_params) def test_eth_estimate_gas_revert_with_msg( self, w3, revert_contract, keyfile_account_address ): txn_params = revert_contract._prepare_transaction( abi_element_identifier="revertWithMessage", transaction={ "from": keyfile_account_address, "to": revert_contract.address, }, ) with pytest.raises( TransactionFailed, match="execution reverted: Function has been reverted" ): w3.eth.estimate_gas(txn_params) def test_eth_estimate_gas_revert_without_msg( self, w3, revert_contract, keyfile_account_address ): with pytest.raises(TransactionFailed, match="execution reverted"): txn_params = revert_contract._prepare_transaction( abi_element_identifier="revertWithoutMessage", transaction={ "from": keyfile_account_address, "to": revert_contract.address, }, ) w3.eth.estimate_gas(txn_params) def test_eth_call_custom_error_revert_with_msg( self, w3, revert_contract, keyfile_account_address, ) -> None: txn_params = revert_contract._prepare_transaction( abi_element_identifier="customErrorWithMessage", transaction={ "from": keyfile_account_address, "to": revert_contract.address, }, ) # test that the error message matches the custom error text from the contract with pytest.raises(TransactionFailed, match="You are not authorized"): w3.eth.call(txn_params) def test_eth_call_custom_error_revert_without_msg( self, w3, revert_contract, keyfile_account_address ): txn_params = revert_contract._prepare_transaction( abi_element_identifier="customErrorWithoutMessage", transaction={ "from": keyfile_account_address, "to": revert_contract.address, }, ) with pytest.raises(TransactionFailed, match="execution reverted"): w3.eth.call(txn_params) def test_eth_estimate_gas_custom_error_revert_with_msg( self, w3, revert_contract, keyfile_account_address, ) -> None: txn_params = revert_contract._prepare_transaction( abi_element_identifier="customErrorWithMessage", transaction={ "from": keyfile_account_address, "to": revert_contract.address, }, ) # test that the error message matches the custom error text from the contract with pytest.raises(TransactionFailed, match="You are not authorized"): w3.eth.estimate_gas(txn_params) def test_eth_estimate_gas_custom_error_revert_without_msg( self, w3, revert_contract, keyfile_account_address, ) -> None: txn_params = revert_contract._prepare_transaction( abi_element_identifier="customErrorWithoutMessage", transaction={ "from": keyfile_account_address, "to": revert_contract.address, }, ) with pytest.raises(TransactionFailed, match="execution reverted"): w3.eth.estimate_gas(txn_params) @disable_auto_mine def test_eth_send_transaction(self, eth_tester, w3, keyfile_account_address): super().test_eth_send_transaction(w3, keyfile_account_address) @disable_auto_mine def test_eth_send_transaction_legacy(self, eth_tester, w3, keyfile_account_address): super().test_eth_send_transaction_legacy(w3, keyfile_account_address) def test_eth_send_raw_transaction(self, eth_tester, w3, keyfile_account_pkey): super().test_eth_send_raw_transaction(w3, keyfile_account_pkey) @disable_auto_mine @pytest.mark.parametrize( "max_fee", (1000000000, None), ids=["with_max_fee", "without_max_fee"] ) def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn( self, eth_tester, w3, keyfile_account_address, max_fee, ): super().test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn( w3, keyfile_account_address, max_fee ) @disable_auto_mine def test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn_no_tip( self, eth_tester, w3, keyfile_account_address ): super().test_gas_price_from_strategy_bypassed_for_dynamic_fee_txn_no_tip( w3, keyfile_account_address, ) @disable_auto_mine def test_eth_send_transaction_default_fees( self, eth_tester, w3, keyfile_account_address ): super().test_eth_send_transaction_default_fees(w3, keyfile_account_address) @disable_auto_mine def test_eth_send_transaction_hex_fees( self, eth_tester, w3, keyfile_account_address ): super().test_eth_send_transaction_hex_fees(w3, keyfile_account_address) @disable_auto_mine def test_eth_send_transaction_no_gas(self, eth_tester, w3, keyfile_account_address): super().test_eth_send_transaction_no_gas(w3, keyfile_account_address) @disable_auto_mine def test_eth_send_transaction_no_max_fee( self, eth_tester, w3, keyfile_account_address ): super().test_eth_send_transaction_no_max_fee(w3, keyfile_account_address) def test_eth_fee_history_with_integer( self, w3: "Web3", empty_block: BlockData ) -> None: super().test_eth_fee_history_with_integer(w3, empty_block) def test_eth_get_balance_with_block_identifier(self, w3: "Web3") -> None: w3.testing.mine() miner_address = w3.eth.get_block(1)["miner"] genesis_balance = w3.eth.get_balance(miner_address, 0) later_balance = w3.eth.get_balance(miner_address, 1) assert is_integer(genesis_balance) assert is_integer(later_balance) assert later_balance > genesis_balance
TestEthereumTesterEthModule
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 66067, "end": 67185 }
class ____(torch.nn.Module): def __init__(self, qengine="fbgemm"): super().__init__() self.qconfig = torch.ao.quantization.get_default_qconfig(qengine) self.conv = torch.nn.Conv2d(3, 5, 3, bias=False).to(dtype=torch.float) self.bn = torch.nn.BatchNorm2d(5).to(dtype=torch.float) self.relu = nn.ReLU(inplace=True) self.quant = QuantStub() self.dequant = DeQuantStub() def forward(self, x): x = self.quant(x) x = self.conv(x) x = self.bn(x) x = self.relu(x) x = self.dequant(x) return x def fuse_model(self): # TODO: remove this check and define two fuse_modules function on this module if self.training: torch.ao.quantization.fuse_modules_qat( self, [["conv", "bn", "relu"]], inplace=True ) else: torch.ao.quantization.fuse_modules( self, [["conv", "bn", "relu"]], inplace=True ) def get_example_inputs(self) -> tuple[Any, ...]: return (torch.rand(1, 3, 5, 5),)
AnnotatedConvBnReLUModel
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 27993, "end": 28667 }
class ____(_MutableDictTestBase, fixtures.MappedTest): @classmethod def define_tables(cls, metadata): MutableDict = cls._type_fixture() mutable_pickle = MutableDict.as_mutable(PickleType) Table( "foo", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("skip", mutable_pickle), Column("data", mutable_pickle), Column("non_mutable_data", PickleType), Column("unrelated_data", String(50)), ) def test_non_mutable(self): self._test_non_mutable()
MutableWithScalarPickleTest
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/top_level.py
{ "start": 144, "end": 191 }
class ____(expr_context): ... # Some comment.
Load
python
pexpect__pexpect
pexpect/popen_spawn.py
{ "start": 396, "end": 6159 }
class ____(SpawnBase): def __init__(self, cmd, timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None, encoding=None, codec_errors='strict', preexec_fn=None): super(PopenSpawn, self).__init__(timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize, logfile=logfile, encoding=encoding, codec_errors=codec_errors) # Note that `SpawnBase` initializes `self.crlf` to `\r\n` # because the default behaviour for a PTY is to convert # incoming LF to `\r\n` (see the `onlcr` flag and # https://stackoverflow.com/a/35887657/5397009). Here we set # it to `os.linesep` because that is what the spawned # application outputs by default and `popen` doesn't translate # anything. if encoding is None: self.crlf = os.linesep.encode ("ascii") else: self.crlf = self.string_type (os.linesep) kwargs = dict(bufsize=0, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, cwd=cwd, preexec_fn=preexec_fn, env=env) if sys.platform == 'win32': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW kwargs['startupinfo'] = startupinfo kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP if isinstance(cmd, string_types) and sys.platform != 'win32': cmd = shlex.split(cmd, posix=os.name == 'posix') self.proc = subprocess.Popen(cmd, **kwargs) self.pid = self.proc.pid self.closed = False self._buf = self.string_type() self._read_queue = Queue() self._read_thread = threading.Thread(target=self._read_incoming) self._read_thread.daemon = True self._read_thread.start() _read_reached_eof = False def read_nonblocking(self, size, timeout): buf = self._buf if self._read_reached_eof: # We have already finished reading. Use up any buffered data, # then raise EOF if buf: self._buf = buf[size:] return buf[:size] else: self.flag_eof = True raise EOF('End Of File (EOF).') if timeout == -1: timeout = self.timeout elif timeout is None: timeout = 1e6 t0 = time.time() while (time.time() - t0) < timeout and size and len(buf) < size: try: incoming = self._read_queue.get_nowait() except Empty: break else: if incoming is None: self._read_reached_eof = True break buf += self._decoder.decode(incoming, final=False) r, self._buf = buf[:size], buf[size:] self._log(r, 'read') return r def _read_incoming(self): """Run in a thread to move output from a pipe to a queue.""" fileno = self.proc.stdout.fileno() while 1: buf = b'' try: buf = os.read(fileno, 1024) except OSError as e: self._log(e, 'read') if not buf: # This indicates we have reached EOF self._read_queue.put(None) return self._read_queue.put(buf) def write(self, s): '''This is similar to send() except that there is no return value. ''' self.send(s) def writelines(self, sequence): '''This calls write() for each element in the sequence. The sequence can be any iterable object producing strings, typically a list of strings. This does not add line separators. There is no return value. ''' for s in sequence: self.send(s) def send(self, s): '''Send data to the subprocess' stdin. Returns the number of bytes written. ''' s = self._coerce_send_string(s) self._log(s, 'send') b = self._encoder.encode(s, final=False) if PY3: return self.proc.stdin.write(b) else: # On Python 2, .write() returns None, so we return the length of # bytes written ourselves. This assumes they all got written. self.proc.stdin.write(b) return len(b) def sendline(self, s=''): '''Wraps send(), sending string ``s`` to child process, with os.linesep automatically appended. Returns number of bytes written. ''' n = self.send(s) return n + self.send(self.linesep) def wait(self): '''Wait for the subprocess to finish. Returns the exit code. ''' status = self.proc.wait() if status >= 0: self.exitstatus = status self.signalstatus = None else: self.exitstatus = None self.signalstatus = -status self.terminated = True return status def kill(self, sig): '''Sends a Unix signal to the subprocess. Use constants from the :mod:`signal` module to specify which signal. ''' if sys.platform == 'win32': if sig in [signal.SIGINT, signal.CTRL_C_EVENT]: sig = signal.CTRL_C_EVENT elif sig in [signal.SIGBREAK, signal.CTRL_BREAK_EVENT]: sig = signal.CTRL_BREAK_EVENT else: sig = signal.SIGTERM os.kill(self.proc.pid, sig) def sendeof(self): '''Closes the stdin pipe from the writing end.''' self.proc.stdin.close()
PopenSpawn
python
Pylons__pyramid
src/pyramid/interfaces.py
{ "start": 37631, "end": 38447 }
class ____(Interface): """An object representing the default CSRF settings to be used for all view configurations which do not explicitly declare their own.""" require_csrf = Attribute( 'Boolean attribute. If ``True``, then CSRF checks will be enabled by ' 'default for the view unless overridden.' ) token = Attribute('The key to be matched in the body of the request.') header = Attribute('The header to be matched with the CSRF token.') safe_methods = Attribute('A set of safe methods that skip CSRF checks.') callback = Attribute('A callback to disable CSRF checks per-request.') allow_no_origin = Attribute( 'Boolean. If false, a request lacking both an ``Origin`` and ' '``Referer`` header will fail the CSRF check.' )
IDefaultCSRFOptions
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/pickleable.py
{ "start": 2577, "end": 2833 }
class ____: def __init__(self, data): self.data = data def __hash__(self): return id(self) def __eq__(self, other): raise NotImplementedError def __ne__(self, other): raise NotImplementedError
BrokenComparable
python
apache__airflow
providers/microsoft/azure/tests/unit/microsoft/azure/sensors/test_msgraph.py
{ "start": 1345, "end": 6793 }
class ____: def test_execute_with_result_processor_with_old_signature(self): status = load_json_from_resources(dirname(__file__), "..", "resources", "status.json") response = mock_json_response(200, *status) with patch_hook_and_request_adapter(response): sensor = MSGraphSensor( task_id="check_workspaces_status", conn_id="powerbi", url="myorg/admin/workspaces/scanStatus/{scanId}", path_parameters={"scanId": "0a1b1bf3-37de-48f7-9863-ed4cda97a9ef"}, result_processor=lambda context, result: result["id"], retry_delay=5, timeout=5, ) with pytest.warns( AirflowProviderDeprecationWarning, match="result_processor signature has changed, result parameter should be defined before context!", ): results, events = execute_operator(sensor) assert sensor.path_parameters == {"scanId": "0a1b1bf3-37de-48f7-9863-ed4cda97a9ef"} assert isinstance(results, str) assert results == "0a1b1bf3-37de-48f7-9863-ed4cda97a9ef" assert len(events) == 3 assert isinstance(events[0], TriggerEvent) assert events[0].payload["status"] == "success" assert events[0].payload["type"] == "builtins.dict" assert events[0].payload["response"] == json.dumps(status[0]) assert isinstance(events[1], TriggerEvent) assert isinstance(events[1].payload, datetime) assert isinstance(events[2], TriggerEvent) assert events[2].payload["status"] == "success" assert events[2].payload["type"] == "builtins.dict" assert events[2].payload["response"] == json.dumps(status[1]) def test_execute_with_result_processor_with_new_signature(self): status = load_json_from_resources(dirname(__file__), "..", "resources", "status.json") response = mock_json_response(200, *status) with patch_hook_and_request_adapter(response): sensor = MSGraphSensor( task_id="check_workspaces_status", conn_id="powerbi", url="myorg/admin/workspaces/scanStatus/{scanId}", path_parameters={"scanId": "0a1b1bf3-37de-48f7-9863-ed4cda97a9ef"}, result_processor=lambda result, **context: result["id"], retry_delay=5, timeout=5, ) results, events = execute_operator(sensor) assert sensor.path_parameters == {"scanId": "0a1b1bf3-37de-48f7-9863-ed4cda97a9ef"} assert isinstance(results, str) assert results == "0a1b1bf3-37de-48f7-9863-ed4cda97a9ef" assert len(events) == 3 assert isinstance(events[0], TriggerEvent) assert events[0].payload["status"] == "success" assert events[0].payload["type"] == "builtins.dict" assert events[0].payload["response"] == json.dumps(status[0]) assert isinstance(events[1], TriggerEvent) assert isinstance(events[1].payload, datetime) assert isinstance(events[2], TriggerEvent) assert events[2].payload["status"] == "success" assert events[2].payload["type"] == "builtins.dict" assert events[2].payload["response"] == json.dumps(status[1]) def test_execute_with_lambda_parameter_and_result_processor_with_new_signature(self): status = load_json_from_resources(dirname(__file__), "..", "resources", "status.json") response = mock_json_response(200, *status) with patch_hook_and_request_adapter(response): sensor = MSGraphSensor( task_id="check_workspaces_status", conn_id="powerbi", url="myorg/admin/workspaces/scanStatus/{scanId}", path_parameters=lambda context, jinja_env: {"scanId": "0a1b1bf3-37de-48f7-9863-ed4cda97a9ef"}, result_processor=lambda result, **context: result["id"], retry_delay=5, timeout=5, ) results, events = execute_operator(sensor) assert sensor.path_parameters == {"scanId": "0a1b1bf3-37de-48f7-9863-ed4cda97a9ef"} assert isinstance(results, str) assert results == "0a1b1bf3-37de-48f7-9863-ed4cda97a9ef" assert len(events) == 3 assert isinstance(events[0], TriggerEvent) assert events[0].payload["status"] == "success" assert events[0].payload["type"] == "builtins.dict" assert events[0].payload["response"] == json.dumps(status[0]) assert isinstance(events[1], TriggerEvent) assert isinstance(events[1].payload, datetime) assert isinstance(events[2], TriggerEvent) assert events[2].payload["status"] == "success" assert events[2].payload["type"] == "builtins.dict" assert events[2].payload["response"] == json.dumps(status[1]) def test_template_fields(self): sensor = MSGraphSensor( task_id="check_workspaces_status", conn_id="powerbi", url="myorg/admin/workspaces/scanStatus/{scanId}", ) for template_field in MSGraphSensor.template_fields: getattr(sensor, template_field)
TestMSGraphSensor
python
PyCQA__pylint
doc/data/messages/t/too-many-ancestors/good.py
{ "start": 0, "end": 185 }
class ____: beaver_tailed: bool can_swim: bool has_beak: bool has_fur: bool has_vertebrae: bool lays_egg: bool protected_specie: bool venomous: bool
Animal
python
tensorflow__tensorflow
tensorflow/python/keras/engine/keras_tensor.py
{ "start": 17376, "end": 18032 }
class ____(KerasTensor): """A specialized KerasTensor representation for `tf.sparse.SparseTensor`s. Specifically, it specializes the conversion to a placeholder in order to maintain dense shape information. """ def _to_placeholder(self): spec = self.type_spec # nest.map_structure loses dense shape information for sparse tensors. # So, we special-case sparse placeholder creation. # This only preserves shape information for top-level sparse tensors; # not for sparse tensors that are nested inside another composite # tensor. return array_ops.sparse_placeholder(dtype=spec.dtype, shape=spec.shape)
SparseKerasTensor
python
ansible__ansible
test/units/modules/utils.py
{ "start": 82, "end": 289 }
class ____(Exception): pass def exit_json(*args, **kwargs): raise AnsibleExitJson(kwargs) def fail_json(*args, **kwargs): kwargs['failed'] = True raise AnsibleFailJson(kwargs)
AnsibleFailJson
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-of-a-path-with-special-roads.py
{ "start": 1322, "end": 2545 }
class ____(object): def minimumCost(self, start, target, specialRoads): """ :type start: List[int] :type target: List[int] :type specialRoads: List[List[int]] :rtype: int """ start, target = tuple(start), tuple(target) adj = collections.defaultdict(list, {target:[]}) for x1, y1, x2, y2, c in specialRoads: adj[x1, y1].append((x2, y2, c)) min_heap = [(0, start)] dist = {start:0} while min_heap: d, (x1, y1) = heapq.heappop(min_heap) if d > dist[x1, y1]: continue if (x1, y1) == target: return d for x2, y2, c in adj[x1, y1]: if not ((x2, y2) not in dist or dist[x2, y2] > d+c): continue dist[x2, y2] = d+c heapq.heappush(min_heap, (dist[x2, y2], (x2, y2))) for x2, y2 in adj.iterkeys(): if not ((x2, y2) not in dist or dist[x2, y2] > d+abs(x2-x1)+abs(y2-y1)): continue dist[x2, y2] = d+abs(x2-x1)+abs(y2-y1) heapq.heappush(min_heap, (dist[x2, y2], (x2, y2))) return -1
Solution2
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/inputs.py
{ "start": 9902, "end": 10312 }
class ____(graphene.InputObjectType): repositoryName = graphene.NonNull(graphene.String) repositoryLocationName = graphene.NonNull(graphene.String) resourceName = graphene.NonNull(graphene.String) class Meta: description = ( """This type represents the fields necessary to identify a top-level resource.""" ) name = "ResourceSelector"
GrapheneResourceSelector
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 98951, "end": 99346 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field( sgqlc.types.non_null(DiscussionOrderField), graphql_name="field" ) direction = sgqlc.types.Field( sgqlc.types.non_null(OrderDirection), graphql_name="direction" )
DiscussionOrder
python
getsentry__sentry
src/sentry/interfaces/contexts.py
{ "start": 6473, "end": 6699 }
class ____(ContextType): type = "os" context_to_tag_mapping = { "": "{os}", "name": "{name}", "rooted": "{rooted}", "build": "{build}", } # build, rooted @contexttype
OsContextType
python
allegroai__clearml
clearml/backend_api/services/v2_9/projects.py
{ "start": 25766, "end": 30118 }
class ____(Request): """ Create a new project :param name: Project name Unique within the company. :type name: str :param description: Project description. :type description: str :param tags: User-defined tags :type tags: Sequence[str] :param system_tags: System tags. This field is reserved for system use, please don't use it. :type system_tags: Sequence[str] :param default_output_destination: The default output destination URL for new tasks under this project :type default_output_destination: str """ _service = "projects" _action = "create" _version = "2.9" _schema = { "definitions": {}, "properties": { "default_output_destination": { "description": "The default output destination URL for new tasks under this project", "type": "string", }, "description": {"description": "Project description. ", "type": "string"}, "name": { "description": "Project name Unique within the company.", "type": "string", }, "system_tags": { "description": "System tags. This field is reserved for system use, please don't use it.", "items": {"type": "string"}, "type": "array", }, "tags": { "description": "User-defined tags", "items": {"type": "string"}, "type": "array", }, }, "required": ["name", "description"], "type": "object", } def __init__( self, name: str, description: str, tags: Optional[List[str]] = None, system_tags: Optional[List[str]] = None, default_output_destination: Optional[str] = None, **kwargs: Any ) -> None: super(CreateRequest, self).__init__(**kwargs) self.name = name self.description = description self.tags = tags self.system_tags = system_tags self.default_output_destination = default_output_destination @schema_property("name") def name(self) -> str: return self._property_name @name.setter def name(self, value: str) -> None: if value is None: self._property_name = None return self.assert_isinstance(value, "name", six.string_types) self._property_name = value @schema_property("description") def description(self) -> str: return self._property_description @description.setter def description(self, value: str) -> None: if value is None: self._property_description = None return self.assert_isinstance(value, "description", six.string_types) self._property_description = value @schema_property("tags") def tags(self) -> Optional[List[str]]: return self._property_tags @tags.setter def tags(self, value: Optional[List[str]]) -> None: if value is None: self._property_tags = None return self.assert_isinstance(value, "tags", (list, tuple)) self.assert_isinstance(value, "tags", six.string_types, is_array=True) self._property_tags = value @schema_property("system_tags") def system_tags(self) -> Optional[List[str]]: return self._property_system_tags @system_tags.setter def system_tags(self, value: Optional[List[str]]) -> None: if value is None: self._property_system_tags = None return self.assert_isinstance(value, "system_tags", (list, tuple)) self.assert_isinstance(value, "system_tags", six.string_types, is_array=True) self._property_system_tags = value @schema_property("default_output_destination") def default_output_destination(self) -> Optional[str]: return self._property_default_output_destination @default_output_destination.setter def default_output_destination(self, value: Optional[str]) -> None: if value is None: self._property_default_output_destination = None return self.assert_isinstance(value, "default_output_destination", six.string_types) self._property_default_output_destination = value
CreateRequest
python
ray-project__ray
python/ray/dashboard/modules/reporter/reporter_head.py
{ "start": 2232, "end": 35778 }
class ____(SubprocessModule): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._ray_config = None # TODO(fyrestone): Avoid using ray.state in dashboard, it's not # asynchronous and will lead to low performance. ray disconnect() # will be hang when the ray.state is connected and the GCS is exit. # Please refer to: https://github.com/ray-project/ray/issues/16328 self.service_discovery = PrometheusServiceDiscoveryWriter( self.gcs_address, self.temp_dir ) self._state_api = None self._executor = ThreadPoolExecutor( max_workers=RAY_DASHBOARD_REPORTER_HEAD_TPE_MAX_WORKERS, thread_name_prefix="reporter_head_executor", ) # Fetched from GCS only once on startup in run(). It's static throughout the # the cluster's lifetime. self.cluster_metadata = None self._health_checker = HealthChecker(self.gcs_client) @routes.get("/api/v0/cluster_metadata") async def get_cluster_metadata(self, req): return dashboard_optional_utils.rest_response( status_code=dashboard_utils.HTTPStatusCode.OK, message="", **self.cluster_metadata, ) @routes.get("/api/cluster_status") async def get_cluster_status(self, req): """Returns status information about the cluster. Currently contains two fields: autoscaling_status (str)-- a status message from the autoscaler. autoscaling_error (str)-- an error message from the autoscaler if anything has gone wrong during autoscaling. These fields are both read from the GCS, it's expected that the autoscaler writes them there. """ # TODO(rickyx): We should be able to get the cluster status from the # autoscaler directly with V2. And we should be able to return structured data # rather than a string. return_formatted_output = req.query.get("format", "0") == "1" (legacy_status, formatted_status_string, error) = await asyncio.gather( *[ self.gcs_client.async_internal_kv_get( key.encode(), namespace=None, timeout=GCS_RPC_TIMEOUT_SECONDS ) for key in [ DEBUG_AUTOSCALING_STATUS_LEGACY, DEBUG_AUTOSCALING_STATUS, DEBUG_AUTOSCALING_ERROR, ] ] ) formatted_status = ( json.loads(formatted_status_string.decode()) if formatted_status_string else {} ) if not return_formatted_output: return dashboard_optional_utils.rest_response( status_code=dashboard_utils.HTTPStatusCode.OK, message="Got cluster status.", autoscaling_status=legacy_status.decode() if legacy_status else None, autoscaling_error=error.decode() if error else None, cluster_status=formatted_status if formatted_status else None, ) else: return dashboard_optional_utils.rest_response( status_code=dashboard_utils.HTTPStatusCode.OK, message="Got formatted cluster status.", cluster_status=debug_status( formatted_status_string, error, address=self.gcs_address ), ) async def get_task_ids_running_in_a_worker(self, worker_id: str) -> List[str]: """ Retrieves the task IDs of running tasks associated with a specific worker. Args: worker_id: The ID of the worker. Returns: List[str]: A list containing the task IDs of all the running tasks associated with the worker. """ option = ListApiOptions( filters=[("worker_id", "=", worker_id), ("state", "=", "RUNNING")], detail=True, timeout=10, ) # Call the state API to get all tasks in a worker tasks_in_a_worker_result = await self._state_api.list_tasks(option=option) tasks_in_a_worker = tasks_in_a_worker_result.result # Get task_id from each task in a worker task_ids_in_a_worker = [ task.get("task_id") for task in tasks_in_a_worker if task and "task_id" in task ] return task_ids_in_a_worker async def get_worker_details_for_running_task( self, task_id: str, attempt_number: int ) -> Tuple[Optional[int], Optional[str]]: """Retrieves worker details for a specific task and attempt number. Args: task_id: The ID of the task. attempt_number: The attempt number of the task. Returns: Tuple[Optional[int], Optional[str]]: A tuple containing the worker's PID (process ID), and worker's ID. Raises: ValueError: If the task attempt is not running or the state API is not initialized. """ if self._state_api is None: raise ValueError("The state API is not initialized yet. Please retry.") option = ListApiOptions( filters=[ ("task_id", "=", task_id), ("attempt_number", "=", attempt_number), ], detail=True, timeout=10, ) result = await self._state_api.list_tasks(option=option) tasks = result.result if not tasks: return None, None pid = tasks[0]["worker_pid"] worker_id = tasks[0]["worker_id"] state = tasks[0]["state"] if state != "RUNNING": raise ValueError( f"The task attempt is not running: the current state is {state}." ) return pid, worker_id @routes.get("/task/traceback") async def get_task_traceback( self, req: aiohttp.web.Request ) -> aiohttp.web.Response: """Retrieves the traceback information for a specific task. Note that one worker process works on one task at a time or one worker works on multiple async tasks. Params: task_id: The ID of the task. attempt_number: The attempt number of the task. node_id: The ID of the node. Returns: aiohttp.web.Response: The HTTP response containing the traceback information. Raises: ValueError: If the "task_id" parameter is missing in the request query. ValueError: If the "attempt_number" parameter is missing in the request query. ValueError: If the worker begins working on another task during the traceback retrieval. aiohttp.web.HTTPInternalServerError: If there is an internal server error during the traceback retrieval. """ if "task_id" not in req.query: raise ValueError("task_id is required") if "attempt_number" not in req.query: raise ValueError("task's attempt number is required") if "node_id" not in req.query: raise ValueError("node_id is required") task_id = req.query.get("task_id") attempt_number = req.query.get("attempt_number") node_id_hex = req.query.get("node_id") addrs = await self._get_stub_address_by_node_id(NodeID.from_hex(node_id_hex)) if not addrs: raise aiohttp.web.HTTPInternalServerError( text=f"Failed to get agent address for node {node_id_hex}" ) node_id, ip, http_port, grpc_port = addrs reporter_stub = self._make_stub(build_address(ip, grpc_port)) # Default not using `--native` for profiling native = req.query.get("native", False) == "1" try: (pid, _) = await self.get_worker_details_for_running_task( task_id, attempt_number ) except ValueError as e: raise aiohttp.web.HTTPInternalServerError(text=str(e)) logger.info( "Sending stack trace request to {}:{} with native={}".format( ip, pid, native ) ) reply = await reporter_stub.GetTraceback( reporter_pb2.GetTracebackRequest(pid=pid, native=native) ) """ In order to truly confirm whether there are any other tasks running during the profiling, we need to retrieve all tasks that are currently running or have finished, and then parse the task events (i.e., their start and finish times) to check for any potential overlap. However, this process can be quite extensive, so here we will make our best efforts to check for any overlapping tasks. Therefore, we will check if the task is still running """ try: (_, worker_id) = await self.get_worker_details_for_running_task( task_id, attempt_number ) except ValueError as e: raise aiohttp.web.HTTPInternalServerError(text=str(e)) if not reply.success: return aiohttp.web.HTTPInternalServerError(text=reply.output) logger.info("Returning stack trace, size {}".format(len(reply.output))) task_ids_in_a_worker = await self.get_task_ids_running_in_a_worker(worker_id) return aiohttp.web.Response( text=( WARNING_FOR_MULTI_TASK_IN_A_WORKER + str(task_ids_in_a_worker) + "\n" + reply.output if len(task_ids_in_a_worker) > 1 else reply.output ) ) @routes.get("/task/cpu_profile") async def get_task_cpu_profile( self, req: aiohttp.web.Request ) -> aiohttp.web.Response: """Retrieves the CPU profile for a specific task. Note that one worker process works on one task at a time or one worker works on multiple async tasks. Returns: aiohttp.web.Response: The HTTP response containing the CPU profile data. Raises: ValueError: If the "task_id" parameter is missing in the request query. ValueError: If the "attempt_number" parameter is missing in the request query. ValueError: If the maximum duration allowed is exceeded. ValueError: If the worker begins working on another task during the profile retrieval. aiohttp.web.HTTPInternalServerError: If there is an internal server error during the profile retrieval. aiohttp.web.HTTPInternalServerError: If the CPU Flame Graph information for the task is not found. """ if "task_id" not in req.query: raise ValueError("task_id is required") if "attempt_number" not in req.query: raise ValueError("task's attempt number is required") if "node_id" not in req.query: raise ValueError("node_id is required") task_id = req.query.get("task_id") attempt_number = req.query.get("attempt_number") node_id_hex = req.query.get("node_id") duration_s = int(req.query.get("duration", 5)) if duration_s > 60: raise ValueError(f"The max duration allowed is 60 seconds: {duration_s}.") format = req.query.get("format", "flamegraph") # Default not using `--native` for profiling native = req.query.get("native", False) == "1" addrs = await self._get_stub_address_by_node_id(NodeID.from_hex(node_id_hex)) if not addrs: raise aiohttp.web.HTTPInternalServerError( text=f"Failed to get agent address for node {node_id_hex}" ) node_id, ip, http_port, grpc_port = addrs reporter_stub = self._make_stub(build_address(ip, grpc_port)) try: (pid, _) = await self.get_worker_details_for_running_task( task_id, attempt_number ) except ValueError as e: raise aiohttp.web.HTTPInternalServerError(text=str(e)) logger.info( f"Sending CPU profiling request to {build_address(ip, grpc_port)}, pid {pid}, for {task_id} with native={native}" ) reply = await reporter_stub.CpuProfiling( reporter_pb2.CpuProfilingRequest( pid=pid, duration=duration_s, format=format, native=native ) ) """ In order to truly confirm whether there are any other tasks running during the profiling, we need to retrieve all tasks that are currently running or have finished, and then parse the task events (i.e., their start and finish times) to check for any potential overlap. However, this process can be quite extensive, so here we will make our best efforts to check for any overlapping tasks. Therefore, we will check if the task is still running """ try: (_, worker_id) = await self.get_worker_details_for_running_task( task_id, attempt_number ) except ValueError as e: raise aiohttp.web.HTTPInternalServerError(text=str(e)) if not reply.success: return aiohttp.web.HTTPInternalServerError(text=reply.output) logger.info("Returning profiling response, size {}".format(len(reply.output))) task_ids_in_a_worker = await self.get_task_ids_running_in_a_worker(worker_id) return aiohttp.web.Response( body=( '<p style="color: #E37400;">{} {} </br> </p> </br>'.format( EMOJI_WARNING, WARNING_FOR_MULTI_TASK_IN_A_WORKER + str(task_ids_in_a_worker), ) + SVG_STYLE + (reply.output) if len(task_ids_in_a_worker) > 1 else SVG_STYLE + reply.output ), headers={"Content-Type": "text/html"}, ) @routes.get("/worker/traceback") async def get_traceback(self, req: aiohttp.web.Request) -> aiohttp.web.Response: """Retrieves the traceback information for a specific worker. Params: pid: Required. The PID of the worker. ip or node_id: Required. The IP address or hex ID of the node. """ pid = req.query.get("pid") ip = req.query.get("ip") node_id_hex = req.query.get("node_id") if not pid: raise ValueError("pid is required") if not node_id_hex and not ip: raise ValueError("ip or node_id is required") if node_id_hex: addrs = await self._get_stub_address_by_node_id( NodeID.from_hex(node_id_hex) ) if not addrs: raise aiohttp.web.HTTPInternalServerError( text=f"Failed to get agent address for node at node_id {node_id_hex}" ) else: addrs = await self._get_stub_address_by_ip(ip) if not addrs: raise aiohttp.web.HTTPInternalServerError( text=f"Failed to get agent address for node at IP {ip}" ) node_id, ip, http_port, grpc_port = addrs reporter_stub = self._make_stub(build_address(ip, grpc_port)) # Default not using `--native` for profiling native = req.query.get("native", False) == "1" logger.info( f"Sending stack trace request to {build_address(ip, grpc_port)}, pid {pid}, with native={native}" ) pid = int(pid) reply = await reporter_stub.GetTraceback( reporter_pb2.GetTracebackRequest(pid=pid, native=native) ) if reply.success: logger.info("Returning stack trace, size {}".format(len(reply.output))) return aiohttp.web.Response(text=reply.output) else: return aiohttp.web.HTTPInternalServerError(text=reply.output) @routes.get("/worker/cpu_profile") async def cpu_profile(self, req: aiohttp.web.Request) -> aiohttp.web.Response: """Retrieves the CPU profile for a specific worker. Params: pid: Required. The PID of the worker. ip or node_id: Required. The IP address or hex ID of the node. duration: Optional. Duration in seconds for profiling (default: 5, max: 60). format: Optional. Output format (default: "flamegraph"). native: Optional. Whether to use native profiling (default: false). Raises: ValueError: If pid is not provided. ValueError: If ip or node_id is not provided. ValueError: If duration exceeds 60 seconds. aiohttp.web.HTTPInternalServerError: If there is an internal server error during the profile retrieval. """ pid = req.query.get("pid") ip = req.query.get("ip") node_id_hex = req.query.get("node_id") if not pid: raise ValueError("pid is required") if not node_id_hex and not ip: raise ValueError("ip or node_id is required") if node_id_hex: addrs = await self._get_stub_address_by_node_id( NodeID.from_hex(node_id_hex) ) if not addrs: raise aiohttp.web.HTTPInternalServerError( text=f"Failed to get agent address for node at node_id {node_id_hex}" ) else: addrs = await self._get_stub_address_by_ip(ip) if not addrs: raise aiohttp.web.HTTPInternalServerError( text=f"Failed to get agent address for node at IP {ip}" ) node_id, ip, http_port, grpc_port = addrs reporter_stub = self._make_stub(build_address(ip, grpc_port)) pid = int(pid) duration_s = int(req.query.get("duration", 5)) if duration_s > 60: raise ValueError(f"The max duration allowed is 60 seconds: {duration_s}.") format = req.query.get("format", "flamegraph") # Default not using `--native` for profiling native = req.query.get("native", False) == "1" logger.info( f"Sending CPU profiling request to {build_address(ip, grpc_port)}, pid {pid}, with native={native}" ) reply = await reporter_stub.CpuProfiling( reporter_pb2.CpuProfilingRequest( pid=pid, duration=duration_s, format=format, native=native ) ) if reply.success: logger.info( "Returning profiling response, size {}".format(len(reply.output)) ) return aiohttp.web.Response( body=reply.output, headers={ "Content-Type": ( "image/svg+xml" if format == "flamegraph" else "text/plain" ) }, ) else: return aiohttp.web.HTTPInternalServerError(text=reply.output) @routes.get("/worker/gpu_profile") async def gpu_profile(self, req: aiohttp.web.Request) -> aiohttp.web.Response: """Retrieves the Torch GPU profile trace for a specific worker. This is a Torch-specific API. It is not supported for other frameworks. Params: req: A request with the following query parameters: pid: Required. The PID of the GPU training worker. ip or node_id: Required. The IP address or hex ID of the node where the GPU training worker is running. num_iterations: Number of training steps for profiling. Defaults to 4 This is the number of calls to the torch Optimizer.step(). Returns: A redirect to the log API to download the GPU profiling trace file. Raises: aiohttp.web.HTTPInternalServerError: if one of the following happens: (1) The GPU profiling dependencies are not installed on the target node. (2) The target node doesn't have GPUs. (3) The GPU profiling fails or times out. The output will contain a description of the error. For example, trying to profile a non-Torch training process will result in an error. """ pid = req.query.get("pid") ip = req.query.get("ip") node_id_hex = req.query.get("node_id") if not pid: raise ValueError("pid is required") if not node_id_hex and not ip: raise ValueError("ip or node_id is required") if node_id_hex: addrs = await self._get_stub_address_by_node_id( NodeID.from_hex(node_id_hex) ) if not addrs: raise aiohttp.web.HTTPInternalServerError( text=f"Failed to get agent address for node at node_id {node_id_hex}, pid {pid}" ) else: addrs = await self._get_stub_address_by_ip(ip) if not addrs: raise aiohttp.web.HTTPInternalServerError( text=f"Failed to get agent address for node at IP {ip}, pid {pid}" ) node_id, ip, http_port, grpc_port = addrs reporter_stub = self._make_stub(build_address(ip, grpc_port)) # Profile for num_iterations training steps (calls to optimizer.step()) num_iterations = int(req.query.get("num_iterations", 4)) logger.info( f"Sending GPU profiling request to {build_address(ip, grpc_port)}, pid {pid}. " f"Profiling for {num_iterations} training steps." ) reply = await reporter_stub.GpuProfiling( reporter_pb2.GpuProfilingRequest( pid=int(pid), num_iterations=num_iterations ) ) if not reply.success: return aiohttp.web.HTTPInternalServerError(text=reply.output) logger.info("Returning profiling response, size {}".format(len(reply.output))) filepath = str(reply.output) download_filename = Path(filepath).name query = urlencode( { "node_ip": ip, "filename": filepath, "download_filename": download_filename, "lines": "-1", } ) redirect_url = f"/api/v0/logs/file?{query}" raise aiohttp.web.HTTPFound(redirect_url) @routes.get("/memory_profile") async def memory_profile(self, req: aiohttp.web.Request) -> aiohttp.web.Response: """Retrieves the memory profile for a specific worker or task. Note that for tasks, one worker process works on one task at a time or one worker works on multiple async tasks. Returns: aiohttp.web.Response: The HTTP response containing the memory profile data. Params (1): pid: The PID of the worker. ip or node_id: The IP address or hex ID of the node. Params (2): task_id: The ID of the task. attempt_number: The attempt number of the task. node_id: The ID of the node. Raises: aiohttp.web.HTTPInternalServerError: If no stub found from the given IP address or hex ID value aiohttp.web.HTTPInternalServerError: If the "task_id" parameter exists but either "attempt_number" or "node id" is missing in the request query. aiohttp.web.HTTPInternalServerError: If the maximum duration allowed is exceeded. aiohttp.web.HTTPInternalServerError: If requesting task profiling for the worker begins working on another task during the profile retrieval. aiohttp.web.HTTPInternalServerError: If there is an internal server error during the profile retrieval. """ is_task = "task_id" in req.query # Either is_task or not, we need to get ip and grpc_port. if is_task: if "attempt_number" not in req.query: return aiohttp.web.HTTPInternalServerError( text=( "Failed to execute task profiling: " "task's attempt number is required" ) ) if "node_id" not in req.query: return aiohttp.web.HTTPInternalServerError( text=( "Failed to execute task profiling: " "task's node id is required" ) ) task_id = req.query.get("task_id") attempt_number = req.query.get("attempt_number") try: (pid, _) = await self.get_worker_details_for_running_task( task_id, attempt_number ) except ValueError as e: raise aiohttp.web.HTTPInternalServerError(text=str(e)) node_id_hex = req.query.get("node_id") addrs = await self._get_stub_address_by_node_id( NodeID.from_hex(node_id_hex) ) if not addrs: return aiohttp.web.HTTPInternalServerError( text=f"Failed to execute: no agent address found for node {node_id_hex}" ) _, ip, _, grpc_port = addrs else: pid = int(req.query["pid"]) ip = req.query.get("ip") node_id_hex = req.query.get("node_id") if not node_id_hex and not ip: raise ValueError("ip or node_id is required") if node_id_hex: addrs = await self._get_stub_address_by_node_id( NodeID.from_hex(node_id_hex) ) if not addrs: return aiohttp.web.HTTPInternalServerError( text=f"Failed to execute: no agent address found for node {node_id_hex}" ) _, ip, _, grpc_port = addrs else: addrs = await self._get_stub_address_by_ip(ip) if not addrs: return aiohttp.web.HTTPInternalServerError( text=f"Failed to execute: no agent address found for node IP {ip}" ) _, ip, _, grpc_port = addrs assert pid is not None ip_port = build_address(ip, grpc_port) duration_s = int(req.query.get("duration", 10)) # Default not using `--native`, `--leaks` and `--format` for profiling format = req.query.get("format", "flamegraph") native = req.query.get("native", False) == "1" leaks = req.query.get("leaks", False) == "1" trace_python_allocators = req.query.get("trace_python_allocators", False) == "1" reporter_stub = self._make_stub(ip_port) logger.info( f"Retrieving memory profiling request to {build_address(ip, grpc_port)}, pid {pid}, with native={native}" ) reply = await reporter_stub.MemoryProfiling( reporter_pb2.MemoryProfilingRequest( pid=pid, format=format, leaks=leaks, duration=duration_s, native=native, trace_python_allocators=trace_python_allocators, ) ) task_ids_in_a_worker = None warning = reply.warning if reply.warning else "" if is_task: """ In order to truly confirm whether there are any other tasks running during the profiling, Ray needs to retrieve all tasks that are currently running or have finished, and then parse the task events (i.e., their start and finish times) to check for any potential overlap. However, this process can be quite extensive, so Ray makes our best efforts to check for any overlapping tasks. Therefore, Ray checks if the task is still running. """ try: (_, worker_id) = await self.get_worker_details_for_running_task( task_id, attempt_number ) except ValueError as e: raise aiohttp.web.HTTPInternalServerError(text=str(e)) task_ids_in_a_worker = await self.get_task_ids_running_in_a_worker( worker_id ) if len(task_ids_in_a_worker) > 1: warning += ( "\n" + WARNING_FOR_MULTI_TASK_IN_A_WORKER + str(task_ids_in_a_worker) ) if not reply.success: return aiohttp.web.HTTPInternalServerError(text=reply.output) logger.info("Returning profiling response, size {}".format(len(reply.output))) return aiohttp.web.Response( body=( '<p style="color: #E37400;">{} {} </br> </p> </br>'.format( EMOJI_WARNING, warning ) + (reply.output) if warning != "" else reply.output ), headers={"Content-Type": "text/html"}, ) @routes.get("/api/gcs_healthz") async def health_check(self, req: aiohttp.web.Request) -> aiohttp.web.Response: try: alive = await self._health_checker.check_gcs_liveness() if alive is True: return aiohttp.web.Response( text="success", content_type="application/text", ) except Exception as e: return aiohttp.web.HTTPServiceUnavailable( reason=f"Health check failed: {e}" ) return aiohttp.web.HTTPServiceUnavailable(reason="Health check failed") @routes.get("/api/prometheus/sd") async def prometheus_service_discovery(self, req) -> aiohttp.web.Response: """ Expose Prometheus metrics targets through HTTP Service Discovery. """ content = self.service_discovery.get_latest_service_discovery_content() if not isinstance(content, list): error_message = "service discovery error: content is not a list" logger.warning(error_message) return aiohttp.web.json_response( {"error": error_message}, status=dashboard_utils.HTTPStatusCode.INTERNAL_ERROR, headers={"Cache-Control": "no-store"}, ) return aiohttp.web.Response( text=json.dumps(content), content_type="application/json", charset="utf-8", status=dashboard_utils.HTTPStatusCode.OK, headers={"Cache-Control": "no-store"}, ) async def _get_stub_address_by_node_id( self, node_id: NodeID ) -> Optional[Tuple[NodeID, str, int, int]]: """ Given a NodeID, get agent port from InternalKV. returns a tuple of (ip, http_port, grpc_port). If not found, return None. """ agent_addr_json = await self.gcs_client.async_internal_kv_get( f"{dashboard_consts.DASHBOARD_AGENT_ADDR_NODE_ID_PREFIX}{node_id.hex()}".encode(), namespace=KV_NAMESPACE_DASHBOARD, timeout=GCS_RPC_TIMEOUT_SECONDS, ) if not agent_addr_json: return None ip, http_port, grpc_port = json.loads(agent_addr_json) return node_id, ip, http_port, grpc_port async def _get_stub_address_by_ip( self, ip: str ) -> Optional[Tuple[str, str, int, int]]: agent_addr_json = await self.gcs_client.async_internal_kv_get( f"{dashboard_consts.DASHBOARD_AGENT_ADDR_IP_PREFIX}{ip}".encode(), namespace=KV_NAMESPACE_DASHBOARD, timeout=GCS_RPC_TIMEOUT_SECONDS, ) if not agent_addr_json: return None node_id, http_port, grpc_port = json.loads(agent_addr_json) return NodeID.from_hex(node_id), ip, http_port, grpc_port def _make_stub( self, ip_port: str ) -> Optional[reporter_pb2_grpc.ReporterServiceStub]: options = GLOBAL_GRPC_OPTIONS channel = init_grpc_channel(ip_port, options=options, asynchronous=True) return reporter_pb2_grpc.ReporterServiceStub(channel) async def run(self): await super().run() self._state_api_data_source_client = StateDataSourceClient( self.aiogrpc_gcs_channel, self.gcs_client ) # Set up the state API in order to fetch task information. # This is only used to get task info. If we have Task APIs in GcsClient we can # remove this. # TODO(ryw): unify the StateAPIManager in reporter_head and state_head. self._state_api = StateAPIManager( self._state_api_data_source_client, self._executor, ) # Need daemon True to avoid dashboard hangs at exit. self.service_discovery.daemon = True self.service_discovery.start() cluster_metadata = await self.gcs_client.async_internal_kv_get( CLUSTER_METADATA_KEY, namespace=KV_NAMESPACE_CLUSTER, ) self.cluster_metadata = json.loads(cluster_metadata.decode("utf-8"))
ReportHead
python
kamyu104__LeetCode-Solutions
Python/stepping-numbers.py
{ "start": 856, "end": 1539 }
class ____(object): def countSteppingNumbers(self, low, high): """ :type low: int :type high: int :rtype: List[int] """ result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for i in xrange(1, high): if result[-1] >= high: break d1 = result[i]%10 - 1 if d1 >= 0: result.append(result[i]*10 + d1) d2 = result[i]%10 + 1 if d2 <= 9: result.append(result[i]*10 + d2) result.append(float("inf")) lit = bisect.bisect_left(result, low) rit = bisect.bisect_right(result, high) return result[lit:rit]
Solution2
python
tiangolo__fastapi
docs_src/header_param_models/tutorial002_pv1_py39.py
{ "start": 112, "end": 434 }
class ____(BaseModel): class Config: extra = "forbid" host: str save_data: bool if_modified_since: Union[str, None] = None traceparent: Union[str, None] = None x_tag: list[str] = [] @app.get("/items/") async def read_items(headers: CommonHeaders = Header()): return headers
CommonHeaders
python
scrapy__scrapy
tests/test_spidermiddleware_referer.py
{ "start": 28546, "end": 31740 }
class ____: def test_valid_name(self): for s, p in [ (POLICY_SCRAPY_DEFAULT, DefaultReferrerPolicy), (POLICY_NO_REFERRER, NoReferrerPolicy), (POLICY_NO_REFERRER_WHEN_DOWNGRADE, NoReferrerWhenDowngradePolicy), (POLICY_SAME_ORIGIN, SameOriginPolicy), (POLICY_ORIGIN, OriginPolicy), (POLICY_STRICT_ORIGIN, StrictOriginPolicy), (POLICY_ORIGIN_WHEN_CROSS_ORIGIN, OriginWhenCrossOriginPolicy), (POLICY_STRICT_ORIGIN_WHEN_CROSS_ORIGIN, StrictOriginWhenCrossOriginPolicy), (POLICY_UNSAFE_URL, UnsafeUrlPolicy), ]: settings = Settings({"REFERRER_POLICY": s}) mw = RefererMiddleware(settings) assert mw.default_policy == p def test_valid_name_casevariants(self): for s, p in [ (POLICY_SCRAPY_DEFAULT, DefaultReferrerPolicy), (POLICY_NO_REFERRER, NoReferrerPolicy), (POLICY_NO_REFERRER_WHEN_DOWNGRADE, NoReferrerWhenDowngradePolicy), (POLICY_SAME_ORIGIN, SameOriginPolicy), (POLICY_ORIGIN, OriginPolicy), (POLICY_STRICT_ORIGIN, StrictOriginPolicy), (POLICY_ORIGIN_WHEN_CROSS_ORIGIN, OriginWhenCrossOriginPolicy), (POLICY_STRICT_ORIGIN_WHEN_CROSS_ORIGIN, StrictOriginWhenCrossOriginPolicy), (POLICY_UNSAFE_URL, UnsafeUrlPolicy), ]: settings = Settings({"REFERRER_POLICY": s.upper()}) mw = RefererMiddleware(settings) assert mw.default_policy == p def test_invalid_name(self): settings = Settings({"REFERRER_POLICY": "some-custom-unknown-policy"}) with pytest.raises(RuntimeError): RefererMiddleware(settings) def test_multiple_policy_tokens(self): # test parsing without space(s) after the comma settings1 = Settings( { "REFERRER_POLICY": ( f"some-custom-unknown-policy," f"{POLICY_SAME_ORIGIN}," f"{POLICY_STRICT_ORIGIN_WHEN_CROSS_ORIGIN}," f"another-custom-unknown-policy" ) } ) mw1 = RefererMiddleware(settings1) assert mw1.default_policy == StrictOriginWhenCrossOriginPolicy # test parsing with space(s) after the comma settings2 = Settings( { "REFERRER_POLICY": ( f"{POLICY_STRICT_ORIGIN_WHEN_CROSS_ORIGIN}," f" another-custom-unknown-policy," f" {POLICY_UNSAFE_URL}" ) } ) mw2 = RefererMiddleware(settings2) assert mw2.default_policy == UnsafeUrlPolicy def test_multiple_policy_tokens_all_invalid(self): settings = Settings( { "REFERRER_POLICY": ( "some-custom-unknown-policy," "another-custom-unknown-policy," "yet-another-custom-unknown-policy" ) } ) with pytest.raises(RuntimeError): RefererMiddleware(settings)
TestSettingsPolicyByName
python
geekcomputers__Python
Merge_linked_list.py
{ "start": 234, "end": 2422 }
class ____: # Function to initialize head def __init__(self): self.head = None self.tail = None # Method to print linked list def printList(self): temp = self.head while temp: print(temp.data, end="->") temp = temp.next # Function to add of node at the end. def append(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node self.tail = new_node return self.tail.next = new_node self.tail = self.tail.next # Function to merge two sorted linked list. def mergeLists(head1, head2): # create a temp node NULL temp = None # List1 is empty then return List2 if head1 is None: return head2 # if List2 is empty then return List1 if head2 is None: return head1 # If List1's data is smaller or # equal to List2's data if head1.data <= head2.data: # assign temp to List1's data temp = head1 # Again check List1's data is smaller or equal List2's # data and call mergeLists function. temp.next = mergeLists(head1.next, head2) else: # If List2's data is greater than or equal List1's # data assign temp to head2 temp = head2 # Again check List2's data is greater or equal List's # data and call mergeLists function. temp.next = mergeLists(head1, head2.next) # return the temp list. return temp # Driver Function if __name__ == "__main__": # Create linked list : # 10->20->30->40->50 list1 = LinkedList() list1.append(10) list1.append(20) list1.append(30) list1.append(40) list1.append(50) # Create linked list 2 : # 5->15->18->35->60 list2 = LinkedList() list2.append(5) list2.append(15) list2.append(18) list2.append(35) list2.append(60) # Create linked list 3 list3 = LinkedList() # Merging linked list 1 and linked list 2 # in linked list 3 list3.head = mergeLists(list1.head, list2.head) print(" Merged Linked List is : ", end="") list3.printList()
LinkedList
python
langchain-ai__langchain
libs/partners/qdrant/tests/integration_tests/common.py
{ "start": 2188, "end": 3337 }
class ____(SparseEmbeddings): """Fake sparse embeddings which remembers all the texts seen so far "to return consistent vectors for the same texts. """ def __init__(self, dimensionality: int = 25) -> None: self.known_texts: list[str] = [] self.dimensionality = dimensionality def embed_documents(self, texts: list[str]) -> list[SparseVector]: """Return consistent embeddings for each text seen so far.""" out_vectors = [] for text in texts: if text not in self.known_texts: self.known_texts.append(text) index = self.known_texts.index(text) indices = [i + index for i in range(self.dimensionality)] values = [1.0] * (self.dimensionality - 1) + [float(index)] out_vectors.append(SparseVector(indices=indices, values=values)) return out_vectors def embed_query(self, text: str) -> SparseVector: """Return consistent embeddings for the text, if seen before, or a constant one if the text is unknown. """ return self.embed_documents([text])[0]
ConsistentFakeSparseEmbeddings
python
pytorch__pytorch
torch/_inductor/cache.py
{ "start": 1813, "end": 7473 }
class ____(Cache[Key, Value]): """ In-memory cache implementation using a dictionary and thread lock. """ def __init__(self: Self) -> None: """ Initialize an empty in-memory cache. """ self._cache: dict[Key, Value] = {} self._lock: Lock = Lock() def get(self: Self, key: Key) -> Value | None: """ Retrieve a value from the cache. Args: key (Key): The key to look up. Returns: Value | None: The cached value if present, else None. """ with self._lock: if (value := self._cache.get(key)) is not None: return value return None def insert(self: Self, key: Key, value: Value) -> bool: """ Insert a value into the cache. Args: key (Key): The key to insert. value (Value): The value to associate with the key. Returns: bool: True if the value was inserted, False if the key already exists. """ with self._lock: if key in self._cache: # no overwrites for insert! return False self._cache[key] = value return True @classmethod def from_env_var(cls, env_var: str) -> Self: """ Create an in-memory cache from an environment variable. Args: env_var (str): Name of the environment variable containing cache data. Returns: InMemoryCache: An instance populated from the environment variable. Raises: CacheError: If the environment variable is malformed or contains invalid data. """ cache = cls() if (env_val := getenv(env_var)) is None: # env_var doesn't exist = empty cache return cache for kv_pair in env_val.split(";"): # ignore whitespace prefix/suffix kv_pair = kv_pair.strip() if not kv_pair: # kv_pair could be '' if env_val is '' or has ; suffix continue try: # keys and values should be comma separated key_bytes_repr, value_bytes_repr = kv_pair.split(",", 1) except ValueError as err: raise CacheError( f"Malformed kv_pair {kv_pair!r} from env_var {env_var!r}, likely missing comma separator." ) from err # ignore whitespace prefix/suffix, again key_bytes_repr, value_bytes_repr = ( key_bytes_repr.strip(), value_bytes_repr.strip(), ) try: # check that key_bytes_str is an actual, legitimate encoding key_bytes = literal_eval(key_bytes_repr) except (ValueError, SyntaxError) as err: raise CacheError( f"Malformed key_bytes_repr {key_bytes_repr!r} in kv_pair {kv_pair!r}, encoding is invalid." ) from err try: # check that value_bytes_str is an actual, legitimate encoding value_bytes = literal_eval(value_bytes_repr) except (ValueError, SyntaxError) as err: raise CacheError( f"Malformed value_bytes_repr {value_bytes_repr!r} in kv_pair {kv_pair!r}, encoding is invalid." ) from err try: key = pickle.loads(key_bytes) except pickle.UnpicklingError as err: raise CacheError( f"Malformed key_bytes_repr {key_bytes_repr!r} in kv_pair {kv_pair!r}, not un-pickle-able." ) from err try: value = pickle.loads(value_bytes) except pickle.UnpicklingError as err: raise CacheError( f"Malformed value_bytes_repr {value_bytes_repr!r} in kv_pair {kv_pair!r}, not un-pickle-able." ) from err # true duplicates, i.e. multiple occurrences of the same key => value # mapping are ok and treated as a no-op; key duplicates with differing # values, i.e. key => value_1 and key => value_2 where value_1 != value_2, # are not okay since we don't allow overwriting cached values (it's bad regardless) if (not cache.insert(key, value)) and (cache.get(key) != value): raise CacheError( f"Multiple values for key {key!r} found, got {cache.get(key)!r} and {value!r}." ) return cache @classmethod def from_file_path(cls, fpath: Path) -> Self: """ Create an in-memory cache from a file path. Args: fpath (Path): Path to the file containing pickled cache data. Returns: InMemoryCache: An instance populated from the file. Raises: CacheError: If the file is not a valid pickled dictionary. """ cache = cls() if not fpath.is_file(): # fpath doesn't exit = empty cache return cache try: with open(fpath, "rb") as fp: cache._cache = pickle.load(fp) except pickle.UnpicklingError as err: raise CacheError( f"Failed to create cache from file path {fpath}, file contents are un-pickle-able." ) from err if not isinstance(cache._cache, dict): raise CacheError( f"Failed to create cache from file path {fpath}, file contents not pickled dict[Key, Value]." ) return cache
InMemoryCache
python
kamyu104__LeetCode-Solutions
Python/sort-items-by-groups-respecting-dependencies.py
{ "start": 58, "end": 1058 }
class ____(object): def __init__(self): self.__nodes = set() self.__in_degree = collections.defaultdict(set) self.__out_degree = collections.defaultdict(set) def add_node(self, node): self.__nodes.add(node) def add_edge(self, src, dst): self.add_node(src), self.add_node(dst) self.__in_degree[dst].add(src) self.__out_degree[src].add(dst) def sort(self): q = collections.deque() result = [] for node in self.__nodes: if node not in self.__in_degree: q.append(node) while q: node = q.popleft() result.append(node) for nei in self.__out_degree[node]: self.__in_degree[nei].remove(node) if not self.__in_degree[nei]: self.__in_degree.pop(nei) q.append(nei) if len(result) < len(self.__nodes): return return result
Topo
python
django__django
tests/auth_tests/test_views.py
{ "start": 20994, "end": 22581 }
class ____(AuthViewsTestCase): user_email = "staffmember@example.com" @classmethod def setUpTestData(cls): cls.u1 = CustomUser.custom_objects.create( email="staffmember@example.com", date_of_birth=datetime.date(1976, 11, 8), ) cls.u1.set_password("password") cls.u1.save() def setUp(self): self.client = PasswordResetConfirmClient() def _test_confirm_start(self): # Start by creating the email response = self.client.post("/password_reset/", {"email": self.user_email}) self.assertEqual(response.status_code, 302) self.assertEqual(len(mail.outbox), 1) return self._read_signup_email(mail.outbox[0]) def _read_signup_email(self, email): urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body) self.assertIsNotNone(urlmatch, "No URL found in sent email") return urlmatch[0], urlmatch[1] def test_confirm_valid_custom_user(self): url, path = self._test_confirm_start() response = self.client.get(path) # redirect to a 'complete' page: self.assertContains(response, "Please enter your new password") # then submit a new password response = self.client.post( path, { "new_password1": "anewpassword", "new_password2": "anewpassword", }, ) self.assertRedirects(response, "/reset/done/") @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserCompositePrimaryKey")
CustomUserPasswordResetTest
python
ray-project__ray
python/ray/llm/_internal/batch/stages/chat_template_stage.py
{ "start": 4486, "end": 4966 }
class ____(StatefulStage): """ A stage that applies chat template. """ fn: Type[StatefulStageUDF] = ChatTemplateUDF def get_required_input_keys(self) -> Dict[str, str]: """The required input keys of the stage and their descriptions.""" return { "messages": "A list of messages in OpenAI chat format. " "See https://platform.openai.com/docs/api-reference/chat/create " "for details." }
ChatTemplateStage
python
dagster-io__dagster
python_modules/libraries/dagster-azure/dagster_azure/adls2/resources.py
{ "start": 888, "end": 971 }
class ____(Config): credential_type: Literal["key"] = "key" key: str
ADLS2Key
python
joke2k__faker
faker/providers/ssn/es_CO/__init__.py
{ "start": 818, "end": 2111 }
class ____(BaseProvider): nuip_formats = OrderedDict( [ ("10########", 0.25), ("11########", 0.25), ("12########", 0.1), ("%!######", 0.4), ] ) legal_person_nit_formats = [ "8########", "9########", ] def nuip(self) -> str: """ https://es.wikipedia.org/wiki/C%C3%A9dula_de_Ciudadan%C3%ADa_(Colombia) :example: '1095312769' """ return self.numerify(self.random_element(self.nuip_formats)) natural_person_nit = nuip def natural_person_nit_with_check_digit(self) -> str: """ :example: '1095312769-0' """ nit = self.natural_person_nit() check_digit = nit_check_digit(nit) return f"{nit}-{check_digit}" def legal_person_nit(self) -> str: """ https://es.wikipedia.org/wiki/N%C3%BAmero_de_Identificaci%C3%B3n_Tributaria :example: '967807269' """ return self.numerify(self.random_element(self.legal_person_nit_formats)) def legal_person_nit_with_check_digit(self) -> str: """ :example: '967807269-7' """ nit = self.legal_person_nit() check_digit = nit_check_digit(nit) return f"{nit}-{check_digit}"
Provider
python
tornadoweb__tornado
tornado/test/gen_test.py
{ "start": 17672, "end": 18016 }
class ____(RequestHandler): @gen.coroutine def get(self): yield gen.moment self.write("1") yield gen.moment self.write("2") yield gen.moment # just write, don't finish self.write("3") # "Undecorated" here refers to the absence of @asynchronous.
GenCoroutineUnfinishedSequenceHandler
python
euske__pdfminer
pdfminer/layout.py
{ "start": 9890, "end": 10860 }
class ____(LTTextLine): def __init__(self, word_margin): LTTextLine.__init__(self, word_margin) self._y0 = -INF return def add(self, obj): if isinstance(obj, LTChar) and self.word_margin: margin = self.word_margin * max(obj.width, obj.height) if obj.y1+margin < self._y0: LTContainer.add(self, LTAnno(' ')) self._y0 = obj.y0 LTTextLine.add(self, obj) return def find_neighbors(self, plane, ratio): d = ratio*self.width objs = plane.find((self.x0-d, self.y0, self.x1+d, self.y1)) return [obj for obj in objs if (isinstance(obj, LTTextLineVertical) and abs(obj.width-self.width) < d and (abs(obj.y0-self.y0) < d or abs(obj.y1-self.y1) < d))] ## LTTextBox ## ## A set of text objects that are grouped within ## a certain rectangular area. ##
LTTextLineVertical
python
tensorflow__tensorflow
tensorflow/python/autograph/tests/loop_distributed_test.py
{ "start": 3586, "end": 5271 }
class ____(reference_test_base.TestCase, parameterized.TestCase): @parameterized.parameters(*itertools.product( ( no_vars_loop, single_var_loop, two_vars_loop, loop_with_break, loop_with_continue, ), ( _distributed_dataset, _distributed_iterator, ), )) def test_basic(self, test_fn, target): if (test_fn in (loop_with_break, loop_with_continue) and target is _distributed_dataset): self.skipTest('b/162250181') self.assertFunctionMatchesEagerStatefulInput(test_fn, target) def test_iterator_next(self): strat, ds = _distributed_dataset() self.assertFunctionMatchesEager(iterator_next, strat, ds) def test_iterator_next_multiple_calls(self): strat, ds = _distributed_dataset() self.assertFunctionMatchesEager(iterator_next_multiple_calls, strat, ds) @parameterized.parameters(*itertools.product( ( 0, 1, 2, ), ( range, tf.range, ), )) def test_iterator_next_in_limited_loop(self, n, type_): n = type_(n) strat, ds = _distributed_dataset() self.assertFunctionMatchesEager(iterator_next_in_limited_loop, strat, ds, n) @parameterized.parameters( (iterator_next_stopping,), # Note that `except` has no effect in graph mode. (iterator_next_with_catching_stop_iteration,), ) def test_iterator_next_stopping(self, test_fn): strat, ds = _distributed_dataset() with self.assertRaises(tf.errors.OutOfRangeError): tf.function(test_fn)(strat, ds, tf.constant(True)) if __name__ == '__main__': tf.test.main()
ReferenceTest
python
getsentry__sentry
tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py
{ "start": 5029, "end": 5388 }
class ____(BaseSafeMigrationTest): app = "bad_flow_rename_field_app" migrate_from = "0001_initial" migrate_to = "0002_rename_field" def test(self) -> None: with pytest.raises( UnsafeOperationException, match="Renaming column TestTable.field to new_field is unsafe" ): self.run_migration()
RenameFieldTest
python
matplotlib__matplotlib
lib/mpl_toolkits/axisartist/angle_helper.py
{ "start": 4665, "end": 4846 }
class ____(LocatorBase): def __call__(self, v1, v2): return select_step24(v1, v2, self.nbins, self._include_last, threshold_factor=1)
LocatorH
python
psf__requests
src/requests/exceptions.py
{ "start": 3069, "end": 3167 }
class ____(RequestException, ValueError): """The URL provided was somehow invalid."""
InvalidURL
python
FactoryBoy__factory_boy
factory/fuzzy.py
{ "start": 2164, "end": 2876 }
class ____(BaseFuzzyAttribute): """Handles fuzzy choice of an attribute. Args: choices (iterable): An iterable yielding options; will only be unrolled on the first call. getter (callable or None): a function to parse returned values """ def __init__(self, choices, getter=None): self.choices = None self.choices_generator = choices self.getter = getter super().__init__() def fuzz(self): if self.choices is None: self.choices = list(self.choices_generator) value = random.randgen.choice(self.choices) if self.getter is None: return value return self.getter(value)
FuzzyChoice
python
apache__thrift
lib/py/src/transport/THeaderTransport.py
{ "start": 1435, "end": 1510 }
class ____(object): BINARY = 0x00 COMPACT = 0x02
THeaderSubprotocolID
python
pypa__warehouse
tests/unit/manage/views/test_organizations.py
{ "start": 1821, "end": 12835 }
class ____: def test_manage_organization_application(self, db_request): _organization_application = OrganizationApplicationFactory.create( status=OrganizationApplicationStatus.Submitted ) view = org_views.ManageOrganizationApplicationViews( _organization_application, db_request ) assert view.manage_organization_application() == { "organization_application": _organization_application, "information_requests": [], "response_forms": {}, } assert ( _organization_application.status == OrganizationApplicationStatus.Submitted ) def test_manage_organization_application_response_with_info_requests( self, db_request, organization_service, monkeypatch ): _organization_application = OrganizationApplicationFactory.create( status=OrganizationApplicationStatus.MoreInformationNeeded ) with freeze_time() as frozen_datetime: _request_for_more_info0 = OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we need more information"}, created=datetime.datetime.now(datetime.UTC), ) frozen_datetime.tick(1.0) _request_for_more_info1 = OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we still need more information"}, created=datetime.datetime.now(datetime.UTC), ) view = org_views.ManageOrganizationApplicationViews( _organization_application, db_request ) _response = view.manage_organization_application() assert ( _organization_application.status == OrganizationApplicationStatus.MoreInformationNeeded ) assert _response["organization_application"] == _organization_application assert _response["information_requests"] == [ _request_for_more_info1, _request_for_more_info0, ] assert len(_response["response_forms"]) == 2 assert _request_for_more_info0.id in _response["response_forms"] assert _request_for_more_info1.id in _response["response_forms"] def test_manage_organization_application_response_with_info_requests_and_responses( self, db_request, organization_service, monkeypatch ): _organization_application = OrganizationApplicationFactory.create( status=OrganizationApplicationStatus.MoreInformationNeeded ) with freeze_time() as frozen_datetime: _request_for_more_info0 = OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we need more information"}, additional={ "response": "you got it", "response_time": "2025-03-14T15:40:36.485495+00:00", }, created=datetime.datetime.now(datetime.UTC), ) frozen_datetime.tick(1.0) _request_for_more_info1 = OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we still need more information"}, created=datetime.datetime.now(datetime.UTC), ) view = org_views.ManageOrganizationApplicationViews( _organization_application, db_request ) _response = view.manage_organization_application() assert ( _organization_application.status == OrganizationApplicationStatus.MoreInformationNeeded ) assert _response["organization_application"] == _organization_application assert _response["information_requests"] == [ _request_for_more_info1, _request_for_more_info0, ] assert len(_response["response_forms"]) == 1 assert _request_for_more_info1.id in _response["response_forms"] def test_manage_organization_application_response_with_all_responded( self, db_request, organization_service ): _organization_application = OrganizationApplicationFactory.create( status=OrganizationApplicationStatus.Submitted ) with freeze_time() as frozen_datetime: _request_for_more_info0 = OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we need more information"}, additional={ "response": "you got it", "response_time": "2025-03-14T15:40:36.485495+00:00", }, created=datetime.datetime.now(datetime.UTC), ) frozen_datetime.tick(1.0) _request_for_more_info1 = OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we still need more information"}, additional={ "response": "you got it", "response_time": "2025-03-14T15:40:36.485495+00:00", }, created=datetime.datetime.now(datetime.UTC), ) view = org_views.ManageOrganizationApplicationViews( _organization_application, db_request ) _response = view.manage_organization_application() assert ( _organization_application.status == OrganizationApplicationStatus.Submitted ) assert _response["organization_application"] == _organization_application assert _response["information_requests"] == [ _request_for_more_info1, _request_for_more_info0, ] assert len(_response["response_forms"]) == 0 def test_manage_organization_application_submit_empty( self, db_request, organization_service ): _organization_application = OrganizationApplicationFactory.create( status=OrganizationApplicationStatus.MoreInformationNeeded ) with freeze_time() as frozen_datetime: _request_for_more_info0 = OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we need more information"}, additional={ "response": "you got it", "response_time": "2025-03-14T15:40:36.485495+00:00", }, created=datetime.datetime.now(datetime.UTC), ) frozen_datetime.tick(1.0) _request_for_more_info1 = OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we still need more information"}, created=datetime.datetime.now(datetime.UTC), ) db_request.POST = MultiDict({}) view = org_views.ManageOrganizationApplicationViews( _organization_application, db_request ) _response = view.manage_organization_application_submit() assert ( _organization_application.status == OrganizationApplicationStatus.MoreInformationNeeded ) assert _response["organization_application"] == _organization_application assert _response["information_requests"] == [ _request_for_more_info1, _request_for_more_info0, ] assert len(_response["response_forms"]) == 1 assert _request_for_more_info1.id in _response["response_forms"] def test_manage_organization_application_submit_response( self, db_request, organization_service ): _organization_application = OrganizationApplicationFactory.create( status=OrganizationApplicationStatus.MoreInformationNeeded ) with freeze_time() as frozen_datetime: OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we need more information"}, additional={ "response": "you got it", "response_time": "2025-03-14T15:40:36.485495+00:00", }, created=datetime.datetime.now(datetime.UTC), ) frozen_datetime.tick(1.0) _request_for_more_info1 = OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we still need more information"}, created=datetime.datetime.now(datetime.UTC), ) db_request.POST = MultiDict( { "response_form-id": _request_for_more_info1.id.__str__(), "response": "This is my response", } ) view = org_views.ManageOrganizationApplicationViews( _organization_application, db_request ) _response = view.manage_organization_application_submit() assert ( _organization_application.status == OrganizationApplicationStatus.Submitted ) assert isinstance(_response, HTTPSeeOther) assert _request_for_more_info1.additional["response"] == "This is my response" def test_manage_organization_application_submit_response_correct_request( self, db_request, organization_service ): _organization_application = OrganizationApplicationFactory.create( status=OrganizationApplicationStatus.MoreInformationNeeded ) with freeze_time() as frozen_datetime: OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we need more information"}, created=datetime.datetime.now(datetime.UTC), ) frozen_datetime.tick(1.0) _request_for_more_info1 = OrganizationApplicationObservationFactory( related=_organization_application, payload={"message": "we still need more information"}, created=datetime.datetime.now(datetime.UTC), ) db_request.POST = MultiDict( { "response_form-id": _request_for_more_info1.id.__str__(), "response": "This is my response", } ) view = org_views.ManageOrganizationApplicationViews( _organization_application, db_request ) _response = view.manage_organization_application_submit() assert ( _organization_application.status == OrganizationApplicationStatus.MoreInformationNeeded ) assert isinstance(_response, HTTPSeeOther) assert _request_for_more_info1.additional["response"] == "This is my response"
TestManageOrganizationApplication
python
ray-project__ray
ci/ray_ci/ray_docker_container.py
{ "start": 360, "end": 3071 }
class ____(DockerContainer): """ Container for building and publishing ray docker images """ def run(self, base: Optional[str] = None) -> None: """ Build and publish ray docker images """ assert "RAYCI_BUILD_ID" in os.environ, "RAYCI_BUILD_ID not set" rayci_build_id = os.environ["RAYCI_BUILD_ID"] if base is None: if self.image_type in [ RayType.RAY_EXTRA.value, RayType.RAY_ML_EXTRA.value, RayType.RAY_LLM_EXTRA.value, ]: base = "base-extra" else: base = "base" if self.architecture == DEFAULT_ARCHITECTURE: suffix = base else: suffix = f"{base}-{self.architecture}" image_repo = RAY_REPO_MAP[self.image_type] base_image = ( f"{_DOCKER_ECR_REPO}:{rayci_build_id}" f"-{image_repo}-py{self.python_version}-{self.platform}-{suffix}" ) docker_pull(base_image) bin_path = PYTHON_VERSIONS[self.python_version]["bin_path"] wheel_name = ( f"ray-{RAY_VERSION}-{bin_path}-manylinux2014_{self.architecture}.whl" ) constraints_file = "requirements_compiled.txt" tag = self._get_canonical_tag() ray_image = f"rayproject/{image_repo}:{tag}" pip_freeze = f"{self.image_type}:{tag}_pip-freeze.txt" cmds = [ "./ci/build/build-ray-docker.sh " f"{wheel_name} {base_image} {constraints_file} {ray_image} {pip_freeze}" ] if self._should_upload(): cmds += [ "bazel run .buildkite:copy_files -- --destination docker_login", ] for alias in self._get_image_names(): cmds += [ f"docker tag {ray_image} {alias}", f"docker push {alias}", ] self.run_script(cmds) def _should_upload(self) -> bool: if not self.upload: return False if ( os.environ.get("BUILDKITE_PIPELINE_ID") not in get_global_config()["ci_pipeline_postmerge"] ): return False if os.environ.get("BUILDKITE_BRANCH", "").startswith("releases/"): return True return ( os.environ.get("BUILDKITE_BRANCH") == "master" and os.environ.get("RAYCI_SCHEDULE") == "nightly" ) def _get_image_names(self) -> List[str]: repo_name = RAY_REPO_MAP[self.image_type] ray_repo = f"rayproject/{repo_name}" return [f"{ray_repo}:{tag}" for tag in self._get_image_tags(external=True)]
RayDockerContainer
python
realpython__materials
python-textual/grid_tcss.py
{ "start": 101, "end": 415 }
class ____(App): CSS_PATH = "grid.tcss" def compose(self): with Grid(): for row in range(6): for col in range(4): yield Static(f"Static ({row=}, {col=})") if __name__ == "__main__": app = GridLayoutAppWithTCSS() app.run()
GridLayoutAppWithTCSS
python
jazzband__django-model-utils
tests/test_models/test_timeframed_model.py
{ "start": 350, "end": 1349 }
class ____(TestCase): def setUp(self) -> None: self.now = datetime.now() def test_not_yet_begun(self) -> None: TimeFrame.objects.create(start=self.now + timedelta(days=2)) self.assertEqual(TimeFrame.timeframed.count(), 0) def test_finished(self) -> None: TimeFrame.objects.create(end=self.now - timedelta(days=1)) self.assertEqual(TimeFrame.timeframed.count(), 0) def test_no_end(self) -> None: TimeFrame.objects.create(start=self.now - timedelta(days=10)) self.assertEqual(TimeFrame.timeframed.count(), 1) def test_no_start(self) -> None: TimeFrame.objects.create(end=self.now + timedelta(days=2)) self.assertEqual(TimeFrame.timeframed.count(), 1) def test_within_range(self) -> None: TimeFrame.objects.create(start=self.now - timedelta(days=1), end=self.now + timedelta(days=1)) self.assertEqual(TimeFrame.timeframed.count(), 1)
TimeFramedModelTests
python
PrefectHQ__prefect
tests/server/models/test_block_registration.py
{ "start": 3876, "end": 5153 }
class ____: async def test_register_new_block_schema(self, session): block_type_id = await register_block_type( session=session, block_type=Secret._to_block_type() ) registered_block_schema_id = await register_block_schema( session, block_schema=Secret._to_block_schema(block_type_id=block_type_id) ) read_block_schema = await read_block_schema_by_checksum( session, checksum=Secret._calculate_schema_checksum(), version=Secret.get_block_schema_version(), ) assert registered_block_schema_id == read_block_schema.id async def test_register_existing_block_schema(self, session): block_type_id = await register_block_type( session=session, block_type=Secret._to_block_type() ) first_registered_block_schema_id = await register_block_schema( session, block_schema=Secret._to_block_schema(block_type_id=block_type_id) ) second_registered_block_schema_id = await register_block_schema( session, block_schema=Secret._to_block_schema(block_type_id=block_type_id) ) assert first_registered_block_schema_id == second_registered_block_schema_id
TestRegisterBlockSchema
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_test.py
{ "start": 54089, "end": 83442 }
class ____(test.TestCase): def test_raises_if_empty_feature_columns(self): with self.assertRaisesRegex(ValueError, 'feature_columns must not be empty'): fc.linear_model(features={}, feature_columns=[]) def test_should_be_feature_column(self): with self.assertRaisesRegex(ValueError, 'must be a _FeatureColumn'): fc.linear_model(features={'a': [[0]]}, feature_columns='NotSupported') def test_should_be_dense_or_categorical_column(self): class NotSupportedColumn(_FeatureColumn): @property def name(self): return 'NotSupportedColumn' def _transform_feature(self, cache): pass @property def _parse_example_spec(self): pass with self.assertRaisesRegex( ValueError, 'must be either a _DenseColumn or _CategoricalColumn'): fc.linear_model( features={'a': [[0]]}, feature_columns=[NotSupportedColumn()]) def test_does_not_support_dict_columns(self): with self.assertRaisesRegex( ValueError, 'Expected feature_columns to be iterable, found dict.'): fc.linear_model( features={'a': [[0]]}, feature_columns={'a': fc._numeric_column('a')}) def test_raises_if_duplicate_name(self): with self.assertRaisesRegex( ValueError, 'Duplicate feature column name found for columns'): fc.linear_model( features={'a': [[0]]}, feature_columns=[fc._numeric_column('a'), fc._numeric_column('a')]) def test_dense_bias(self): price = fc._numeric_column('price') with ops.Graph().as_default(): features = {'price': [[1.], [5.]]} predictions = fc.linear_model(features, [price]) bias = get_linear_model_bias() price_var = get_linear_model_column_var(price) with _initialized_session() as sess: self.assertAllClose([0.], self.evaluate(bias)) sess.run(price_var.assign([[10.]])) sess.run(bias.assign([5.])) self.assertAllClose([[15.], [55.]], self.evaluate(predictions)) def test_sparse_bias(self): wire_cast = fc._categorical_column_with_hash_bucket('wire_cast', 4) with ops.Graph().as_default(): wire_tensor = sparse_tensor.SparseTensor( values=['omar', 'stringer', 'marlo'], # hashed to = [2, 0, 3] indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) features = {'wire_cast': wire_tensor} predictions = fc.linear_model(features, [wire_cast]) bias = get_linear_model_bias() wire_cast_var = get_linear_model_column_var(wire_cast) with _initialized_session() as sess: self.assertAllClose([0.], self.evaluate(bias)) self.assertAllClose([[0.], [0.], [0.], [0.]], self.evaluate(wire_cast_var)) sess.run(wire_cast_var.assign([[10.], [100.], [1000.], [10000.]])) sess.run(bias.assign([5.])) self.assertAllClose([[1005.], [10015.]], self.evaluate(predictions)) def test_dense_and_sparse_bias(self): wire_cast = fc._categorical_column_with_hash_bucket('wire_cast', 4) price = fc._numeric_column('price') with ops.Graph().as_default(): wire_tensor = sparse_tensor.SparseTensor( values=['omar', 'stringer', 'marlo'], # hashed to = [2, 0, 3] indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) features = {'wire_cast': wire_tensor, 'price': [[1.], [5.]]} predictions = fc.linear_model(features, [wire_cast, price]) bias = get_linear_model_bias() wire_cast_var = get_linear_model_column_var(wire_cast) price_var = get_linear_model_column_var(price) with _initialized_session() as sess: sess.run(wire_cast_var.assign([[10.], [100.], [1000.], [10000.]])) sess.run(bias.assign([5.])) sess.run(price_var.assign([[10.]])) self.assertAllClose([[1015.], [10065.]], self.evaluate(predictions)) def test_dense_and_sparse_column(self): """When the column is both dense and sparse, uses sparse tensors.""" class _DenseAndSparseColumn(_DenseColumn, _CategoricalColumn): @property def name(self): return 'dense_and_sparse_column' @property def _parse_example_spec(self): return {self.name: parsing_ops.VarLenFeature(self.dtype)} def _transform_feature(self, inputs): return inputs.get(self.name) @property def _variable_shape(self): raise ValueError('Should not use this method.') def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): raise ValueError('Should not use this method.') @property def _num_buckets(self): return 4 def _get_sparse_tensors(self, inputs, weight_collections=None, trainable=None): sp_tensor = sparse_tensor.SparseTensor( indices=[[0, 0], [1, 0], [1, 1]], values=[2, 0, 3], dense_shape=[2, 2]) return _CategoricalColumn.IdWeightPair(sp_tensor, None) dense_and_sparse_column = _DenseAndSparseColumn() with ops.Graph().as_default(): sp_tensor = sparse_tensor.SparseTensor( values=['omar', 'stringer', 'marlo'], indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) features = {dense_and_sparse_column.name: sp_tensor} predictions = fc.linear_model(features, [dense_and_sparse_column]) bias = get_linear_model_bias() dense_and_sparse_column_var = get_linear_model_column_var( dense_and_sparse_column) with _initialized_session() as sess: sess.run(dense_and_sparse_column_var.assign( [[10.], [100.], [1000.], [10000.]])) sess.run(bias.assign([5.])) self.assertAllClose([[1005.], [10015.]], self.evaluate(predictions)) def test_dense_multi_output(self): price = fc._numeric_column('price') with ops.Graph().as_default(): features = {'price': [[1.], [5.]]} predictions = fc.linear_model(features, [price], units=3) bias = get_linear_model_bias() price_var = get_linear_model_column_var(price) with _initialized_session() as sess: self.assertAllClose(np.zeros((3,)), self.evaluate(bias)) self.assertAllClose(np.zeros((1, 3)), self.evaluate(price_var)) sess.run(price_var.assign([[10., 100., 1000.]])) sess.run(bias.assign([5., 6., 7.])) self.assertAllClose([[15., 106., 1007.], [55., 506., 5007.]], self.evaluate(predictions)) def test_sparse_multi_output(self): wire_cast = fc._categorical_column_with_hash_bucket('wire_cast', 4) with ops.Graph().as_default(): wire_tensor = sparse_tensor.SparseTensor( values=['omar', 'stringer', 'marlo'], # hashed to = [2, 0, 3] indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) features = {'wire_cast': wire_tensor} predictions = fc.linear_model(features, [wire_cast], units=3) bias = get_linear_model_bias() wire_cast_var = get_linear_model_column_var(wire_cast) with _initialized_session() as sess: self.assertAllClose(np.zeros((3,)), self.evaluate(bias)) self.assertAllClose(np.zeros((4, 3)), self.evaluate(wire_cast_var)) sess.run( wire_cast_var.assign([[10., 11., 12.], [100., 110., 120.], [ 1000., 1100., 1200. ], [10000., 11000., 12000.]])) sess.run(bias.assign([5., 6., 7.])) self.assertAllClose([[1005., 1106., 1207.], [10015., 11017., 12019.]], self.evaluate(predictions)) def test_dense_multi_dimension(self): price = fc._numeric_column('price', shape=2) with ops.Graph().as_default(): features = {'price': [[1., 2.], [5., 6.]]} predictions = fc.linear_model(features, [price]) price_var = get_linear_model_column_var(price) with _initialized_session() as sess: self.assertAllClose([[0.], [0.]], self.evaluate(price_var)) sess.run(price_var.assign([[10.], [100.]])) self.assertAllClose([[210.], [650.]], self.evaluate(predictions)) def test_sparse_multi_rank(self): wire_cast = fc._categorical_column_with_hash_bucket('wire_cast', 4) with ops.Graph().as_default(): wire_tensor = array_ops.sparse_placeholder(dtypes.string) wire_value = sparse_tensor.SparseTensorValue( values=['omar', 'stringer', 'marlo', 'omar'], # hashed = [2, 0, 3, 2] indices=[[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 0, 1]], dense_shape=[2, 2, 2]) features = {'wire_cast': wire_tensor} predictions = fc.linear_model(features, [wire_cast]) wire_cast_var = get_linear_model_column_var(wire_cast) with _initialized_session() as sess: self.assertAllClose(np.zeros((4, 1)), self.evaluate(wire_cast_var)) self.assertAllClose( np.zeros((2, 1)), predictions.eval(feed_dict={wire_tensor: wire_value})) sess.run(wire_cast_var.assign([[10.], [100.], [1000.], [10000.]])) self.assertAllClose( [[1010.], [11000.]], predictions.eval(feed_dict={wire_tensor: wire_value})) def test_sparse_combiner(self): wire_cast = fc._categorical_column_with_hash_bucket('wire_cast', 4) with ops.Graph().as_default(): wire_tensor = sparse_tensor.SparseTensor( values=['omar', 'stringer', 'marlo'], # hashed to = [2, 0, 3] indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) features = {'wire_cast': wire_tensor} predictions = fc.linear_model( features, [wire_cast], sparse_combiner='mean') bias = get_linear_model_bias() wire_cast_var = get_linear_model_column_var(wire_cast) with _initialized_session() as sess: sess.run(wire_cast_var.assign([[10.], [100.], [1000.], [10000.]])) sess.run(bias.assign([5.])) self.assertAllClose([[1005.], [5010.]], self.evaluate(predictions)) def test_sparse_combiner_with_negative_weights(self): wire_cast = fc._categorical_column_with_hash_bucket('wire_cast', 4) wire_cast_weights = fc._weighted_categorical_column(wire_cast, 'weights') with ops.Graph().as_default(): wire_tensor = sparse_tensor.SparseTensor( values=['omar', 'stringer', 'marlo'], # hashed to = [2, 0, 3] indices=[[0, 0], [1, 0], [1, 1]], dense_shape=[2, 2]) features = { 'wire_cast': wire_tensor, 'weights': constant_op.constant([[1., 1., -1.0]]) } predictions = fc.linear_model( features, [wire_cast_weights], sparse_combiner='sum') bias = get_linear_model_bias() wire_cast_var = get_linear_model_column_var(wire_cast) with _initialized_session() as sess: sess.run(wire_cast_var.assign([[10.], [100.], [1000.], [10000.]])) sess.run(bias.assign([5.])) self.assertAllClose([[1005.], [-9985.]], self.evaluate(predictions)) def test_dense_multi_dimension_multi_output(self): price = fc._numeric_column('price', shape=2) with ops.Graph().as_default(): features = {'price': [[1., 2.], [5., 6.]]} predictions = fc.linear_model(features, [price], units=3) bias = get_linear_model_bias() price_var = get_linear_model_column_var(price) with _initialized_session() as sess: self.assertAllClose(np.zeros((3,)), self.evaluate(bias)) self.assertAllClose(np.zeros((2, 3)), self.evaluate(price_var)) sess.run(price_var.assign([[1., 2., 3.], [10., 100., 1000.]])) sess.run(bias.assign([2., 3., 4.])) self.assertAllClose([[23., 205., 2007.], [67., 613., 6019.]], self.evaluate(predictions)) def test_raises_if_shape_mismatch(self): price = fc._numeric_column('price', shape=2) with ops.Graph().as_default(): features = {'price': [[1.], [5.]]} with self.assertRaisesRegex( Exception, r'Cannot reshape a tensor with 2 elements to shape \[2,2\]'): fc.linear_model(features, [price]) def test_dense_reshaping(self): price = fc._numeric_column('price', shape=[1, 2]) with ops.Graph().as_default(): features = {'price': [[[1., 2.]], [[5., 6.]]]} predictions = fc.linear_model(features, [price]) bias = get_linear_model_bias() price_var = get_linear_model_column_var(price) with _initialized_session() as sess: self.assertAllClose([0.], self.evaluate(bias)) self.assertAllClose([[0.], [0.]], self.evaluate(price_var)) self.assertAllClose([[0.], [0.]], self.evaluate(predictions)) sess.run(price_var.assign([[10.], [100.]])) self.assertAllClose([[210.], [650.]], self.evaluate(predictions)) def test_dense_multi_column(self): price1 = fc._numeric_column('price1', shape=2) price2 = fc._numeric_column('price2') with ops.Graph().as_default(): features = { 'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]] } predictions = fc.linear_model(features, [price1, price2]) bias = get_linear_model_bias() price1_var = get_linear_model_column_var(price1) price2_var = get_linear_model_column_var(price2) with _initialized_session() as sess: self.assertAllClose([0.], self.evaluate(bias)) self.assertAllClose([[0.], [0.]], self.evaluate(price1_var)) self.assertAllClose([[0.]], self.evaluate(price2_var)) self.assertAllClose([[0.], [0.]], self.evaluate(predictions)) sess.run(price1_var.assign([[10.], [100.]])) sess.run(price2_var.assign([[1000.]])) sess.run(bias.assign([7.])) self.assertAllClose([[3217.], [4657.]], self.evaluate(predictions)) def test_fills_cols_to_vars(self): price1 = fc._numeric_column('price1', shape=2) price2 = fc._numeric_column('price2') with ops.Graph().as_default(): features = {'price1': [[1., 2.], [5., 6.]], 'price2': [[3.], [4.]]} cols_to_vars = {} fc.linear_model(features, [price1, price2], cols_to_vars=cols_to_vars) bias = get_linear_model_bias() price1_var = get_linear_model_column_var(price1) price2_var = get_linear_model_column_var(price2) self.assertEqual(cols_to_vars['bias'], [bias]) self.assertEqual(cols_to_vars[price1], [price1_var]) self.assertEqual(cols_to_vars[price2], [price2_var]) def test_fills_cols_to_vars_partitioned_variables(self): price1 = fc._numeric_column('price1', shape=2) price2 = fc._numeric_column('price2', shape=3) with ops.Graph().as_default(): features = { 'price1': [[1., 2.], [6., 7.]], 'price2': [[3., 4., 5.], [8., 9., 10.]] } cols_to_vars = {} with variable_scope.variable_scope( 'linear', partitioner=partitioned_variables.fixed_size_partitioner(2, axis=0)): fc.linear_model(features, [price1, price2], cols_to_vars=cols_to_vars) with _initialized_session(): self.assertEqual([0.], cols_to_vars['bias'][0].eval()) # Partitioning shards the [2, 1] price1 var into 2 [1, 1] Variables. self.assertAllEqual([[0.]], cols_to_vars[price1][0]) self.assertAllEqual([[0.]], cols_to_vars[price1][1]) # Partitioning shards the [3, 1] price2 var into a [2, 1] Variable and # a [1, 1] Variable. self.assertAllEqual([[0.], [0.]], cols_to_vars[price2][0]) self.assertAllEqual([[0.]], cols_to_vars[price2][1]) def test_fills_cols_to_output_tensors(self): # Provide three _DenseColumn's to input_layer: a _NumericColumn, a # _BucketizedColumn, and an _EmbeddingColumn. Only the _EmbeddingColumn # creates a Variable. apple_numeric_column = fc._numeric_column('apple_numeric_column') banana_dense_feature = fc._numeric_column('banana_dense_feature') banana_dense_feature_bucketized = fc._bucketized_column( banana_dense_feature, boundaries=[0.]) cherry_sparse_column = fc._categorical_column_with_hash_bucket( 'cherry_sparse_feature', hash_bucket_size=5) dragonfruit_embedding_column = fc._embedding_column( cherry_sparse_column, dimension=10) with ops.Graph().as_default(): features = { 'apple_numeric_column': [[3.], [4.]], 'banana_dense_feature': [[-1.], [4.]], 'cherry_sparse_feature': [['a'], ['x']], } cols_to_output_tensors = {} all_cols = [ apple_numeric_column, banana_dense_feature_bucketized, dragonfruit_embedding_column ] input_layer = fc.input_layer( features, all_cols, cols_to_output_tensors=cols_to_output_tensors) # We check the mapping by checking that we have the right keys, # and that the values (output_tensors) were indeed the ones used to # form the input layer. self.assertCountEqual(all_cols, cols_to_output_tensors.keys()) input_layer_inputs = [tensor for tensor in input_layer.op.inputs[:-1]] output_tensors = [tensor for tensor in cols_to_output_tensors.values()] self.assertCountEqual(input_layer_inputs, output_tensors) def test_dense_collection(self): price = fc._numeric_column('price') with ops.Graph().as_default() as g: features = {'price': [[1.], [5.]]} fc.linear_model(features, [price], weight_collections=['my-vars']) my_vars = g.get_collection('my-vars') bias = get_linear_model_bias() price_var = get_linear_model_column_var(price) self.assertIn(bias, my_vars) self.assertIn(price_var, my_vars) def test_sparse_collection(self): wire_cast = fc._categorical_column_with_hash_bucket('wire_cast', 4) with ops.Graph().as_default() as g: wire_tensor = sparse_tensor.SparseTensor( values=['omar'], indices=[[0, 0]], dense_shape=[1, 1]) features = {'wire_cast': wire_tensor} fc.linear_model( features, [wire_cast], weight_collections=['my-vars']) my_vars = g.get_collection('my-vars') bias = get_linear_model_bias() wire_cast_var = get_linear_model_column_var(wire_cast) self.assertIn(bias, my_vars) self.assertIn(wire_cast_var, my_vars) def test_dense_trainable_default(self): price = fc._numeric_column('price') with ops.Graph().as_default() as g: features = {'price': [[1.], [5.]]} fc.linear_model(features, [price]) bias = get_linear_model_bias() price_var = get_linear_model_column_var(price) trainable_vars = g.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES) self.assertIn(bias, trainable_vars) self.assertIn(price_var, trainable_vars) def test_sparse_trainable_default(self): wire_cast = fc._categorical_column_with_hash_bucket('wire_cast', 4) with ops.Graph().as_default() as g: wire_tensor = sparse_tensor.SparseTensor( values=['omar'], indices=[[0, 0]], dense_shape=[1, 1]) features = {'wire_cast': wire_tensor} fc.linear_model(features, [wire_cast]) trainable_vars = g.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES) bias = get_linear_model_bias() wire_cast_var = get_linear_model_column_var(wire_cast) self.assertIn(bias, trainable_vars) self.assertIn(wire_cast_var, trainable_vars) def test_dense_trainable_false(self): price = fc._numeric_column('price') with ops.Graph().as_default() as g: features = {'price': [[1.], [5.]]} fc.linear_model(features, [price], trainable=False) trainable_vars = g.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES) self.assertEqual([], trainable_vars) def test_sparse_trainable_false(self): wire_cast = fc._categorical_column_with_hash_bucket('wire_cast', 4) with ops.Graph().as_default() as g: wire_tensor = sparse_tensor.SparseTensor( values=['omar'], indices=[[0, 0]], dense_shape=[1, 1]) features = {'wire_cast': wire_tensor} fc.linear_model(features, [wire_cast], trainable=False) trainable_vars = g.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES) self.assertEqual([], trainable_vars) def test_column_order(self): price_a = fc._numeric_column('price_a') price_b = fc._numeric_column('price_b') wire_cast = fc._categorical_column_with_hash_bucket('wire_cast', 4) with ops.Graph().as_default() as g: features = { 'price_a': [[1.]], 'price_b': [[3.]], 'wire_cast': sparse_tensor.SparseTensor( values=['omar'], indices=[[0, 0]], dense_shape=[1, 1]) } fc.linear_model( features, [price_a, wire_cast, price_b], weight_collections=['my-vars']) my_vars = g.get_collection('my-vars') self.assertIn('price_a', my_vars[0].name) self.assertIn('price_b', my_vars[1].name) self.assertIn('wire_cast', my_vars[2].name) with ops.Graph().as_default() as g: features = { 'price_a': [[1.]], 'price_b': [[3.]], 'wire_cast': sparse_tensor.SparseTensor( values=['omar'], indices=[[0, 0]], dense_shape=[1, 1]) } fc.linear_model( features, [wire_cast, price_b, price_a], weight_collections=['my-vars']) my_vars = g.get_collection('my-vars') self.assertIn('price_a', my_vars[0].name) self.assertIn('price_b', my_vars[1].name) self.assertIn('wire_cast', my_vars[2].name) def test_static_batch_size_mismatch(self): price1 = fc._numeric_column('price1') price2 = fc._numeric_column('price2') with ops.Graph().as_default(): features = { 'price1': [[1.], [5.], [7.]], # batchsize = 3 'price2': [[3.], [4.]] # batchsize = 2 } with self.assertRaisesRegex( ValueError, r'Batch size \(first dimension\) of each feature must be same.'): fc.linear_model(features, [price1, price2]) def test_subset_of_static_batch_size_mismatch(self): price1 = fc._numeric_column('price1') price2 = fc._numeric_column('price2') price3 = fc._numeric_column('price3') with ops.Graph().as_default(): features = { 'price1': array_ops.placeholder(dtype=dtypes.int64), # batchsize = 3 'price2': [[3.], [4.]], # batchsize = 2 'price3': [[3.], [4.], [5.]] # batchsize = 3 } with self.assertRaisesRegex( ValueError, r'Batch size \(first dimension\) of each feature must be same.'): # pylint: disable=anomalous-backslash-in-string fc.linear_model(features, [price1, price2, price3]) def test_runtime_batch_size_mismatch(self): price1 = fc._numeric_column('price1') price2 = fc._numeric_column('price2') with ops.Graph().as_default(): features = { 'price1': array_ops.placeholder(dtype=dtypes.int64), # batchsize = 3 'price2': [[3.], [4.]] # batchsize = 2 } predictions = fc.linear_model(features, [price1, price2]) with _initialized_session() as sess: with self.assertRaisesRegex(errors.OpError, 'must have the same size and shape'): sess.run( predictions, feed_dict={features['price1']: [[1.], [5.], [7.]]}) def test_runtime_batch_size_matches(self): price1 = fc._numeric_column('price1') price2 = fc._numeric_column('price2') with ops.Graph().as_default(): features = { 'price1': array_ops.placeholder(dtype=dtypes.int64), # batchsize = 2 'price2': array_ops.placeholder(dtype=dtypes.int64), # batchsize = 2 } predictions = fc.linear_model(features, [price1, price2]) with _initialized_session() as sess: sess.run( predictions, feed_dict={ features['price1']: [[1.], [5.]], features['price2']: [[1.], [5.]], }) @test_util.run_deprecated_v1 # FeatureColumnV1 uses variable scope etc. which is TF1. def test_with_1d_sparse_tensor(self): price = fc._numeric_column('price') price_buckets = fc._bucketized_column( price, boundaries=[ 0., 10., 100., ]) body_style = fc._categorical_column_with_vocabulary_list( 'body-style', vocabulary_list=['hardtop', 'wagon', 'sedan']) # Provides 1-dim tensor and dense tensor. features = { 'price': constant_op.constant([-1., 12.,]), 'body-style': sparse_tensor.SparseTensor( indices=((0,), (1,)), values=('sedan', 'hardtop'), dense_shape=(2,)), } self.assertEqual(1, features['price'].shape.ndims) self.assertEqual(1, features['body-style'].dense_shape.get_shape()[0]) net = fc.linear_model(features, [price_buckets, body_style]) with _initialized_session() as sess: bias = get_linear_model_bias() price_buckets_var = get_linear_model_column_var(price_buckets) body_style_var = get_linear_model_column_var(body_style) sess.run(price_buckets_var.assign([[10.], [100.], [1000.], [10000.]])) sess.run(body_style_var.assign([[-10.], [-100.], [-1000.]])) sess.run(bias.assign([5.])) self.assertAllClose([[10 - 1000 + 5.], [1000 - 10 + 5.]], self.evaluate(net)) @test_util.run_deprecated_v1 # Placeholders are TF1. Replacing with tf.function not feasible because of V1 # variable creation. def test_with_1d_unknown_shape_sparse_tensor(self): price = fc._numeric_column('price') price_buckets = fc._bucketized_column( price, boundaries=[ 0., 10., 100., ]) body_style = fc._categorical_column_with_vocabulary_list( 'body-style', vocabulary_list=['hardtop', 'wagon', 'sedan']) country = fc._categorical_column_with_vocabulary_list( 'country', vocabulary_list=['US', 'JP', 'CA']) # Provides 1-dim tensor and dense tensor. features = { 'price': array_ops.placeholder(dtypes.float32), 'body-style': array_ops.sparse_placeholder(dtypes.string), 'country': array_ops.placeholder(dtypes.string), } self.assertIsNone(features['price'].shape.ndims) self.assertIsNone(features['body-style'].get_shape().ndims) price_data = np.array([-1., 12.]) body_style_data = sparse_tensor.SparseTensorValue( indices=((0,), (1,)), values=('sedan', 'hardtop'), dense_shape=(2,)) country_data = np.array(['US', 'CA']) net = fc.linear_model(features, [price_buckets, body_style, country]) bias = get_linear_model_bias() price_buckets_var = get_linear_model_column_var(price_buckets) body_style_var = get_linear_model_column_var(body_style) with _initialized_session() as sess: sess.run(price_buckets_var.assign([[10.], [100.], [1000.], [10000.]])) sess.run(body_style_var.assign([[-10.], [-100.], [-1000.]])) sess.run(bias.assign([5.])) self.assertAllClose([[10 - 1000 + 5.], [1000 - 10 + 5.]], sess.run( net, feed_dict={ features['price']: price_data, features['body-style']: body_style_data, features['country']: country_data })) @test_util.run_deprecated_v1 # Placeholders are TF1. Replacing with tf.function not feasible because of V1 # variable creation. def test_with_rank_0_feature(self): price = fc._numeric_column('price') features = { 'price': constant_op.constant(0), } self.assertEqual(0, features['price'].shape.ndims) # Static rank 0 should fail with self.assertRaisesRegex(ValueError, 'Feature .* cannot have rank 0'): fc.linear_model(features, [price]) # Dynamic rank 0 should fail features = { 'price': array_ops.placeholder(dtypes.float32), } net = fc.linear_model(features, [price]) self.assertEqual(1, net.shape[1]) with _initialized_session() as sess: with self.assertRaisesOpError('Feature .* cannot have rank 0'): sess.run(net, feed_dict={features['price']: np.array(1)}) def test_multiple_linear_models(self): price = fc._numeric_column('price') with ops.Graph().as_default(): features1 = {'price': [[1.], [5.]]} features2 = {'price': [[2.], [10.]]} predictions1 = fc.linear_model(features1, [price]) predictions2 = fc.linear_model(features2, [price]) bias1 = get_linear_model_bias(name='linear_model') bias2 = get_linear_model_bias(name='linear_model_1') price_var1 = get_linear_model_column_var(price, name='linear_model') price_var2 = get_linear_model_column_var(price, name='linear_model_1') with _initialized_session() as sess: self.assertAllClose([0.], self.evaluate(bias1)) sess.run(price_var1.assign([[10.]])) sess.run(bias1.assign([5.])) self.assertAllClose([[15.], [55.]], self.evaluate(predictions1)) self.assertAllClose([0.], self.evaluate(bias2)) sess.run(price_var2.assign([[10.]])) sess.run(bias2.assign([5.])) self.assertAllClose([[25.], [105.]], self.evaluate(predictions2))
LinearModelTest
python
kamyu104__LeetCode-Solutions
Python/loud-and-rich.py
{ "start": 38, "end": 830 }
class ____(object): def loudAndRich(self, richer, quiet): """ :type richer: List[List[int]] :type quiet: List[int] :rtype: List[int] """ def dfs(graph, quiet, node, result): if result[node] is None: result[node] = node for nei in graph[node]: smallest_person = dfs(graph, quiet, nei, result) if quiet[smallest_person] < quiet[result[node]]: result[node] = smallest_person return result[node] graph = [[] for _ in xrange(len(quiet))] for u, v in richer: graph[v].append(u) result = [None]*len(quiet) return map(lambda x: dfs(graph, quiet, x, result), xrange(len(quiet)))
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/unit_tests/test_api.py
{ "start": 311, "end": 6665 }
class ____: @pytest.fixture def fb_api(self): return source_facebook_marketing.api.MyFacebookAdsApi.init(access_token="foo", crash_log=False) @pytest.mark.parametrize( "max_rate,max_pause_interval,min_pause_interval,usage,pause_interval,expected_pause_interval", [ ( 95, timedelta(minutes=5), timedelta(minutes=1), 96, timedelta(minutes=6), timedelta(minutes=6), ), ( 95, timedelta(minutes=5), timedelta(minutes=2), 96, timedelta(minutes=1), timedelta(minutes=5), ), ( 95, timedelta(minutes=5), timedelta(minutes=1), 93, timedelta(minutes=4), timedelta(minutes=4), ), ], ) def test__compute_pause_interval( self, mocker, fb_api, max_rate, max_pause_interval, min_pause_interval, usage, pause_interval, expected_pause_interval, ): mocker.patch.object(fb_api, "MAX_RATE", max_rate) mocker.patch.object(fb_api, "MAX_PAUSE_INTERVAL", max_pause_interval) mocker.patch.object(fb_api, "MIN_PAUSE_INTERVAL", min_pause_interval) computed_pause_interval = fb_api._compute_pause_interval(usage, pause_interval) assert computed_pause_interval == expected_pause_interval @pytest.mark.parametrize( "min_pause_interval,usages_pause_intervals,expected_output", [ ( timedelta(minutes=1), # min_pause_interval [ (5, timedelta(minutes=6)), (7, timedelta(minutes=5)), ], # usages_pause_intervals (7, timedelta(minutes=6)), # expected_output ), ( timedelta(minutes=10), # min_pause_interval [ (5, timedelta(minutes=6)), (7, timedelta(minutes=5)), ], # usages_pause_intervals (7, timedelta(minutes=10)), # expected_output ), ( timedelta(minutes=10), # min_pause_interval [ # usages_pause_intervals (9, timedelta(minutes=6)), ], (9, timedelta(minutes=10)), # expected_output ), ( timedelta(minutes=10), # min_pause_interval [ # usages_pause_intervals (-1, timedelta(minutes=1)), (-2, timedelta(minutes=10)), (-3, timedelta(minutes=100)), ], (0, timedelta(minutes=100)), # expected_output ), ], ) def test__get_max_usage_pause_interval_from_batch( self, mocker, fb_api, min_pause_interval, usages_pause_intervals, expected_output, ): records = [ { "headers": [ {"name": "USAGE", "value": usage}, {"name": "PAUSE_INTERVAL", "value": pause_interval}, ] } for usage, pause_interval in usages_pause_intervals ] mock_parse_call_rate_header = mocker.Mock(side_effect=usages_pause_intervals) mocker.patch.object(fb_api, "_parse_call_rate_header", mock_parse_call_rate_header) mocker.patch.object(fb_api, "MIN_PAUSE_INTERVAL", min_pause_interval) output = fb_api._get_max_usage_pause_interval_from_batch(records) fb_api._parse_call_rate_header.assert_called_with( { "usage": usages_pause_intervals[-1][0], "pause_interval": usages_pause_intervals[-1][1], } ) assert output == expected_output @pytest.mark.parametrize( "params,min_rate,usage,expect_sleep", [ (["batch"], 0, 1, True), (["batch"], 0, 0, True), (["batch"], 2, 1, False), (["not_batch"], 0, 1, True), (["not_batch"], 0, 0, True), (["not_batch"], 2, 1, False), ], ) def test__handle_call_rate_limit(self, mocker, fb_api, params, min_rate, usage, expect_sleep): pause_interval = 1 mock_response = mocker.Mock() mocker.patch.object(fb_api, "MIN_RATE", min_rate) mocker.patch.object( fb_api, "_get_max_usage_pause_interval_from_batch", mocker.Mock(return_value=(usage, pause_interval)), ) mocker.patch.object( fb_api, "_parse_call_rate_header", mocker.Mock(return_value=(usage, pause_interval)), ) mocker.patch.object(fb_api, "_compute_pause_interval") mocker.patch.object(source_facebook_marketing.api, "logger") mocker.patch.object(source_facebook_marketing.api, "sleep") assert fb_api._handle_call_rate_limit(mock_response, params) is None if "batch" in params: fb_api._get_max_usage_pause_interval_from_batch.assert_called_with(mock_response.json.return_value) else: fb_api._parse_call_rate_header.assert_called_with(mock_response.headers.return_value) if expect_sleep: fb_api._compute_pause_interval.assert_called_with(usage=usage, pause_interval=pause_interval) source_facebook_marketing.api.sleep.assert_called_with(fb_api._compute_pause_interval.return_value.total_seconds()) source_facebook_marketing.api.logger.warning.assert_called_with( f"Facebook API Utilization is too high ({usage})%, pausing for {fb_api._compute_pause_interval.return_value}" ) def test_find_account(self, api, account_id, requests_mock): requests_mock.register_uri( "GET", FacebookSession.GRAPH + f"/{FB_API_VERSION}/act_{account_id}/", [{"json": {"id": "act_test"}}], ) account = api.get_account(account_id) assert isinstance(account, AdAccount) assert account.get_id() == "act_test"
TestMyFacebookAdsApi
python
pallets__itsdangerous
src/itsdangerous/_json.py
{ "start": 78, "end": 473 }
class ____: """Wrapper around json module that strips whitespace.""" @staticmethod def loads(payload: str | bytes) -> t.Any: return _json.loads(payload) @staticmethod def dumps(obj: t.Any, **kwargs: t.Any) -> str: kwargs.setdefault("ensure_ascii", False) kwargs.setdefault("separators", (",", ":")) return _json.dumps(obj, **kwargs)
_CompactJSON
python
numpy__numpy
numpy/_core/tests/test_numerictypes.py
{ "start": 24078, "end": 24174 }
class ____: def test_bool_definition(self): assert nt.bool is np.bool
TestBoolDefinition
python
openai__openai-python
src/openai/types/beta/function_tool.py
{ "start": 249, "end": 397 }
class ____(BaseModel): function: FunctionDefinition type: Literal["function"] """The type of tool being defined: `function`"""
FunctionTool
python
huggingface__transformers
src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py
{ "start": 6296, "end": 11037 }
class ____(nn.Module): """ Multiscale deformable attention as proposed in Deformable DETR. """ def __init__(self, config: MMGroundingDinoConfig, num_heads: int, n_points: int): super().__init__() self.attn = MultiScaleDeformableAttention() if config.d_model % num_heads != 0: raise ValueError( f"embed_dim (d_model) must be divisible by num_heads, but got {config.d_model} and {num_heads}" ) dim_per_head = config.d_model // num_heads # check if dim_per_head is power of 2 if not ((dim_per_head & (dim_per_head - 1) == 0) and dim_per_head != 0): warnings.warn( "You'd better set embed_dim (d_model) in MMGroundingDinoMultiscaleDeformableAttention to make the" " dimension of each attention head a power of 2 which is more efficient in the authors' CUDA" " implementation." ) self.im2col_step = 64 self.d_model = config.d_model self.n_levels = config.num_feature_levels self.n_heads = num_heads self.n_points = n_points self.sampling_offsets = nn.Linear(config.d_model, num_heads * self.n_levels * n_points * 2) self.attention_weights = nn.Linear(config.d_model, num_heads * self.n_levels * n_points) self.value_proj = nn.Linear(config.d_model, config.d_model) self.output_proj = nn.Linear(config.d_model, config.d_model) self.disable_custom_kernels = config.disable_custom_kernels def with_pos_embed(self, tensor: torch.Tensor, position_embeddings: Optional[Tensor]): return tensor if position_embeddings is None else tensor + position_embeddings def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, encoder_hidden_states=None, encoder_attention_mask=None, position_embeddings: Optional[torch.Tensor] = None, reference_points=None, spatial_shapes=None, spatial_shapes_list=None, level_start_index=None, output_attentions: bool = False, ): # add position embeddings to the hidden states before projecting to queries and keys if position_embeddings is not None: hidden_states = self.with_pos_embed(hidden_states, position_embeddings) batch_size, num_queries, _ = hidden_states.shape batch_size, sequence_length, _ = encoder_hidden_states.shape # Ignore copy if (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() != sequence_length: raise ValueError( "Make sure to align the spatial shapes with the sequence length of the encoder hidden states" ) value = self.value_proj(encoder_hidden_states) if attention_mask is not None: # we invert the attention_mask value = value.masked_fill(~attention_mask[..., None], float(0)) value = value.view(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads) sampling_offsets = self.sampling_offsets(hidden_states).view( batch_size, num_queries, self.n_heads, self.n_levels, self.n_points, 2 ) attention_weights = self.attention_weights(hidden_states).view( batch_size, num_queries, self.n_heads, self.n_levels * self.n_points ) attention_weights = F.softmax(attention_weights, -1).view( batch_size, num_queries, self.n_heads, self.n_levels, self.n_points ) # batch_size, num_queries, n_heads, n_levels, n_points, 2 num_coordinates = reference_points.shape[-1] if num_coordinates == 2: offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1) sampling_locations = ( reference_points[:, :, None, :, None, :] + sampling_offsets / offset_normalizer[None, None, None, :, None, :] ) elif num_coordinates == 4: sampling_locations = ( reference_points[:, :, None, :, None, :2] + sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5 ) else: raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {reference_points.shape[-1]}") output = self.attn( value, spatial_shapes, spatial_shapes_list, level_start_index, sampling_locations, attention_weights, self.im2col_step, ) output = self.output_proj(output) return output, attention_weights
MMGroundingDinoMultiscaleDeformableAttention
python
getsentry__sentry
tests/sentry/sentry_apps/api/bases/test_sentryapps.py
{ "start": 9550, "end": 11071 }
class ____(TestCase): def setUp(self) -> None: self.endpoint = IntegrationPlatformEndpoint() def test_handle_sentry_app_error(self) -> None: error = SentryAppError(message="cool", status_code=400) response = self.endpoint._handle_sentry_app_exception(error) assert response.status_code == 400 assert response.exception is True assert response.data == {"detail": error.message} def test_handle_sentry_app_integrator_error(self) -> None: public_context = {"help": "123423123"} error = SentryAppIntegratorError( message="yep", webhook_context={"hi": "bye!"}, public_context=public_context, status_code=400, ) response = self.endpoint._handle_sentry_app_exception(error) assert response.status_code == 400 assert response.exception is True assert response.data == {"detail": error.message, "context": public_context} def test_handle_sentry_app_sentry_error(self) -> None: public_context = {"help": "123423123"} error = SentryAppSentryError( message="bruh", webhook_context={"bruh": "bruhhh"}, public_context=public_context ) response = self.endpoint._handle_sentry_app_exception(error) assert response.status_code == 500 assert response.data == { "detail": f"An issue occured during the integration platform process. Sentry error ID: {None}" }
IntegrationPlatformEndpointTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor28.py
{ "start": 323, "end": 479 }
class ____(ParentA, Generic[T]): def __init__(self, a: T) -> None: ... def func1(arg1: ParentA, arg2: ParentA): ... func1(ChildA(1), ChildA(2))
ChildA
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/match3.py
{ "start": 186, "end": 260 }
class ____(TypedDict): name: Literal["b"] other_extra_value: int
TD2
python
aio-libs__aiohttp
aiohttp/client.py
{ "start": 50492, "end": 54048 }
class ____: __slots__ = ("_coro", "_resp", "_session") def __init__( self, coro: Coroutine["asyncio.Future[Any]", None, ClientResponse], session: ClientSession, ) -> None: self._coro = coro self._resp: ClientResponse | None = None self._session = session async def __aenter__(self) -> ClientResponse: try: self._resp = await self._coro except BaseException: await self._session.close() raise else: return self._resp async def __aexit__( self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, ) -> None: assert self._resp is not None self._resp.close() await self._session.close() if sys.version_info >= (3, 11) and TYPE_CHECKING: def request( method: str, url: StrOrURL, *, version: HttpVersion = http.HttpVersion11, connector: BaseConnector | None = None, **kwargs: Unpack[_RequestOptions], ) -> _SessionRequestContextManager: ... else: def request( method: str, url: StrOrURL, *, version: HttpVersion = http.HttpVersion11, connector: BaseConnector | None = None, **kwargs: Any, ) -> _SessionRequestContextManager: """Constructs and sends a request. Returns response object. method - HTTP method url - request url params - (optional) Dictionary or bytes to be sent in the query string of the new request data - (optional) Dictionary, bytes, or file-like object to send in the body of the request json - (optional) Any json compatible python object headers - (optional) Dictionary of HTTP Headers to send with the request cookies - (optional) Dict object to send with the request auth - (optional) BasicAuth named tuple represent HTTP Basic Auth auth - aiohttp.helpers.BasicAuth allow_redirects - (optional) If set to False, do not follow redirects version - Request HTTP version. compress - Set to True if request has to be compressed with deflate encoding. chunked - Set to chunk size for chunked transfer encoding. expect100 - Expect 100-continue response from server. connector - BaseConnector sub-class instance to support connection pooling. read_until_eof - Read response until eof if response does not have Content-Length header. loop - Optional event loop. timeout - Optional ClientTimeout settings structure, 5min total timeout by default. Usage:: >>> import aiohttp >>> async with aiohttp.request('GET', 'http://python.org/') as resp: ... print(resp) ... data = await resp.read() <ClientResponse(https://www.python.org/) [200 OK]> """ connector_owner = False if connector is None: connector_owner = True connector = TCPConnector(force_close=True) session = ClientSession( cookies=kwargs.pop("cookies", None), version=version, timeout=kwargs.pop("timeout", sentinel), connector=connector, connector_owner=connector_owner, ) return _SessionRequestContextManager( session._request(method, url, **kwargs), session, )
_SessionRequestContextManager
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 188019, "end": 190928 }
class ____(VegaLiteSchema): """ BinParams schema wrapper. Binning properties or boolean flag for determining whether to bin data or not. Parameters ---------- anchor : float A value in the binned domain at which to anchor the bins, shifting the bin boundaries if necessary to ensure that a boundary aligns with the anchor value. **Default value:** the minimum bin extent value base : float The number base to use for automatic bin determination (default is base 10). **Default value:** ``10`` binned : bool When set to ``true``, Vega-Lite treats the input data as already binned. divide : Sequence[float] Scale factors indicating allowable subdivisions. The default value is [5, 2], which indicates that for base 10 numbers (the default base), the method may consider dividing bin sizes by 5 and/or 2. For example, for an initial step size of 10, the method can check if bin sizes of 2 (= 10/5), 5 (= 10/2), or 1 (= 10/(5*2)) might also satisfy the given constraints. **Default value:** ``[5, 2]`` extent : dict, Sequence[float], :class:`BinExtent`, :class:`ParameterExtent` A two-element (``[min, max]``) array indicating the range of desired bin values. maxbins : float Maximum number of bins. **Default value:** ``6`` for ``row``, ``column`` and ``shape`` channels; ``10`` for other channels minstep : float A minimum allowable step size (particularly useful for integer values). nice : bool If true, attempts to make the bin boundaries use human-friendly boundaries, such as multiples of ten. **Default value:** ``true`` step : float An exact step size to use between bins. **Note:** If provided, options such as maxbins will be ignored. steps : Sequence[float] An array of allowable step sizes to choose from. """ _schema = {"$ref": "#/definitions/BinParams"} def __init__( self, anchor: Optional[float] = Undefined, base: Optional[float] = Undefined, binned: Optional[bool] = Undefined, divide: Optional[Sequence[float]] = Undefined, extent: Optional[Parameter | SchemaBase | Sequence[float] | Map] = Undefined, maxbins: Optional[float] = Undefined, minstep: Optional[float] = Undefined, nice: Optional[bool] = Undefined, step: Optional[float] = Undefined, steps: Optional[Sequence[float]] = Undefined, **kwds, ): super().__init__( anchor=anchor, base=base, binned=binned, divide=divide, extent=extent, maxbins=maxbins, minstep=minstep, nice=nice, step=step, steps=steps, **kwds, )
BinParams
python
walkccc__LeetCode
solutions/780. Reaching Points/780.py
{ "start": 0, "end": 272 }
class ____: def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool: while sx < tx and sy < ty: tx, ty = tx % ty, ty % tx return (sx == tx and sy <= ty and (ty - sy) % tx == 0 or sy == ty and sx <= tx and (tx - sx) % ty == 0)
Solution
python
huggingface__transformers
src/transformers/models/aria/modular_aria.py
{ "start": 18751, "end": 40389 }
class ____(BaseImageProcessor): """ A vision processor for the Aria model that handles image preprocessing. Initialize the AriaImageProcessor. Args: image_mean (`list`, *optional*, defaults to [0.5, 0.5, 0.5]): Mean values for normalization. image_std (`list`, *optional*, defaults to [0.5, 0.5, 0.5]): Standard deviation values for normalization. max_image_size (`int`, *optional*, defaults to 980): Maximum image size. min_image_size (`int`, *optional*, defaults to 336): Minimum image size. split_resolutions (`list`, *optional*, defaults to a list of optimal,resolutions as tuples): The optimal resolutions for splitting the image. split_image (`bool`, *optional*, defaults to `False`): Whether to split the image. do_convert_rgb (`bool`, *optional*, defaults to `True`): Whether to convert the image to RGB. do_rescale (`bool`, *optional*, defaults to `True`): Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in the `preprocess` method. rescale_factor (`int` or `float`, *optional*, defaults to `1/255`): Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess` method. do_normalize (`bool`, *optional*, defaults to `True`): Whether to normalize the image. resample (PILImageResampling, *optional*, defaults to `BICUBIC`): The resampling filter to use if resizing the image. """ model_input_names = ["pixel_values", "pixel_mask", "num_crops"] def __init__( self, image_mean: Optional[list[float]] = None, image_std: Optional[list[float]] = None, max_image_size: int = 980, min_image_size: int = 336, split_resolutions: Optional[list[tuple[int, int]]] = None, split_image: Optional[bool] = False, do_convert_rgb: Optional[bool] = True, do_rescale: bool = True, rescale_factor: Union[int, float] = 1 / 255, do_normalize: Optional[bool] = True, resample: PILImageResampling = PILImageResampling.BICUBIC, **kwargs, ): super().__init__(**kwargs) if image_mean is None: image_mean = [0.5, 0.5, 0.5] if image_std is None: image_std = [0.5, 0.5, 0.5] self.max_image_size = max_image_size self.min_image_size = min_image_size self.image_mean = image_mean self.image_std = image_std self.split_image = split_image if split_resolutions is None: split_resolutions = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, 4), (2, 3), (2, 2), (2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (5, 1), (6, 1), (7, 1), (8, 1)] # fmt: skip split_resolutions = [(el[0] * 490, el[1] * 490) for el in split_resolutions] self.split_resolutions = split_resolutions self.do_convert_rgb = do_convert_rgb self.do_rescale = do_rescale self.rescale_factor = rescale_factor self.do_normalize = do_normalize self.resample = resample def preprocess( self, images: Union[ImageInput, list[ImageInput]], image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, max_image_size: Optional[int] = None, min_image_size: Optional[int] = None, split_image: Optional[bool] = None, do_convert_rgb: Optional[bool] = None, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, resample: Optional[PILImageResampling] = None, return_tensors: Optional[Union[str, TensorType]] = "pt", data_format: Optional[ChannelDimension] = ChannelDimension.FIRST, input_data_format: Optional[Union[str, ChannelDimension]] = None, ): """ Process a list of images. Args: images (ImageInput or list of ImageInput): The input image or a list of images. image_mean (`list`, *optional*, defaults to [0.5, 0.5, 0.5]): Mean values for normalization. image_std (`list`, *optional*, defaults to [0.5, 0.5, 0.5]): Standard deviation values for normalization. max_image_size (`int`, *optional*, defaults to `self.max_image_size` (980)): Maximum image size. min_image_size (`int`, *optional*, defaults to `self.min_image_size` (336)): Minimum image size. split_image (`bool`, *optional*, defaults to `self.split_image` (False)): Whether to split the image. do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb` (True)): Whether to convert the image to RGB. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): Whether to rescale the image. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): Rescale factor to rescale the image by if `do_rescale` is set to `True`. do_normalize (`bool`, *optional*, defaults to `self.do_normalize` (True)): Whether to normalize the image. resample (PILImageResampling, *optional*, defaults to `self.resample` (BICUBIC)): The resampling filter to use if resizing the image. return_tensors (`str` or `TensorType`, *optional*, defaults to "pt"): The type of tensor to return. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the output image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use same as the input image. input_data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use the inferred format of the input image. Returns: BatchFeature: A BatchFeature object containing: - 'pixel_values': Tensor of processed image pixel values. - 'pixel_mask': Boolean pixel mask. This mask is a 2D tensor of shape (max_image_size, max_image_size) where: - True (1) values indicate pixels that belong to the original resized image. - False (0) values indicate pixels that are part of the padding. The mask helps distinguish between actual image content and padded areas in subsequent processing steps. - 'num_crops': The maximum number of crops across all images. """ image_mean = image_mean if image_mean is not None else self.image_mean image_std = image_std if image_std is not None else self.image_std max_image_size = max_image_size if max_image_size is not None else self.max_image_size min_image_size = min_image_size if min_image_size is not None else self.min_image_size split_image = split_image if split_image is not None else self.split_image do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb do_rescale = do_rescale if do_rescale is not None else self.do_rescale rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor do_normalize = do_normalize if do_normalize is not None else self.do_normalize resample = resample if resample is not None else self.resample if max_image_size not in [490, 980]: raise ValueError("max_image_size must be either 490 or 980") images = self.fetch_images(images) images = make_flat_list_of_images(images) if not valid_images(images): raise ValueError("Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor") validate_preprocess_arguments( do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, resample=resample, do_rescale=do_rescale, rescale_factor=rescale_factor, ) if do_convert_rgb: images = [convert_to_rgb(image) for image in images] # All transformations expect numpy arrays. images = [to_numpy_array(image) for image in images] if do_rescale and is_scaled_image(images[0]): logger.warning_once( "It looks like you are trying to rescale already rescaled images. If the input" " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again." ) if input_data_format is None: # We assume that all images have the same channel dimension format. input_data_format = infer_channel_dimension_format(images[0]) pixel_values = [] pixel_masks = [] num_crops = None for image in images: if split_image: crop_images = self.get_image_patches( image, self.split_resolutions, max_image_size, resample, data_format=input_data_format, input_data_format=input_data_format, ) else: crop_images = [image] if num_crops is None or len(crop_images) > num_crops: num_crops = len(crop_images) for crop_image in crop_images: # At this point the scale is the rescaling factor that would bring the image to max_size in its larger dimension h, w = get_image_size(crop_image) scale = max_image_size / max(h, w) if w >= h: new_size = (max(int(h * scale), min_image_size), max_image_size) # h, w else: new_size = (max_image_size, max(int(w * scale), min_image_size)) # h, w crop_image_resized = resize( crop_image, new_size, resample=resample, data_format=input_data_format, input_data_format=input_data_format, ) padding_bottom, padding_right = max_image_size - new_size[0], max_image_size - new_size[1] crop_image_padded = pad( crop_image_resized, ((0, padding_bottom), (0, padding_right)), data_format=input_data_format, input_data_format=input_data_format, ) # Create a pixel mask pixel_mask = np.zeros((max_image_size, max_image_size), dtype=bool) pixel_mask[: new_size[0], : new_size[1]] = 1 pixel_masks.append(pixel_mask) if do_rescale: crop_image_padded = self.rescale( image=crop_image_padded, scale=rescale_factor, input_data_format=input_data_format ) if do_normalize: crop_image_padded = self.normalize( crop_image_padded, self.image_mean, self.image_std, data_format=input_data_format, input_data_format=input_data_format, ) crop_image_padded = ( to_channel_dimension_format(crop_image_padded, data_format, input_data_format) if data_format is not None else crop_image_padded ) pixel_values.append(crop_image_padded) return BatchFeature( data={ "pixel_values": np.stack(pixel_values, axis=0), "pixel_mask": np.stack(pixel_masks, axis=0), "num_crops": num_crops, }, tensor_type=return_tensors, ) def _resize_for_patching( self, image: np.ndarray, target_resolution: tuple, resample, input_data_format: ChannelDimension ) -> np.ndarray: """ Resizes an image to a target resolution while maintaining aspect ratio. Args: image (np.ndarray): The input image. target_resolution (tuple): The target resolution (height, width) of the image. resample (`PILImageResampling`): Resampling filter to use if resizing the image. input_data_format (`ChannelDimension` or `str`): The channel dimension format of the input image. Returns: np.ndarray: The resized and padded image. """ new_height, new_width = get_patch_output_size(image, target_resolution, input_data_format) # Resize the image resized_image = resize(image, (new_height, new_width), resample=resample, input_data_format=input_data_format) return resized_image def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple): original_height, original_width = original_resolution target_height, target_width = target_resolution paste_x, r_x = divmod(target_width - original_width, 2) paste_y, r_y = divmod(target_height - original_height, 2) return (paste_y, paste_y + r_y), (paste_x, paste_x + r_x) def _pad_for_patching( self, image: np.ndarray, target_resolution: tuple, input_data_format: ChannelDimension ) -> np.ndarray: """ Pad an image to a target resolution while maintaining aspect ratio. """ new_resolution = get_patch_output_size(image, target_resolution, input_data_format) padding = self._get_padding_size(new_resolution, target_resolution) padded_image = self.pad(image, padding=padding) return padded_image def pad( self, image: np.ndarray, padding: Union[int, tuple[int, int], Iterable[tuple[int, int]]], mode: PaddingMode = PaddingMode.CONSTANT, constant_values: Union[float, Iterable[float]] = 0.0, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Pads the `image` with the specified `padding` and `mode`. Padding can be in the (`height`, `width`) dimension of in the (`num_patches`) dimension. In the second case an iterable if tuples is expected as input. Args: image (`np.ndarray`): The image to pad. padding (`int` or `tuple[int, int]` or `Iterable[tuple[int, int]]`): Padding to apply to the edges of the height, width axes. Can be one of three formats: - `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis. - `((before, after),)` yields same before and after pad for height and width. - `(pad,)` or int is a shortcut for before = after = pad width for all axes. mode (`PaddingMode`): The padding mode to use. Can be one of: - `"constant"`: pads with a constant value. - `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the vector along each axis. - `"replicate"`: pads with the replication of the last value on the edge of the array along each axis. - `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array. constant_values (`float` or `Iterable[float]`, *optional*): The value to use for the padding if `mode` is `"constant"`. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the output image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use same as the input image. input_data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use the inferred format of the input image. Returns: `np.ndarray`: The padded image. """ # call the general `pad` if padding on `height/width`, otherwise it's the `num_patched` dim if isinstance(padding, int) or len(padding) != 4: return pad(image, padding, mode, constant_values, data_format, input_data_format) if input_data_format is None: input_data_format = infer_channel_dimension_format(image) padding_mode_mapping = { PaddingMode.CONSTANT: "constant", PaddingMode.REFLECT: "reflect", PaddingMode.REPLICATE: "edge", PaddingMode.SYMMETRIC: "symmetric", } image = np.pad(image, padding, mode=padding_mode_mapping[mode], constant_values=constant_values) image = ( to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image ) return image def get_image_patches( self, image: np.ndarray, grid_pinpoints: list[tuple[int, int]], patch_size: int, resample: PILImageResampling, data_format: ChannelDimension, input_data_format: ChannelDimension, ) -> list[np.ndarray]: """ Process an image with variable resolutions by dividing it into patches. Args: image (`np.ndarray`): The input image to be processed. grid_pinpoints (list[tuple[int, int]]): A list of possible resolutions as tuples. patch_size (`int`): Size of the patches to divide the image into. resample (`PILImageResampling`): Resampling filter to use if resizing the image. data_format (`ChannelDimension` or `str`): The channel dimension format for the output image. input_data_format (`ChannelDimension` or `str`): The channel dimension format of the input image. Returns: `list[np.ndarray]`: A list of NumPy arrays containing the processed image patches. """ if not isinstance(grid_pinpoints, list): raise TypeError("grid_pinpoints must be a list of possible resolutions.") possible_resolutions = grid_pinpoints image_size = get_image_size(image, channel_dim=input_data_format) best_resolution = select_best_resolution(image_size, possible_resolutions) resized_image = self._resize_for_patching( image, best_resolution, resample=resample, input_data_format=input_data_format ) padded_image = self._pad_for_patching(resized_image, best_resolution, input_data_format=input_data_format) patches = divide_to_patches(padded_image, patch_size=patch_size, input_data_format=input_data_format) # make sure that all patches are in the input data format patches = [ to_channel_dimension_format(patch, channel_dim=data_format, input_channel_dim=input_data_format) for patch in patches ] return patches def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None): """ A utility that returns number of image patches for a given image size. Args: height (`int`): Height of the input image. width (`int`): Width of the input image. images_kwargs (`dict`, *optional*) Any kwargs to override defaults of the image processor. Returns: `int`: Number of patches per image. """ split_image = images_kwargs.get("split_image", self.split_image) max_image_size = images_kwargs.get("max_image_size", self.max_image_size) resized_height, resized_width = select_best_resolution((height, width), self.split_resolutions) num_patches = 1 if not split_image else resized_height // max_image_size * resized_width // max_image_size return num_patches
AriaImageProcessor
python
walkccc__LeetCode
solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.py
{ "start": 0, "end": 248 }
class ____: def maximumBeauty(self, nums: list[int], k: int) -> int: ans = 0 nums.sort() l = 0 for r in range(len(nums)): while nums[r] - nums[l] > 2 * k: l += 1 ans = max(ans, r - l + 1) return ans
Solution
python
pydata__xarray
xarray/tests/test_combine.py
{ "start": 12882, "end": 29240 }
class ____: def test_nested_concat(self): objs = [Dataset({"x": [0]}), Dataset({"x": [1]})] expected = Dataset({"x": [0, 1]}) actual = combine_nested(objs, concat_dim="x") assert_identical(expected, actual) actual = combine_nested(objs, concat_dim=["x"]) assert_identical(expected, actual) actual = combine_nested([actual], concat_dim=None) assert_identical(expected, actual) actual = combine_nested([actual], concat_dim="x") assert_identical(expected, actual) objs = [Dataset({"x": [0, 1]}), Dataset({"x": [2]})] actual = combine_nested(objs, concat_dim="x") expected = Dataset({"x": [0, 1, 2]}) assert_identical(expected, actual) # ensure combine_nested handles non-sorted variables objs = [ Dataset({"x": ("a", [0]), "y": ("a", [0])}), Dataset({"y": ("a", [1]), "x": ("a", [1])}), ] actual = combine_nested(objs, concat_dim="a") expected = Dataset({"x": ("a", [0, 1]), "y": ("a", [0, 1])}) assert_identical(expected, actual) objs = [Dataset({"x": [0], "y": [0]}), Dataset({"x": [1]})] actual = combine_nested(objs, concat_dim="x") expected = Dataset({"x": [0, 1], "y": [0]}) assert_identical(expected, actual) @pytest.mark.parametrize( "join, expected", [ ("outer", Dataset({"x": [0, 1], "y": [0, 1]})), ("inner", Dataset({"x": [0, 1], "y": []})), ("left", Dataset({"x": [0, 1], "y": [0]})), ("right", Dataset({"x": [0, 1], "y": [1]})), ], ) def test_combine_nested_join(self, join, expected): objs = [Dataset({"x": [0], "y": [0]}), Dataset({"x": [1], "y": [1]})] actual = combine_nested(objs, concat_dim="x", join=join) assert_identical(expected, actual) def test_combine_nested_join_exact(self): objs = [Dataset({"x": [0], "y": [0]}), Dataset({"x": [1], "y": [1]})] with pytest.raises(ValueError, match=r"cannot align.*join.*exact"): combine_nested(objs, concat_dim="x", join="exact") def test_empty_input(self): assert_identical(Dataset(), combine_nested([], concat_dim="x")) # Fails because of concat's weird treatment of dimension coords, see #2975 @pytest.mark.xfail def test_nested_concat_too_many_dims_at_once(self): objs = [Dataset({"x": [0], "y": [1]}), Dataset({"y": [0], "x": [1]})] with pytest.raises(ValueError, match="not equal across datasets"): combine_nested(objs, concat_dim="x", coords="minimal") def test_nested_concat_along_new_dim(self): objs = [ Dataset({"a": ("x", [10]), "x": [0]}), Dataset({"a": ("x", [20]), "x": [0]}), ] expected = Dataset({"a": (("t", "x"), [[10], [20]]), "x": [0]}) actual = combine_nested(objs, data_vars="all", concat_dim="t") assert_identical(expected, actual) # Same but with a DataArray as new dim, see GH #1988 and #2647 dim = DataArray([100, 150], name="baz", dims="baz") expected = Dataset( {"a": (("baz", "x"), [[10], [20]]), "x": [0], "baz": [100, 150]} ) actual = combine_nested(objs, data_vars="all", concat_dim=dim) assert_identical(expected, actual) def test_nested_merge_with_self(self): data = Dataset({"x": 0}) actual = combine_nested([data, data, data], concat_dim=None) assert_identical(data, actual) def test_nested_merge_with_overlapping_values(self): ds1 = Dataset({"a": ("x", [1, 2]), "x": [0, 1]}) ds2 = Dataset({"a": ("x", [2, 3]), "x": [1, 2]}) expected = Dataset({"a": ("x", [1, 2, 3]), "x": [0, 1, 2]}) with pytest.warns( FutureWarning, match="will change from compat='no_conflicts' to compat='override'", ): actual = combine_nested([ds1, ds2], join="outer", concat_dim=None) assert_identical(expected, actual) actual = combine_nested( [ds1, ds2], join="outer", compat="no_conflicts", concat_dim=None ) assert_identical(expected, actual) actual = combine_nested( [ds1, ds2], join="outer", compat="no_conflicts", concat_dim=[None] ) assert_identical(expected, actual) def test_nested_merge_with_nan_no_conflicts(self): tmp1 = Dataset({"x": 0}) tmp2 = Dataset({"x": np.nan}) actual = combine_nested([tmp1, tmp2], compat="no_conflicts", concat_dim=None) assert_identical(tmp1, actual) with pytest.warns( FutureWarning, match="will change from compat='no_conflicts' to compat='override'", ): combine_nested([tmp1, tmp2], concat_dim=None) actual = combine_nested([tmp1, tmp2], compat="no_conflicts", concat_dim=[None]) assert_identical(tmp1, actual) def test_nested_merge_with_concat_dim_explicitly_provided(self): # Test the issue reported in GH #1988 objs = [Dataset({"x": 0, "y": 1})] dim = DataArray([100], name="baz", dims="baz") actual = combine_nested(objs, concat_dim=[dim], data_vars="all") expected = Dataset({"x": ("baz", [0]), "y": ("baz", [1])}, {"baz": [100]}) assert_identical(expected, actual) def test_nested_merge_with_non_scalars(self): # Just making sure that auto_combine is doing what is # expected for non-scalar values, too. objs = [Dataset({"x": ("z", [0, 1]), "y": ("z", [1, 2])})] dim = DataArray([100], name="baz", dims="baz") actual = combine_nested(objs, concat_dim=[dim], data_vars="all") expected = Dataset( {"x": (("baz", "z"), [[0, 1]]), "y": (("baz", "z"), [[1, 2]])}, {"baz": [100]}, ) assert_identical(expected, actual) def test_concat_multiple_dims(self): objs = [ [Dataset({"a": (("x", "y"), [[0]])}), Dataset({"a": (("x", "y"), [[1]])})], [Dataset({"a": (("x", "y"), [[2]])}), Dataset({"a": (("x", "y"), [[3]])})], ] actual = combine_nested(objs, concat_dim=["x", "y"]) expected = Dataset({"a": (("x", "y"), [[0, 1], [2, 3]])}) assert_identical(expected, actual) def test_concat_name_symmetry(self): """Inspired by the discussion on GH issue #2777""" da1 = DataArray(name="a", data=[[0]], dims=["x", "y"]) da2 = DataArray(name="b", data=[[1]], dims=["x", "y"]) da3 = DataArray(name="a", data=[[2]], dims=["x", "y"]) da4 = DataArray(name="b", data=[[3]], dims=["x", "y"]) x_first = combine_nested([[da1, da2], [da3, da4]], concat_dim=["x", "y"]) y_first = combine_nested([[da1, da3], [da2, da4]], concat_dim=["y", "x"]) assert_identical(x_first, y_first) def test_concat_one_dim_merge_another(self): data = create_test_data(add_attrs=False) data1 = data.copy(deep=True) data2 = data.copy(deep=True) objs = [ [data1.var1.isel(dim2=slice(4)), data2.var1.isel(dim2=slice(4, 9))], [data1.var2.isel(dim2=slice(4)), data2.var2.isel(dim2=slice(4, 9))], ] expected = data[["var1", "var2"]] actual = combine_nested(objs, concat_dim=[None, "dim2"]) assert_identical(expected, actual) def test_auto_combine_2d(self): ds = create_test_data partway1 = concat([ds(0), ds(3)], dim="dim1") partway2 = concat([ds(1), ds(4)], dim="dim1") partway3 = concat([ds(2), ds(5)], dim="dim1") expected = concat([partway1, partway2, partway3], data_vars="all", dim="dim2") datasets = [[ds(0), ds(1), ds(2)], [ds(3), ds(4), ds(5)]] result = combine_nested( datasets, data_vars="all", concat_dim=["dim1", "dim2"], ) assert_equal(result, expected) def test_auto_combine_2d_combine_attrs_kwarg(self): ds = lambda x: create_test_data(x, add_attrs=False) partway1 = concat([ds(0), ds(3)], dim="dim1") partway2 = concat([ds(1), ds(4)], dim="dim1") partway3 = concat([ds(2), ds(5)], dim="dim1") expected = concat([partway1, partway2, partway3], data_vars="all", dim="dim2") expected_dict = {} expected_dict["drop"] = expected.copy(deep=True) expected_dict["drop"].attrs = {} expected_dict["no_conflicts"] = expected.copy(deep=True) expected_dict["no_conflicts"].attrs = { "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, } expected_dict["override"] = expected.copy(deep=True) expected_dict["override"].attrs = {"a": 1} f = lambda attrs, context: attrs[0] expected_dict[f] = expected.copy(deep=True) # type: ignore[index] expected_dict[f].attrs = f([{"a": 1}], None) # type: ignore[index] datasets = [[ds(0), ds(1), ds(2)], [ds(3), ds(4), ds(5)]] datasets[0][0].attrs = {"a": 1} datasets[0][1].attrs = {"a": 1, "b": 2} datasets[0][2].attrs = {"a": 1, "c": 3} datasets[1][0].attrs = {"a": 1, "d": 4} datasets[1][1].attrs = {"a": 1, "e": 5} datasets[1][2].attrs = {"a": 1, "f": 6} with pytest.raises(ValueError, match=r"combine_attrs='identical'"): result = combine_nested( datasets, concat_dim=["dim1", "dim2"], data_vars="all", combine_attrs="identical", ) for combine_attrs, expected in expected_dict.items(): result = combine_nested( datasets, concat_dim=["dim1", "dim2"], data_vars="all", combine_attrs=combine_attrs, ) # type: ignore[call-overload] assert_identical(result, expected) def test_combine_nested_missing_data_new_dim(self): # Your data includes "time" and "station" dimensions, and each year's # data has a different set of stations. datasets = [ Dataset({"a": ("x", [2, 3]), "x": [1, 2]}), Dataset({"a": ("x", [1, 2]), "x": [0, 1]}), ] expected = Dataset( {"a": (("t", "x"), [[np.nan, 2, 3], [1, 2, np.nan]])}, {"x": [0, 1, 2]} ) actual = combine_nested(datasets, data_vars="all", join="outer", concat_dim="t") assert_identical(expected, actual) def test_invalid_hypercube_input(self): ds = create_test_data datasets = [[ds(0), ds(1), ds(2)], [ds(3), ds(4)]] with pytest.raises( ValueError, match=r"sub-lists do not have consistent lengths" ): combine_nested(datasets, concat_dim=["dim1", "dim2"]) datasets2: list = [[ds(0), ds(1)], [[ds(3), ds(4)]]] with pytest.raises( ValueError, match=r"sub-lists do not have consistent depths" ): combine_nested(datasets2, concat_dim=["dim1", "dim2"]) datasets = [[ds(0), ds(1)], [ds(3), ds(4)]] with pytest.raises(ValueError, match=r"concat_dims has length"): combine_nested(datasets, concat_dim=["dim1"]) def test_merge_one_dim_concat_another(self): objs = [ [Dataset({"foo": ("x", [0, 1])}), Dataset({"bar": ("x", [10, 20])})], [Dataset({"foo": ("x", [2, 3])}), Dataset({"bar": ("x", [30, 40])})], ] expected = Dataset({"foo": ("x", [0, 1, 2, 3]), "bar": ("x", [10, 20, 30, 40])}) actual = combine_nested(objs, concat_dim=["x", None], compat="equals") assert_identical(expected, actual) # Proving it works symmetrically objs = [ [Dataset({"foo": ("x", [0, 1])}), Dataset({"foo": ("x", [2, 3])})], [Dataset({"bar": ("x", [10, 20])}), Dataset({"bar": ("x", [30, 40])})], ] actual = combine_nested(objs, concat_dim=[None, "x"], compat="equals") assert_identical(expected, actual) def test_combine_concat_over_redundant_nesting(self): objs = [[Dataset({"x": [0]}), Dataset({"x": [1]})]] actual = combine_nested(objs, concat_dim=[None, "x"]) expected = Dataset({"x": [0, 1]}) assert_identical(expected, actual) objs = [[Dataset({"x": [0]})], [Dataset({"x": [1]})]] actual = combine_nested(objs, concat_dim=["x", None]) expected = Dataset({"x": [0, 1]}) assert_identical(expected, actual) objs = [[Dataset({"x": [0]})]] actual = combine_nested(objs, concat_dim=[None, None]) expected = Dataset({"x": [0]}) assert_identical(expected, actual) @pytest.mark.parametrize("fill_value", [dtypes.NA, 2, 2.0, {"a": 2, "b": 1}]) def test_combine_nested_fill_value(self, fill_value): datasets = [ Dataset({"a": ("x", [2, 3]), "b": ("x", [-2, 1]), "x": [1, 2]}), Dataset({"a": ("x", [1, 2]), "b": ("x", [3, -1]), "x": [0, 1]}), ] if fill_value == dtypes.NA: # if we supply the default, we expect the missing value for a # float array fill_value_a = fill_value_b = np.nan elif isinstance(fill_value, dict): fill_value_a = fill_value["a"] fill_value_b = fill_value["b"] else: fill_value_a = fill_value_b = fill_value expected = Dataset( { "a": (("t", "x"), [[fill_value_a, 2, 3], [1, 2, fill_value_a]]), "b": (("t", "x"), [[fill_value_b, -2, 1], [3, -1, fill_value_b]]), }, {"x": [0, 1, 2]}, ) actual = combine_nested( datasets, concat_dim="t", data_vars="all", join="outer", fill_value=fill_value, ) assert_identical(expected, actual) def test_combine_nested_unnamed_data_arrays(self): unnamed_array = DataArray(data=[1.0, 2.0], coords={"x": [0, 1]}, dims="x") actual = combine_nested([unnamed_array], concat_dim="x") expected = unnamed_array assert_identical(expected, actual) unnamed_array1 = DataArray(data=[1.0, 2.0], coords={"x": [0, 1]}, dims="x") unnamed_array2 = DataArray(data=[3.0, 4.0], coords={"x": [2, 3]}, dims="x") actual = combine_nested([unnamed_array1, unnamed_array2], concat_dim="x") expected = DataArray( data=[1.0, 2.0, 3.0, 4.0], coords={"x": [0, 1, 2, 3]}, dims="x" ) assert_identical(expected, actual) da1 = DataArray(data=[[0.0]], coords={"x": [0], "y": [0]}, dims=["x", "y"]) da2 = DataArray(data=[[1.0]], coords={"x": [0], "y": [1]}, dims=["x", "y"]) da3 = DataArray(data=[[2.0]], coords={"x": [1], "y": [0]}, dims=["x", "y"]) da4 = DataArray(data=[[3.0]], coords={"x": [1], "y": [1]}, dims=["x", "y"]) objs = [[da1, da2], [da3, da4]] expected = DataArray( data=[[0.0, 1.0], [2.0, 3.0]], coords={"x": [0, 1], "y": [0, 1]}, dims=["x", "y"], ) actual = combine_nested(objs, concat_dim=["x", "y"]) assert_identical(expected, actual) # TODO aijams - Determine if this test is appropriate. def test_nested_combine_mixed_datasets_arrays(self): objs = [ DataArray([0, 1], dims=("x"), coords=({"x": [0, 1]})), Dataset({"x": [2, 3]}), ] with pytest.raises( ValueError, match=r"Can't combine datasets with unnamed arrays." ): combine_nested(objs, "x") # type: ignore[arg-type] def test_nested_combine_mixed_datatrees_and_datasets(self): objs = [DataTree.from_dict({"foo": 0}), Dataset({"foo": 1})] with pytest.raises( ValueError, match=r"Can't combine a mix of DataTree and non-DataTree objects.", ): combine_nested(objs, concat_dim="x") # type: ignore[arg-type] def test_datatree(self): objs = [DataTree.from_dict({"foo": 0}), DataTree.from_dict({"foo": 1})] expected = DataTree.from_dict({"foo": ("x", [0, 1])}) actual = combine_nested(objs, concat_dim="x") assert expected.identical(actual)
TestNestedCombine
python
eventlet__eventlet
tests/db_pool_test.py
{ "start": 17078, "end": 17474 }
class ____(tests.LimitedTestCase): __test__ = False def test_cursor_works_as_context_manager(self): with self.connection.cursor() as c: c.execute('select 1') row = c.fetchone() assert row == (1,) def test_set_isolation_level(self): self.connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
TestPsycopg2Base
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_vies_vat.py
{ "start": 887, "end": 1879 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_vies_vat" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): return column.apply(lambda x: is_valid_vies_vat(x)) # This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine # @column_condition_partial(engine=SqlAlchemyExecutionEngine) # def _sqlalchemy(cls, column, _dialect, **kwargs): # raise NotImplementedError # This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine # @column_condition_partial(engine=SparkDFExecutionEngine) # def _spark(cls, column, **kwargs): # raise NotImplementedError # This class defines the Expectation itself
ColumnValuesToBeValidViesVat
python
pola-rs__polars
py-polars/src/polars/io/iceberg/_utils.py
{ "start": 14387, "end": 17751 }
class ____: column_name: str column_dtype: pl.DataType field_id: int load_from_bytes_impl: LoadFromBytesImpl | None null_count: list[int | None] min_values: list[bytes | None] max_values: list[bytes | None] def push_file_statistics(self, file: DataFile) -> None: self.null_count.append(file.null_value_counts.get(self.field_id)) if self.load_from_bytes_impl is not None: self.min_values.append(file.lower_bounds.get(self.field_id)) self.max_values.append(file.upper_bounds.get(self.field_id)) def finish( self, expected_height: int, identity_transformed_values: pl.Series | None, ) -> pl.DataFrame: import polars as pl c = self.column_name assert len(self.null_count) == expected_height out = pl.Series(f"{c}_nc", self.null_count, dtype=pl.UInt32).to_frame() if self.load_from_bytes_impl is None: s = ( identity_transformed_values if identity_transformed_values is not None else pl.repeat(None, expected_height, dtype=self.column_dtype) ) return out.with_columns(s.alias(f"{c}_min"), s.alias(f"{c}_max")) assert len(self.min_values) == expected_height assert len(self.max_values) == expected_height if self.column_dtype.is_nested(): raise NotImplementedError min_values = self.load_from_bytes_impl.load_from_bytes(self.min_values) max_values = self.load_from_bytes_impl.load_from_bytes(self.max_values) if identity_transformed_values is not None: assert identity_transformed_values.dtype == self.column_dtype identity_transformed_values = identity_transformed_values.extend_constant( None, expected_height - identity_transformed_values.len() ) min_values = identity_transformed_values.fill_null(min_values) max_values = identity_transformed_values.fill_null(max_values) return out.with_columns( min_values.alias(f"{c}_min"), max_values.alias(f"{c}_max") ) # Lazy init instead of global const as PyIceberg is an optional dependency @cache def _bytes_loader_lookup() -> dict[ type[IcebergType], tuple[type[LoadFromBytesImpl], type[IcebergType] | Sequence[type[IcebergType]]], ]: from pyiceberg.types import ( BinaryType, BooleanType, DateType, DecimalType, FixedType, IntegerType, LongType, StringType, TimestampType, TimestamptzType, TimeType, ) # TODO: Float statistics return { BooleanType: (LoadBooleanFromBytes, BooleanType), DateType: (LoadDateFromBytes, DateType), TimeType: (LoadTimeFromBytes, TimeType), TimestampType: (LoadTimestampFromBytes, TimestampType), TimestamptzType: (LoadTimestamptzFromBytes, TimestamptzType), IntegerType: (LoadInt32FromBytes, IntegerType), LongType: (LoadInt64FromBytes, (LongType, IntegerType)), StringType: (LoadStringFromBytes, StringType), BinaryType: (LoadBinaryFromBytes, BinaryType), DecimalType: (LoadDecimalFromBytes, DecimalType), FixedType: (LoadFixedFromBytes, FixedType), }
IcebergColumnStatisticsLoader
python
pymupdf__PyMuPDF
src/table.py
{ "start": 49789, "end": 64449 }
class ____: def __init__(self, page, cells): self.page = page self.cells = cells self.header = self._get_header() # PyMuPDF extension @property def bbox(self): c = self.cells return ( min(map(itemgetter(0), c)), min(map(itemgetter(1), c)), max(map(itemgetter(2), c)), max(map(itemgetter(3), c)), ) @property def rows(self) -> list: _sorted = sorted(self.cells, key=itemgetter(1, 0)) xs = list(sorted(set(map(itemgetter(0), self.cells)))) rows = [] for y, row_cells in itertools.groupby(_sorted, itemgetter(1)): xdict = {cell[0]: cell for cell in row_cells} row = TableRow([xdict.get(x) for x in xs]) rows.append(row) return rows @property def row_count(self) -> int: # PyMuPDF extension return len(self.rows) @property def col_count(self) -> int: # PyMuPDF extension return max([len(r.cells) for r in self.rows]) def extract(self, **kwargs) -> list: chars = CHARS table_arr = [] def char_in_bbox(char, bbox) -> bool: v_mid = (char["top"] + char["bottom"]) / 2 h_mid = (char["x0"] + char["x1"]) / 2 x0, top, x1, bottom = bbox return bool( (h_mid >= x0) and (h_mid < x1) and (v_mid >= top) and (v_mid < bottom) ) for row in self.rows: arr = [] row_chars = [char for char in chars if char_in_bbox(char, row.bbox)] for cell in row.cells: if cell is None: cell_text = None else: cell_chars = [ char for char in row_chars if char_in_bbox(char, cell) ] if len(cell_chars): kwargs["x_shift"] = cell[0] kwargs["y_shift"] = cell[1] if "layout" in kwargs: kwargs["layout_width"] = cell[2] - cell[0] kwargs["layout_height"] = cell[3] - cell[1] cell_text = extract_text(cell_chars, **kwargs) else: cell_text = "" arr.append(cell_text) table_arr.append(arr) return table_arr def to_markdown(self, clean=False, fill_empty=True): """Output table content as a string in Github-markdown format. If "clean" then markdown syntax is removed from cell content. If "fill_empty" then cell content None is replaced by the values above (columns) or left (rows) in an effort to approximate row and columns spans. """ output = "|" rows = self.row_count cols = self.col_count # cell coordinates cell_boxes = [[c for c in r.cells] for r in self.rows] # cell text strings cells = [[None for i in range(cols)] for j in range(rows)] for i, row in enumerate(cell_boxes): for j, cell in enumerate(row): if cell is not None: cells[i][j] = extract_cells( TEXTPAGE, cell_boxes[i][j], markdown=True ) if fill_empty: # fill "None" cells where possible # for rows, copy content from left to right for j in range(rows): for i in range(cols - 1): if cells[j][i + 1] is None: cells[j][i + 1] = cells[j][i] # for columns, copy top to bottom for i in range(cols): for j in range(rows - 1): if cells[j + 1][i] is None: cells[j + 1][i] = cells[j][i] # generate header string and MD separator for i, name in enumerate(self.header.names): if not name: # generate a name if empty name = f"Col{i+1}" name = name.replace("\n", "<br>") # use HTML line breaks if clean: # remove sensitive syntax name = html.escape(name.replace("-", "&#45;")) output += name + "|" output += "\n" # insert GitHub header line separator output += "|" + "|".join("---" for i in range(self.col_count)) + "|\n" # skip first row in details if header is part of the table j = 0 if self.header.external else 1 # iterate over detail rows for row in cells[j:]: line = "|" for i, cell in enumerate(row): # replace None cells with empty string # use HTML line break tag if cell is None: cell = "" if clean: # remove sensitive syntax cell = html.escape(cell.replace("-", "&#45;")) line += cell + "|" line += "\n" output += line return output + "\n" def to_pandas(self, **kwargs): """Return a pandas DataFrame version of the table.""" try: import pandas as pd except ModuleNotFoundError: pymupdf.message("Package 'pandas' is not installed") raise pd_dict = {} extract = self.extract() hdr = self.header names = self.header.names hdr_len = len(names) # ensure uniqueness of column names for i in range(hdr_len): name = names[i] if not name: names[i] = f"Col{i}" if hdr_len != len(set(names)): for i in range(hdr_len): name = names[i] if name != f"Col{i}": names[i] = f"{i}-{name}" if not hdr.external: # header is part of 'extract' extract = extract[1:] for i in range(hdr_len): key = names[i] value = [] for j in range(len(extract)): value.append(extract[j][i]) pd_dict[key] = value return pd.DataFrame(pd_dict) def _get_header(self, y_tolerance=3): """Identify the table header. *** PyMuPDF extension. *** Starting from the first line above the table upwards, check if it qualifies to be part of the table header. Criteria include: * A one-line table never has an extra header. * Column borders must not intersect any word. If this happens, all text of this line and above of it is ignored. * No excess inter-line distance: If a line further up has a distance of more than 1.5 times of its font size, it will be ignored and all lines above of it. * Must have same text properties. * Starting with the top table line, a bold text property cannot change back to non-bold. If not all criteria are met (or there is no text above the table), the first table row is assumed to be the header. """ page = self.page y_delta = y_tolerance def top_row_bg_color(self): """ Compare top row background color with color of same-sized bbox above. If different, return True indicating that the original table top row is already the header. """ bbox0 = pymupdf.Rect(self.rows[0].bbox) bboxt = bbox0 + (0, -bbox0.height, 0, -bbox0.height) # area above top_color0 = page.get_pixmap(clip=bbox0).color_topusage()[1] top_colort = page.get_pixmap(clip=bboxt).color_topusage()[1] if top_color0 != top_colort: return True # top row is header return False def row_has_bold(bbox): """Check if a row contains some bold text. If e.g. true for the top row, then it will be used as (internal) column header row if any of the following is true: * the previous (above) text line has no bold span * the second table row text has no bold span Returns True if any spans are bold else False. """ blocks = page.get_text("dict", flags=pymupdf.TEXTFLAGS_TEXT, clip=bbox)[ "blocks" ] spans = [s for b in blocks for l in b["lines"] for s in l["spans"]] return any(s["flags"] & pymupdf.TEXT_FONT_BOLD for s in spans) try: row = self.rows[0] cells = row.cells bbox = pymupdf.Rect(row.bbox) except IndexError: # this table has no rows return None # return this if we determine that the top row is the header header_top_row = TableHeader(bbox, cells, self.extract()[0], False) # 1-line tables have no extra header if len(self.rows) < 2: return header_top_row # 1-column tables have no extra header if len(cells) < 2: return header_top_row # assume top row is the header if second row is empty row2 = self.rows[1] # second row if all(c is None for c in row2.cells): # no valid cell bboxes in row2 return header_top_row # Special check: is top row bold? top_row_bold = row_has_bold(bbox) # assume top row is header if it is bold and any cell # of 2nd row is non-bold if top_row_bold and not row_has_bold(row2.bbox): return header_top_row if top_row_bg_color(self): # if area above top row has a different background color, # then top row is already the header return header_top_row # column coordinates (x1 values) in top row col_x = [c[2] if c is not None else None for c in cells[:-1]] # clip = page area above the table # We will inspect this area for text qualifying as column header. clip = +bbox # take row 0 bbox clip.y0 = 0 # start at top of page clip.y1 = bbox.y0 # end at top of table blocks = page.get_text("dict", clip=clip, flags=pymupdf.TEXTFLAGS_TEXT)[ "blocks" ] # non-empty, non-superscript spans above table, sorted descending by y1 spans = sorted( [ s for b in blocks for l in b["lines"] for s in l["spans"] if not ( white_spaces.issuperset(s["text"]) or s["flags"] & pymupdf.TEXT_FONT_SUPERSCRIPT ) ], key=lambda s: s["bbox"][3], reverse=True, ) select = [] # y1 coordinates above, sorted descending line_heights = [] # line heights above, sorted descending line_bolds = [] # bold indicator per line above, same sorting # walk through the spans and fill above 3 lists for i in range(len(spans)): s = spans[i] y1 = s["bbox"][3] # span bottom h = y1 - s["bbox"][1] # span bbox height bold = s["flags"] & pymupdf.TEXT_FONT_BOLD # use first item to start the lists if i == 0: select.append(y1) line_heights.append(h) line_bolds.append(bold) continue # get previous items from the 3 lists y0 = select[-1] h0 = line_heights[-1] bold0 = line_bolds[-1] if bold0 and not bold: break # stop if switching from bold to non-bold # if fitting in height of previous span, modify bbox if y0 - y1 <= y_delta or abs((y0 - h0) - s["bbox"][1]) <= y_delta: s["bbox"] = (s["bbox"][0], y0 - h0, s["bbox"][2], y0) spans[i] = s if bold: line_bolds[-1] = bold continue elif y0 - y1 > 1.5 * h0: break # stop if distance to previous line too large select.append(y1) line_heights.append(h) line_bolds.append(bold) if select == []: # nothing above the table? return header_top_row select = select[:5] # accept up to 5 lines for an external header # assume top row as header if text above is too far away if bbox.y0 - select[0] >= line_heights[0]: return header_top_row # accept top row as header if bold, but line above is not if top_row_bold and not line_bolds[0]: return header_top_row if spans == []: # nothing left above the table, return top row return header_top_row # re-compute clip above table nclip = pymupdf.EMPTY_RECT() for s in [s for s in spans if s["bbox"][3] >= select[-1]]: nclip |= s["bbox"] if not nclip.is_empty: clip = nclip clip.y1 = bbox.y0 # make sure we still include every word above # Confirm that no word in clip is intersecting a column separator word_rects = [pymupdf.Rect(w[:4]) for w in page.get_text("words", clip=clip)] word_tops = sorted(list(set([r[1] for r in word_rects])), reverse=True) select = [] # exclude lines with words that intersect a column border for top in word_tops: intersecting = [ (x, r) for x in col_x if x is not None for r in word_rects if r[1] == top and r[0] < x and r[2] > x ] if intersecting == []: select.append(top) else: # detected a word crossing a column border break if select == []: # nothing left over: return first row return header_top_row hdr_bbox = +clip # compute the header cells hdr_bbox.y0 = select[-1] # hdr_bbox top is smallest top coord of words hdr_cells = [ (c[0], hdr_bbox.y0, c[2], hdr_bbox.y1) if c is not None else None for c in cells ] # adjust left/right of header bbox hdr_bbox.x0 = self.bbox[0] hdr_bbox.x1 = self.bbox[2] # column names: no line breaks, no excess spaces hdr_names = [ ( page.get_textbox(c).replace("\n", " ").replace(" ", " ").strip() if c is not None else "" ) for c in hdr_cells ] return TableHeader(tuple(hdr_bbox), hdr_cells, hdr_names, True) @dataclass
Table
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py
{ "start": 199, "end": 238 }
class ____( object # ): ...
A
python
huggingface__transformers
src/transformers/pipelines/image_text_to_text.py
{ "start": 1337, "end": 1485 }
class ____(enum.Enum): TENSORS = 0 NEW_TEXT = 1 FULL_TEXT = 2 @add_end_docstrings(build_pipeline_init_args(has_processor=True))
ReturnType
python
jazzband__django-waffle
waffle/tests/test_mixin.py
{ "start": 1722, "end": 2726 }
class ____(TestCase): def setUp(self): super().setUp() self.request = get() def test_sample_must_be_active(self): view = views.SampleView self.assertRaises(Http404, process_request, self.request, view) Sample.objects.create(name='foo', percent='100.0') response = process_request(self.request, view) self.assertEqual(b'foo', response.content) def test_sample_must_be_inactive(self): view = views.SampleOffView response = process_request(self.request, view) self.assertEqual(b'foo', response.content) Sample.objects.create(name='foo', percent='100.0') self.assertRaises(Http404, process_request, self.request, view) def test_override_with_cookie(self): Sample.objects.create(name='foo', percent='0.0') self.request.COOKIES['dwf_foo'] = 'True' self.assertRaises(Http404, process_request, self.request, views.SwitchView)
WaffleSampleMixinTest
python
dask__distributed
distributed/semaphore.py
{ "start": 538, "end": 9102 }
class ____: """An extension for the scheduler to manage Semaphores This adds the following routes to the scheduler * semaphore_acquire * semaphore_release * semaphore_close * semaphore_refresh_leases * semaphore_register """ def __init__(self, scheduler): self.scheduler = scheduler # {semaphore_name: asyncio.Event} self.events = defaultdict(asyncio.Event) # {semaphore_name: max_leases} self.max_leases = dict() # {semaphore_name: {lease_id: lease_last_seen_timestamp}} self.leases = defaultdict(dict) self.lease_timeouts = dict() self.scheduler.handlers.update( { "semaphore_register": self.create, "semaphore_acquire": self.acquire, "semaphore_release": self.release, "semaphore_close": self.close, "semaphore_refresh_leases": self.refresh_leases, "semaphore_value": self.get_value, } ) # {metric_name: {semaphore_name: metric}} self.metrics = { "acquire_total": defaultdict(int), # counter "release_total": defaultdict(int), # counter "average_pending_lease_time": defaultdict(float), # gauge "pending": defaultdict(int), # gauge } validation_callback_time = parse_timedelta( dask.config.get("distributed.scheduler.locks.lease-validation-interval"), default="s", ) self.scheduler.periodic_callbacks["semaphore-lease-timeout"] = pc = ( PeriodicCallback(self._check_lease_timeout, validation_callback_time * 1000) ) pc.start() def get_value(self, name=None): return len(self.leases[name]) # `comm` here is required by the handler interface def create(self, name, max_leases, lease_timeout): # We use `self.max_leases` as the point of truth to find out if a semaphore with a specific # `name` has been created. if name not in self.max_leases: assert isinstance(max_leases, int), max_leases self.max_leases[name] = max_leases self.lease_timeouts[name] = lease_timeout else: if max_leases != self.max_leases[name]: raise ValueError( "Inconsistent max leases: %s, expected: %s" % (max_leases, self.max_leases[name]) ) @log_errors def refresh_leases(self, name=None, lease_ids=None): now = time() logger.debug("Refresh leases for %s with ids %s at %s", name, lease_ids, now) for id_ in lease_ids: if id_ not in self.leases[name]: logger.critical( f"Refreshing an unknown lease ID {id_} for {name}. This might be due to leases " f"timing out and may cause overbooking of the semaphore!" f"This is often caused by long-running GIL-holding in the task which acquired the lease." ) self.leases[name][id_] = now def _get_lease(self, name, lease_id): result = True if ( # This allows request idempotency lease_id in self.leases[name] or len(self.leases[name]) < self.max_leases[name] ): now = time() logger.debug("Acquire lease %s for %s at %s", lease_id, name, now) self.leases[name][lease_id] = now self.metrics["acquire_total"][name] += 1 else: result = False return result def _semaphore_exists(self, name): if name not in self.max_leases: return False return True @log_errors async def acquire(self, name=None, timeout=None, lease_id=None): if not self._semaphore_exists(name): raise RuntimeError(f"Semaphore or Lock `{name}` not known.") if isinstance(name, list): name = tuple(name) deadline = Deadline.after(timeout) self.metrics["pending"][name] += 1 while True: logger.debug( "Trying to acquire %s for %s with %s seconds left.", lease_id, name, deadline.remaining, ) # Reset the event and try to get a release. The event will be set if the state # is changed and helps to identify when it is worth to retry an acquire self.events[name].clear() result = self._get_lease(name, lease_id) # If acquiring fails, we wait for the event to be set, i.e. something has # been released and we can try to acquire again (continue loop) if not result: future = wait_for(self.events[name].wait(), timeout=deadline.remaining) try: await future continue except TimeoutError: result = False logger.debug( "Acquisition of lease %s for %s is %s after waiting for %ss.", lease_id, name, result, deadline.elapsed, ) # We're about to return, so the lease is no longer "pending" self.metrics["average_pending_lease_time"][name] = ( self.metrics["average_pending_lease_time"][name] + deadline.elapsed ) / 2 self.metrics["pending"][name] -= 1 return result @log_errors def release(self, name=None, lease_id=None): if not self._semaphore_exists(name): logger.warning( f"Tried to release Lock or Semaphore `{name}` but it is not known." ) return if isinstance(name, list): name = tuple(name) if name in self.leases and lease_id in self.leases[name]: self._release_value(name, lease_id) else: logger.warning( f"Tried to release Lock or Semaphore but it was already released: " f"{name=}, {lease_id=}. " f"This can happen if the Lock or Semaphore timed out before." ) def _release_value(self, name, lease_id): logger.debug("Releasing %s for %s", lease_id, name) # Everything needs to be atomic here. del self.leases[name][lease_id] self.events[name].set() self.metrics["release_total"][name] += 1 def _check_lease_timeout(self): now = time() semaphore_names = list(self.leases.keys()) for name in semaphore_names: if lease_timeout := self.lease_timeouts.get(name): ids = list(self.leases[name]) logger.debug( "Validating leases for %s at time %s. Currently known %s", name, now, self.leases[name], ) for _id in ids: time_since_refresh = now - self.leases[name][_id] if time_since_refresh > lease_timeout: logger.debug( "Lease %s for %s timed out after %ss.", _id, name, time_since_refresh, ) self._release_value(name=name, lease_id=_id) @log_errors def close(self, name=None): """Hard close the semaphore without warning clients which still hold a lease.""" if not self._semaphore_exists(name): return del self.max_leases[name] del self.lease_timeouts[name] if name in self.events: del self.events[name] if name in self.leases: if self.leases[name]: warnings.warn( f"Closing semaphore {name} but there remain unreleased leases {sorted(self.leases[name])}", RuntimeWarning, ) del self.leases[name] if name in self.metrics["pending"]: if self.metrics["pending"][name]: warnings.warn( f"Closing semaphore {name} but there remain pending leases", RuntimeWarning, ) # Clean-up state of semaphore metrics for _, metric_dict in self.metrics.items(): if name in metric_dict: del metric_dict[name]
SemaphoreExtension
python
huggingface__transformers
src/transformers/models/florence2/configuration_florence2.py
{ "start": 1342, "end": 6262 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Florence2VisionModel`]. It is used to instantiate a Florence2VisionModel according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Florence2VisionModel architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: in_channels (`int`, *optional*, defaults to 3): Number of input image channels. depths (`Tuple[int]`, *optional*, defaults to `(1, 1, 9, 1)`): The depth of the model. patch_size (`Tuple[int]`, *optional*, defaults to `(7, 3, 3, 3)`): The patch size of the image. patch_stride (`Tuple[int]`, *optional*, defaults to `(4, 2, 2, 2)`): The patch stride of the image. patch_padding (`Tuple[int]`, *optional*, defaults to `(3, 1, 1, 1)`): The patch padding of the image. patch_prenorm (`Tuple[bool]`, *optional*, defaults to `(False, True, True, True)`): Whether to apply layer normalization before the patch embedding layer. embed_dim (`Tuple[int]`, *optional*, defaults to `(128, 256, 512, 1024)`): The dimension of the embedding layer. num_heads (`Tuple[int]`, *optional*, defaults to `(4, 8, 16, 32)`): The number of attention heads. num_groups (`Tuple[int]`, *optional*, defaults to `(4, 8, 16, 32)`): The number of groups. window_size (`int`, *optional*, defaults to 12): The window size of the model. drop_path_rate (`float`, *optional*, defaults to 0.1): The dropout rate of the drop path layer. mlp_ratio (`int`, *optional*, defaults to 4.0): Ratio of mlp hidden dim to embedding dim. qkv_bias (`bool`, *optional*, defaults to `True`): If True, add a learnable bias to query, key, value. activation_function (`str` or `function`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. projection_dim (`int`, *optional*, defaults to 1024): The dimension of the projection layer. max_temporal_embeddings (`int`, *optional*, defaults to 100): The configuration of the visual temporal embedding. max_position_embeddings (`int`, *optional*, defaults to 50): The configuration of the image position embedding. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. Example: ```python >>> from transformers import Florence2VisionConfig, Florence2VisionModel >>> # Initializing a Florence2 Vision style configuration >>> configuration = Florence2VisionConfig() >>> # Initializing a model (with random weights) >>> model = Florence2VisionModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "florence_vision" def __init__( self, in_channels=3, depths=(1, 1, 9, 1), patch_size=(7, 3, 3, 3), patch_stride=(4, 2, 2, 2), patch_padding=(3, 1, 1, 1), patch_prenorm=(False, True, True, True), embed_dim=(128, 256, 512, 1024), num_heads=(4, 8, 16, 32), num_groups=(4, 8, 16, 32), window_size=12, drop_path_rate=0.1, mlp_ratio=4.0, qkv_bias=True, activation_function="gelu", projection_dim=1024, max_temporal_embeddings=100, max_position_embeddings=50, initializer_range=0.02, **kwargs, ): self.in_channels = in_channels self.depths = list(depths) self.patch_size = list(patch_size) self.patch_stride = list(patch_stride) self.patch_padding = list(patch_padding) self.patch_prenorm = list(patch_prenorm) self.embed_dim = list(embed_dim) self.num_heads = list(num_heads) self.num_groups = list(num_groups) self.window_size = window_size self.drop_path_rate = drop_path_rate self.mlp_ratio = mlp_ratio self.qkv_bias = qkv_bias self.projection_dim = projection_dim self.max_temporal_embeddings = max_temporal_embeddings self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.activation_function = activation_function super().__init__(**kwargs)
Florence2VisionConfig
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/attributes.py
{ "start": 44117, "end": 50656 }
class ____(_ScalarAttributeImpl): """represents a scalar-holding InstrumentedAttribute, where the target object is also instrumented. Adds events to delete/set operations. """ default_accepts_scalar_loader = False uses_objects = True supports_population = True collection = False __slots__ = () def delete(self, state: InstanceState[Any], dict_: _InstanceDict) -> None: if self.dispatch._active_history: old = self.get( state, dict_, passive=PASSIVE_ONLY_PERSISTENT | NO_AUTOFLUSH | LOAD_AGAINST_COMMITTED, ) else: old = self.get( state, dict_, passive=PASSIVE_NO_FETCH ^ INIT_OK | LOAD_AGAINST_COMMITTED | NO_RAISE, ) self.fire_remove_event(state, dict_, old, self._remove_token) existing = dict_.pop(self.key, NO_VALUE) # if the attribute is expired, we currently have no way to tell # that an object-attribute was expired vs. not loaded. So # for this test, we look to see if the object has a DB identity. if ( existing is NO_VALUE and old is not PASSIVE_NO_RESULT and state.key is None ): raise AttributeError("%s object does not have a value" % self) def get_history( self, state: InstanceState[Any], dict_: _InstanceDict, passive: PassiveFlag = PASSIVE_OFF, ) -> History: if self.key in dict_: current = dict_[self.key] else: if passive & INIT_OK: passive ^= INIT_OK current = self.get(state, dict_, passive=passive) if current is PASSIVE_NO_RESULT: return HISTORY_BLANK if not self._deferred_history: return History.from_object_attribute(self, state, current) else: original = state.committed_state.get(self.key, _NO_HISTORY) if original is PASSIVE_NO_RESULT: loader_passive = passive | ( PASSIVE_ONLY_PERSISTENT | NO_AUTOFLUSH | LOAD_AGAINST_COMMITTED | NO_RAISE | DEFERRED_HISTORY_LOAD ) original = self._fire_loader_callables( state, self.key, loader_passive ) return History.from_object_attribute( self, state, current, original=original ) def get_all_pending( self, state: InstanceState[Any], dict_: _InstanceDict, passive: PassiveFlag = PASSIVE_NO_INITIALIZE, ) -> _AllPendingType: if self.key in dict_: current = dict_[self.key] elif passive & CALLABLES_OK: current = self.get(state, dict_, passive=passive) else: return [] ret: _AllPendingType # can't use __hash__(), can't use __eq__() here if ( current is not None and current is not PASSIVE_NO_RESULT and current is not NO_VALUE ): ret = [(instance_state(current), current)] else: ret = [(None, None)] if self.key in state.committed_state: original = state.committed_state[self.key] if ( original is not None and original is not PASSIVE_NO_RESULT and original is not NO_VALUE and original is not current ): ret.append((instance_state(original), original)) return ret def set( self, state: InstanceState[Any], dict_: _InstanceDict, value: Any, initiator: Optional[AttributeEventToken] = None, passive: PassiveFlag = PASSIVE_OFF, check_old: Any = None, pop: bool = False, ) -> None: """Set a value on the given InstanceState.""" if value is DONT_SET: return if self.dispatch._active_history: old = self.get( state, dict_, passive=PASSIVE_ONLY_PERSISTENT | NO_AUTOFLUSH | LOAD_AGAINST_COMMITTED, ) else: old = self.get( state, dict_, passive=PASSIVE_NO_FETCH ^ INIT_OK | LOAD_AGAINST_COMMITTED | NO_RAISE, ) if ( check_old is not None and old is not PASSIVE_NO_RESULT and check_old is not old ): if pop: return else: raise ValueError( "Object %s not associated with %s on attribute '%s'" % (instance_str(check_old), state_str(state), self.key) ) value = self.fire_replace_event(state, dict_, value, old, initiator) dict_[self.key] = value def fire_remove_event( self, state: InstanceState[Any], dict_: _InstanceDict, value: Any, initiator: Optional[AttributeEventToken], ) -> None: if self.trackparent and value not in ( None, PASSIVE_NO_RESULT, NO_VALUE, ): self.sethasparent(instance_state(value), state, False) for fn in self.dispatch.remove: fn(state, value, initiator or self._remove_token) state._modified_event(dict_, self, value) def fire_replace_event( self, state: InstanceState[Any], dict_: _InstanceDict, value: _T, previous: Any, initiator: Optional[AttributeEventToken], ) -> _T: if self.trackparent: if previous is not value and previous not in ( None, PASSIVE_NO_RESULT, NO_VALUE, ): self.sethasparent(instance_state(previous), state, False) for fn in self.dispatch.set: value = fn( state, value, previous, initiator or self._replace_token ) state._modified_event(dict_, self, previous) if self.trackparent: if value is not None: self.sethasparent(instance_state(value), state, True) return value
_ScalarObjectAttributeImpl
python
django__django
tests/auth_tests/test_mixins.py
{ "start": 1292, "end": 4372 }
class ____(TestCase): factory = RequestFactory() def test_stacked_mixins_success(self): user = models.User.objects.create(username="joe", password="qwerty") perms = models.Permission.objects.filter( codename__in=("add_customuser", "change_customuser") ) user.user_permissions.add(*perms) request = self.factory.get("/rand") request.user = user view = StackedMixinsView1.as_view() response = view(request) self.assertEqual(response.status_code, 200) view = StackedMixinsView2.as_view() response = view(request) self.assertEqual(response.status_code, 200) def test_stacked_mixins_missing_permission(self): user = models.User.objects.create(username="joe", password="qwerty") perms = models.Permission.objects.filter(codename__in=("add_customuser",)) user.user_permissions.add(*perms) request = self.factory.get("/rand") request.user = user view = StackedMixinsView1.as_view() with self.assertRaises(PermissionDenied): view(request) view = StackedMixinsView2.as_view() with self.assertRaises(PermissionDenied): view(request) def test_access_mixin_permission_denied_response(self): user = models.User.objects.create(username="joe", password="qwerty") # Authenticated users receive PermissionDenied. request = self.factory.get("/rand") request.user = user view = AlwaysFalseView.as_view() with self.assertRaises(PermissionDenied): view(request) # Anonymous users are redirected to the login page. request.user = AnonymousUser() response = view(request) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, "/accounts/login/?next=/rand") def test_access_mixin_permission_denied_remote_login_url(self): class AView(AlwaysFalseView): login_url = "https://www.remote.example.com/login" view = AView.as_view() request = self.factory.get("/rand") request.user = AnonymousUser() response = view(request) self.assertEqual(response.status_code, 302) self.assertEqual( response.url, "https://www.remote.example.com/login?next=http%3A//testserver/rand", ) @mock.patch.object(models.User, "is_authenticated", False) def test_stacked_mixins_not_logged_in(self): user = models.User.objects.create(username="joe", password="qwerty") perms = models.Permission.objects.filter( codename__in=("add_customuser", "change_customuser") ) user.user_permissions.add(*perms) request = self.factory.get("/rand") request.user = user view = StackedMixinsView1.as_view() with self.assertRaises(PermissionDenied): view(request) view = StackedMixinsView2.as_view() with self.assertRaises(PermissionDenied): view(request)
AccessMixinTests
python
huggingface__transformers
examples/modular-transformers/modeling_switch_function.py
{ "start": 4283, "end": 7377 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: SwitchFunctionConfig, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.is_causal = True self.q_proj = nn.Linear( config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias ) self.k_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.v_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.o_proj = nn.Linear( config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias ) def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_values: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor, torch.Tensor]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: # sin and cos are specific to RoPE models; cache_position needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights
SwitchFunctionAttention
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 40995, "end": 42653 }
class ____(ASTExpression): def __init__(self, rooted: bool, array: bool, expr: ASTExpression) -> None: self.rooted = rooted self.array = array self.expr = expr def __eq__(self, other: object) -> bool: if not isinstance(other, ASTDeleteExpr): return NotImplemented return ( self.rooted == other.rooted and self.array == other.array and self.expr == other.expr ) def __hash__(self) -> int: return hash((self.rooted, self.array, self.expr)) def _stringify(self, transform: StringifyTransform) -> str: res = [] if self.rooted: res.append('::') res.append('delete ') if self.array: res.append('[] ') res.append(transform(self.expr)) return ''.join(res) def get_id(self, version: int) -> str: if self.array: id = 'da' else: id = 'dl' return id + self.expr.get_id(version) def describe_signature( self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol ) -> None: if self.rooted: signode += addnodes.desc_sig_punctuation('::', '::') signode += addnodes.desc_sig_keyword('delete', 'delete') signode += addnodes.desc_sig_space() if self.array: signode += addnodes.desc_sig_punctuation('[]', '[]') signode += addnodes.desc_sig_space() self.expr.describe_signature(signode, mode, env, symbol) # Other expressions ################################################################################
ASTDeleteExpr