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
dagster-io__dagster
python_modules/dagster/dagster/_module_alias_map.py
{ "start": 2821, "end": 3349 }
class ____(Loader): def __init__(self, alias: str, base_spec: ModuleSpec): self.alias = alias self.base_spec = base_spec def exec_module(self, _module: ModuleType) -> None: # pyright: ignore[reportIncompatibleMethodOverride] base_module = importlib.import_module(self.base_spec.name) sys.modules[self.alias] = base_module def module_repr(self, module: ModuleType) -> str: assert self.base_spec.loader return self.base_spec.loader.module_repr(module)
AliasedModuleLoader
python
PrefectHQ__prefect
tests/client/test_prefect_client.py
{ "start": 72543, "end": 78763 }
class ____: async def test_read_work_pools(self, prefect_client): # default pool shows up when running the test class or individuals, but not when running # test as a module pools = await prefect_client.read_work_pools() existing_name = set([p.name for p in pools]) existing_ids = set([p.id for p in pools]) work_pool_1 = await prefect_client.create_work_pool( work_pool=WorkPoolCreate(name="test-pool-1") ) work_pool_2 = await prefect_client.create_work_pool( work_pool=WorkPoolCreate(name="test-pool-2") ) pools = await prefect_client.read_work_pools() names_after_adding = set([p.name for p in pools]) ids_after_adding = set([p.id for p in pools]) assert names_after_adding.symmetric_difference(existing_name) == { work_pool_1.name, work_pool_2.name, } assert ids_after_adding.symmetric_difference(existing_ids) == { work_pool_1.id, work_pool_2.id, } async def test_create_work_pool_overwriting_existing_work_pool( self, prefect_client: PrefectClient, work_pool: WorkPool ): await prefect_client.create_work_pool( work_pool=WorkPoolCreate( name=work_pool.name, type=work_pool.type, description="new description", ), overwrite=True, ) updated_work_pool = await prefect_client.read_work_pool(work_pool.name) assert updated_work_pool.description == "new description" async def test_create_work_pool_with_attempt_to_overwrite_type( self, prefect_client, work_pool ): with pytest.warns( UserWarning, match="Overwriting work pool type is not supported" ): await prefect_client.create_work_pool( work_pool=WorkPoolCreate( name=work_pool.name, type="kubernetes", description=work_pool.description, ), overwrite=True, ) updated_work_pool = await prefect_client.read_work_pool(work_pool.name) assert updated_work_pool.type == work_pool.type async def test_update_work_pool(self, prefect_client): work_pool = await prefect_client.create_work_pool( work_pool=WorkPoolCreate(name="test-pool-1") ) assert work_pool.description is None await prefect_client.update_work_pool( work_pool_name=work_pool.name, work_pool=WorkPoolUpdate( description="Foo description", ), ) result = await prefect_client.read_work_pool(work_pool_name=work_pool.name) assert result.description == "Foo description" async def test_update_missing_work_pool(self, prefect_client): with pytest.raises(prefect.exceptions.ObjectNotFound): await prefect_client.update_work_pool( work_pool_name="abcdefg", work_pool=WorkPoolUpdate(), ) async def test_delete_work_pool(self, prefect_client, work_pool): await prefect_client.delete_work_pool(work_pool.name) with pytest.raises(prefect.exceptions.ObjectNotFound): await prefect_client.read_work_pool(work_pool.id) @pytest.fixture def sample_bundle_upload_step(self) -> dict[str, Any]: return { "prefect_aws.experimental.bundles.upload": { "requires": "prefect-aws", "bucket": "MY_BUCKET_NAME", "aws_credentials_block_name": "MY_CREDS_BLOCK_NAME", }, } @pytest.fixture def sample_bundle_execution_step(self) -> dict[str, Any]: return { "prefect_aws.experimental.bundles.execute": { "requires": "prefect-aws", "bucket": "MY_BUCKET_NAME", "aws_credentials_block_name": "MY_CREDS_BLOCK_NAME", }, } async def test_create_work_pool_with_storage_configuration( self, prefect_client: PrefectClient, sample_bundle_upload_step: dict[str, Any], sample_bundle_execution_step: dict[str, Any], ): default_result_storage_block_id = uuid4() work_pool = await prefect_client.create_work_pool( work_pool=WorkPoolCreate.model_validate( { "name": "test-pool-1", "storage_configuration": { "bundle_upload_step": sample_bundle_upload_step, "bundle_execution_step": sample_bundle_execution_step, "default_result_storage_block_id": default_result_storage_block_id, }, } ), ) assert work_pool.storage_configuration == WorkPoolStorageConfiguration( bundle_upload_step=sample_bundle_upload_step, bundle_execution_step=sample_bundle_execution_step, default_result_storage_block_id=default_result_storage_block_id, ) async def test_update_work_pool_with_storage_configuration( self, prefect_client: PrefectClient, sample_bundle_upload_step: dict[str, Any], sample_bundle_execution_step: dict[str, Any], ): work_pool = await prefect_client.create_work_pool( work_pool=WorkPoolCreate(name="test-pool-1") ) await prefect_client.update_work_pool( work_pool_name=work_pool.name, work_pool=WorkPoolUpdate.model_validate( { "storage_configuration": { "bundle_upload_step": sample_bundle_upload_step, "bundle_execution_step": {"step": "not a real step"}, }, } ), ) result = await prefect_client.read_work_pool(work_pool.name) assert result.storage_configuration == WorkPoolStorageConfiguration( bundle_upload_step=sample_bundle_upload_step, bundle_execution_step={"step": "not a real step"}, )
TestWorkPools
python
huggingface__transformers
src/transformers/models/cwm/modeling_cwm.py
{ "start": 19056, "end": 22130 }
class ____(CwmPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config): super().__init__(config) self.model = CwmModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: r""" Example: ```python >>> from transformers import AutoTokenizer, CwmForCausalLM >>> model = CwmForCausalLM.from_pretrained("meta-cwm/Cwm-2-7b-hf") >>> tokenizer = AutoTokenizer.from_pretrained("meta-cwm/Cwm-2-7b-hf") >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, cache_position=cache_position, **kwargs, ) hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = ["CwmPreTrainedModel", "CwmModel", "CwmForCausalLM"]
CwmForCausalLM
python
PrefectHQ__prefect
src/integrations/prefect-databricks/tests/test_rest.py
{ "start": 1464, "end": 2688 }
class ____(BaseModel): model_config = ConfigDict(extra="allow", frozen=True) some_string: str some_int: int another_base_model: TestAnotherBaseModel other_base_models: List[TestAnotherBaseModel] def test_serialize_model(): expected = { "base_model": { "some_string": "abc", "some_int": 1, "another_base_model": {"some_float": 2.8, "some_bool": True}, "other_base_models": [ {"some_float": 8.8, "some_bool": False}, {"some_float": 1.8, "some_bool": True}, ], "unexpected_value": ["super", "unexpected"], } } actual = serialize_model( { "base_model": TestBaseModel( some_string="abc", some_int=1, unexpected_value=["super", "unexpected"], another_base_model=TestAnotherBaseModel(some_float=2.8, some_bool=True), other_base_models=[ TestAnotherBaseModel(some_float=8.8, some_bool=False), TestAnotherBaseModel(some_float=1.8, some_bool=True), ], ) } ) assert expected == actual
TestBaseModel
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/instance.py
{ "start": 2362, "end": 3428 }
class ____(graphene.ObjectType): id = graphene.NonNull(graphene.String) daemonStatus = graphene.Field( graphene.NonNull(GrapheneDaemonStatus), daemon_type=graphene.Argument(graphene.String), ) allDaemonStatuses = non_null_list(GrapheneDaemonStatus) class Meta: name = "DaemonHealth" def __init__(self, instance): super().__init__() self._instance = check.inst_param(instance, "instance", DagsterInstance) def resolve_id(self, _graphene_info: ResolveInfo): return "daemonHealth" def resolve_daemonStatus(self, _graphene_info: ResolveInfo, daemon_type): check.str_param(daemon_type, "daemon_type") return GrapheneDaemonStatus( self._instance.get_daemon_statuses(daemon_types=[daemon_type])[daemon_type] ) def resolve_allDaemonStatuses(self, _graphene_info: ResolveInfo): return [ GrapheneDaemonStatus(daemon_status) for daemon_status in self._instance.get_daemon_statuses().values() ]
GrapheneDaemonHealth
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/named_tuples.py
{ "start": 1776, "end": 1975 }
class ____(NamedTuple): benign: int bad: str def issue_with_named_tuple_with_tainted_attribute(): NamedTupleWithTaintedAttribute(bad=_test_source(), benign=1)
NamedTupleWithTaintedAttribute
python
hyperopt__hyperopt
hyperopt/rdists.py
{ "start": 3781, "end": 5538 }
class ____(quniform_gen): """Stats for Y = q * round(e^X / q) where X ~ U(low, high).""" # -- not inheriting from scipy.stats.rv_discrete # because I don't understand the design of those rv classes def __init__(self, low, high, q): low, high = list(map(float, (low, high))) elow = np.exp(low) ehigh = np.exp(high) qlow = safe_int_cast(np.round(elow / q)) * q qhigh = safe_int_cast(np.round(ehigh / q)) * q # -- loguniform for using the CDF lu = loguniform_gen(low=low, high=high) cut_low = np.exp(low) # -- lowest possible pre-round value cut_high = min( qlow + 0.5 * q, ehigh # -- highest value that would ... ) # -- round to qlow xs = [qlow] ps = [lu.cdf(cut_high)] ii = 0 cdf_high = ps[0] while cut_high < (ehigh - 1e-10): # TODO: cut_low never used cut_high, cut_low = min(cut_high + q, ehigh), cut_high cdf_high, cdf_low = lu.cdf(cut_high), cdf_high ii += 1 xs.append(qlow + ii * q) ps.append(cdf_high - cdf_low) ps = np.asarray(ps) ps /= ps.sum() self.low = low self.high = high self.q = q self.qlow = qlow self.qhigh = qhigh self.xs = np.asarray(xs) self.ps = ps def pmf(self, x): return qtable_pmf(x, self.q, self.qlow, self.xs, self.ps) def logpmf(self, x): return qtable_logpmf(x, self.q, self.qlow, self.xs, self.ps) def rvs(self, size=()): x = mtrand.uniform(low=self.low, high=self.high, size=size) rval = safe_int_cast(np.round(np.exp(x) / self.q)) * self.q return rval
qloguniform_gen
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_numeric.py
{ "start": 1551, "end": 3183 }
class ____(TestCase): def test_copies(self): A = np.array([[1, 2], [3, 4]]) Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]]) assert_equal(np.resize(A, (2, 4)), Ar1) Ar2 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) assert_equal(np.resize(A, (4, 2)), Ar2) Ar3 = np.array([[1, 2, 3], [4, 1, 2], [3, 4, 1], [2, 3, 4]]) assert_equal(np.resize(A, (4, 3)), Ar3) def test_repeats(self): A = np.array([1, 2, 3]) Ar1 = np.array([[1, 2, 3, 1], [2, 3, 1, 2]]) assert_equal(np.resize(A, (2, 4)), Ar1) Ar2 = np.array([[1, 2], [3, 1], [2, 3], [1, 2]]) assert_equal(np.resize(A, (4, 2)), Ar2) Ar3 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]) assert_equal(np.resize(A, (4, 3)), Ar3) def test_zeroresize(self): A = np.array([[1, 2], [3, 4]]) Ar = np.resize(A, (0,)) assert_array_equal(Ar, np.array([])) assert_equal(A.dtype, Ar.dtype) Ar = np.resize(A, (0, 2)) assert_equal(Ar.shape, (0, 2)) Ar = np.resize(A, (2, 0)) assert_equal(Ar.shape, (2, 0)) def test_reshape_from_zero(self): # See also gh-6740 A = np.zeros(0, dtype=np.float32) Ar = np.resize(A, (2, 1)) assert_array_equal(Ar, np.zeros((2, 1), Ar.dtype)) assert_equal(A.dtype, Ar.dtype) def test_negative_resize(self): A = np.arange(0, 10, dtype=np.float32) new_shape = (-10, -1) with pytest.raises((RuntimeError, ValueError)): np.resize(A, new_shape=new_shape) @instantiate_parametrized_tests
TestResize
python
kamyu104__LeetCode-Solutions
Python/root-equals-sum-of-children.py
{ "start": 166, "end": 361 }
class ____(object): def checkTree(self, root): """ :type root: Optional[TreeNode] :rtype: bool """ return root.val == root.left.val+root.right.val
Solution
python
pypa__pip
src/pip/_vendor/rich/progress.py
{ "start": 5904, "end": 8721 }
class ____(RawIOBase, BinaryIO): """A reader that tracks progress while it's being read from.""" def __init__( self, handle: BinaryIO, progress: "Progress", task: TaskID, close_handle: bool = True, ) -> None: self.handle = handle self.progress = progress self.task = task self.close_handle = close_handle self._closed = False def __enter__(self) -> "_Reader": self.handle.__enter__() return self def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: self.close() def __iter__(self) -> BinaryIO: return self def __next__(self) -> bytes: line = next(self.handle) self.progress.advance(self.task, advance=len(line)) return line @property def closed(self) -> bool: return self._closed def fileno(self) -> int: return self.handle.fileno() def isatty(self) -> bool: return self.handle.isatty() @property def mode(self) -> str: return self.handle.mode @property def name(self) -> str: return self.handle.name def readable(self) -> bool: return self.handle.readable() def seekable(self) -> bool: return self.handle.seekable() def writable(self) -> bool: return False def read(self, size: int = -1) -> bytes: block = self.handle.read(size) self.progress.advance(self.task, advance=len(block)) return block def readinto(self, b: Union[bytearray, memoryview, mmap]): # type: ignore[no-untyped-def, override] n = self.handle.readinto(b) # type: ignore[attr-defined] self.progress.advance(self.task, advance=n) return n def readline(self, size: int = -1) -> bytes: # type: ignore[override] line = self.handle.readline(size) self.progress.advance(self.task, advance=len(line)) return line def readlines(self, hint: int = -1) -> List[bytes]: lines = self.handle.readlines(hint) self.progress.advance(self.task, advance=sum(map(len, lines))) return lines def close(self) -> None: if self.close_handle: self.handle.close() self._closed = True def seek(self, offset: int, whence: int = 0) -> int: pos = self.handle.seek(offset, whence) self.progress.update(self.task, completed=pos) return pos def tell(self) -> int: return self.handle.tell() def write(self, s: Any) -> int: raise UnsupportedOperation("write") def writelines(self, lines: Iterable[Any]) -> None: raise UnsupportedOperation("writelines")
_Reader
python
mlflow__mlflow
mlflow/store/artifact/hdfs_artifact_repo.py
{ "start": 498, "end": 7986 }
class ____(ArtifactRepository): """ Stores artifacts on HDFS. This repository is used with URIs of the form ``hdfs:/<path>``. The repository can only be used together with the RestStore. """ def __init__( self, artifact_uri: str, tracking_uri: str | None = None, registry_uri: str | None = None ) -> None: super().__init__(artifact_uri, tracking_uri, registry_uri) self.scheme, self.host, self.port, self.path = _resolve_connection_params(artifact_uri) def log_artifact(self, local_file, artifact_path=None): """ Log artifact in hdfs. Args: local_file: Source file path. artifact_path: When specified will attempt to write under artifact_uri/artifact_path. """ hdfs_base_path = _resolve_base_path(self.path, artifact_path) with hdfs_system(scheme=self.scheme, host=self.host, port=self.port) as hdfs: _, file_name = os.path.split(local_file) destination_path = posixpath.join(hdfs_base_path, file_name) with open(local_file, "rb") as source: with hdfs.open_output_stream(destination_path) as destination: destination.write(source.read()) def log_artifacts(self, local_dir, artifact_path=None): """ Log artifacts in hdfs. Missing remote sub-directories will be created if needed. Args: local_dir: Source dir path. artifact_path: When specified will attempt to write under artifact_uri/artifact_path. """ hdfs_base_path = _resolve_base_path(self.path, artifact_path) with hdfs_system(scheme=self.scheme, host=self.host, port=self.port) as hdfs: if not hdfs.get_file_info(hdfs_base_path).type == FileType.Directory: hdfs.create_dir(hdfs_base_path, recursive=True) for subdir_path, _, files in os.walk(local_dir): relative_path = _relative_path_local(local_dir, subdir_path) hdfs_subdir_path = ( posixpath.join(hdfs_base_path, relative_path) if relative_path else hdfs_base_path ) if not hdfs.get_file_info(hdfs_subdir_path).type == FileType.Directory: hdfs.create_dir(hdfs_subdir_path, recursive=True) for each_file in files: source_path = os.path.join(subdir_path, each_file) destination_path = posixpath.join(hdfs_subdir_path, each_file) with open(source_path, "rb") as source: with hdfs.open_output_stream(destination_path) as destination: destination.write(source.read()) def list_artifacts(self, path=None): """ Lists files and directories under artifacts directory for the current run_id. (self.path contains the base path - hdfs:/some/path/run_id/artifacts) Args: path: Relative source path. Possible subdirectory existing under hdfs:/some/path/run_id/artifacts Returns: List of FileInfos under given path """ hdfs_base_path = _resolve_base_path(self.path, path) with hdfs_system(scheme=self.scheme, host=self.host, port=self.port) as hdfs: paths = [] base_info = hdfs.get_file_info(hdfs_base_path) if base_info.type == FileType.Directory: selector = FileSelector(hdfs_base_path) elif base_info.type == FileType.File: selector = [hdfs_base_path] else: return [] for file_detail in hdfs.get_file_info(selector): file_name = file_detail.path # file_name is hdfs_base_path and not a child of that path if file_name == hdfs_base_path: continue # Strip off anything that comes before the artifact root e.g. hdfs://name offset = file_name.index(self.path) rel_path = _relative_path_remote(self.path, file_name[offset:]) is_dir = file_detail.type == FileType.Directory size = file_detail.size paths.append(FileInfo(rel_path, is_dir=is_dir, file_size=size)) return sorted(paths, key=lambda f: paths) def _is_directory(self, artifact_path): hdfs_base_path = _resolve_base_path(self.path, artifact_path) with hdfs_system(scheme=self.scheme, host=self.host, port=self.port) as hdfs: return hdfs.get_file_info(hdfs_base_path).type == FileType.Directory def _download_file(self, remote_file_path, local_path): hdfs_base_path = _resolve_base_path(self.path, remote_file_path) with hdfs_system(scheme=self.scheme, host=self.host, port=self.port) as hdfs: with hdfs.open_input_stream(hdfs_base_path) as source: with open(local_path, "wb") as destination: destination.write(source.read()) def delete_artifacts(self, artifact_path=None): path = posixpath.join(self.path, artifact_path) if artifact_path else self.path with hdfs_system(scheme=self.scheme, host=self.host, port=self.port) as hdfs: file_info = hdfs.get_file_info(path) if file_info.type == FileType.File: hdfs.delete_file(path) elif file_info.type == FileType.Directory: hdfs.delete_dir_contents(path) @contextmanager def hdfs_system(scheme, host, port): """ hdfs system context - Attempt to establish the connection to hdfs and yields HadoopFileSystem Args: scheme: scheme or use hdfs:// as default host: hostname or when relaying on the core-site.xml config use 'default' port: port or when relaying on the core-site.xml config use 0 """ kerb_ticket = MLFLOW_KERBEROS_TICKET_CACHE.get() kerberos_user = MLFLOW_KERBEROS_USER.get() extra_conf = _parse_extra_conf(MLFLOW_PYARROW_EXTRA_CONF.get()) host = scheme + "://" + host if host else "default" yield HadoopFileSystem( host=host, port=port or 0, user=kerberos_user, kerb_ticket=kerb_ticket, extra_conf=extra_conf, ) def _resolve_connection_params(artifact_uri): parsed = urllib.parse.urlparse(artifact_uri) return parsed.scheme, parsed.hostname, parsed.port, parsed.path def _resolve_base_path(path, artifact_path): if path == artifact_path: return path if artifact_path: return posixpath.join(path, artifact_path) return path def _relative_path(base_dir, subdir_path, path_module): relative_path = path_module.relpath(subdir_path, base_dir) return relative_path if relative_path != "." else None def _relative_path_local(base_dir, subdir_path): rel_path = _relative_path(base_dir, subdir_path, os.path) return relative_path_to_artifact_path(rel_path) if rel_path is not None else None def _relative_path_remote(base_dir, subdir_path): return _relative_path(base_dir, subdir_path, posixpath) def _parse_extra_conf(extra_conf): if extra_conf: def as_pair(config): key, val = config.split("=") return key, val list_of_key_val = [as_pair(conf) for conf in extra_conf.split(",")] return dict(list_of_key_val) return None
HdfsArtifactRepository
python
getsentry__sentry
src/sentry/snuba/metrics/query.py
{ "start": 4072, "end": 4276 }
class ____: """ Modelled after snuba_sdk.conditions.Condition """ lhs: MetricField op: Op rhs: int | float | str Groupable = Union[str, Literal["project_id"]]
MetricConditionField
python
python__mypy
mypy/test/testsemanal.py
{ "start": 4716, "end": 6187 }
class ____(DataSuite): required_out_section = True files = ["semanal-typeinfo.test"] def run_case(self, testcase: DataDrivenTestCase) -> None: """Perform a test case.""" try: # Build test case input. src = "\n".join(testcase.input) result = build.build( sources=[BuildSource("main", None, src)], options=get_semanal_options(src, testcase), alt_lib_path=test_temp_dir, ) a = result.errors if a: raise CompileError(a) # Collect all TypeInfos in top-level modules. typeinfos = TypeInfoMap() for module, file in result.files.items(): if module in testcase.test_modules: for n in file.names.values(): if isinstance(n.node, TypeInfo): assert n.fullname if any(n.fullname.startswith(m + ".") for m in testcase.test_modules): typeinfos[n.fullname] = n.node # The output is the symbol table converted into a string. a = str(typeinfos).split("\n") except CompileError as e: a = e.messages assert_string_arrays_equal( testcase.output, a, f"Invalid semantic analyzer output ({testcase.file}, line {testcase.line})", )
SemAnalTypeInfoSuite
python
pytorch__pytorch
torch/_export/db/examples/constrain_as_size_example.py
{ "start": 42, "end": 515 }
class ____(torch.nn.Module): """ If the value is not known at tracing time, you can provide hint so that we can trace further. Please look at torch._check APIs. """ def forward(self, x): a = x.item() torch._check(a >= 0) torch._check(a <= 5) return torch.zeros((a, 5)) example_args = (torch.tensor(4),) tags = { "torch.dynamic-value", "torch.escape-hatch", } model = ConstrainAsSizeExample()
ConstrainAsSizeExample
python
joke2k__faker
faker/providers/person/pt_PT/__init__.py
{ "start": 44, "end": 6739 }
class ____(PersonProvider): formats_male = ( "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{prefix}} {{last_name}}", "{{first_name_male}} {{last_name}}-{{last_name}}", ) formats_female = ( "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{prefix}} {{last_name}}", "{{first_name_female}} {{last_name}}-{{last_name}}", "{{first_name_female}}-{{first_name_female}} {{last_name}}", ) formats = formats_male + formats_female first_names_male = ( "Afonso", "Alexandre", "Álvaro", "André", "Ângelo", "António", "Artur", "Benjamim", "Bernardo", "Brian", "Bruno", "Bryan", "Carlos", "Cláudio", "Cristiano", "César", "Daniel", "David", "Denis", "Diego", "Dinis", "Diogo", "Duarte", "Edgar", "Eduardo", "Emanuel", "Enzo", "Fernando", "Filipe", "Francisco", "Frederico", "Fábio", "Gabriel", "Gaspar", "Gil", "Gonçalo", "Guilherme", "Gustavo", "Henrique", "Hugo", "Igor", "Isaac", "Ismael", "Ivan", "Ivo", "Jaime", "Joaquim", "Joel", "Jorge", "José", "João", "Kevin", "Kévim", "Leandro", "Leonardo", "Lisandro", "Lourenço", "Luca", "Lucas", "Luís", "Manuel", "Marco", "Marcos", "Martim", "Mateus", "Matias", "Mauro", "Micael", "Miguel", "Márcio", "Mário", "Nelson", "Noa", "Noah", "Nuno", "Paulo", "Pedro", "Rafael", "Renato", "Ricardo", "Rodrigo", "Rui", "Rúben", "Salvador", "Samuel", "Sandro", "Santiago", "Sebastião", "Simão", "Sérgio", "Tiago", "Tomás", "Tomé", "Valentim", "Vasco", "Vicente", "Vítor", "William", "Wilson", "Xavier", ) first_names_female = ( "Adriana", "Alexandra", "Alice", "Alícia", "Amélia", "Ana", "Andreia", "Ângela", "Anita", "Ariana", "Beatriz", "Benedita", "Bianca", "Bruna", "Bárbara", "Caetana", "Camila", "Carlota", "Carminho", "Carolina", "Catarina", "Clara", "Constança", "Daniela", "Diana", "Débora", "Eduarda", "Ema", "Emma", "Emília", "Erica", "Érica", "Erika", "Eva", "Fabiana", "Filipa", "Flor", "Francisca", "Gabriela", "Helena", "Iara", "Inês", "Irina", "Íris", "Isabel", "Isabela", "Joana", "Juliana", "Jéssica", "Júlia", "Kelly", "Kyara", "Lara", "Larissa", "Laura", "Leonor", "Letícia", "Lia", "Lorena", "Luana", "Luciana", "Luna", "Luísa", "Lúcia", "Madalena", "Mafalda", "Mara", "Margarida", "Maria", "Mariana", "Marta", "Matilde", "Melissa", "Mia", "Miriam", "Mélanie", "Naiara", "Nair", "Nicole", "Nádia", "Núria", "Patrícia", "Petra", "Pilar", "Rafaela", "Raquel", "Renata", "Rita", "Salomé", "Sara", "Sofia", "Soraia", "Tatiana", "Teresa", "Valentina", "Vera", "Victória", "Violeta", "Vitória", "Yara", "Yasmin", ) first_names = first_names_male + first_names_female last_names = ( "Abreu", "Almeida", "Alves", "Amaral", "Amorim", "Andrade", "Anjos", "Antunes", "Araújo", "Assunção", "Azevedo", "Baptista", "Barbosa", "Barros", "Batista", "Borges", "Branco", "Brito", "Campos", "Cardoso", "Carneiro", "Carvalho", "Castro", "Coelho", "Correia", "Costa", "Cruz", "Cunha", "Domingues", "Esteves", "Faria", "Fernandes", "Ferreira", "Figueiredo", "Fonseca", "Freitas", "Garcia", "Gaspar", "Gomes", "Gonçalves", "Guerreiro", "Henriques", "Jesus", "Leal", "Leite", "Lima", "Lopes", "Loureiro", "Lourenço", "Macedo", "Machado", "Magalhães", "Maia", "Marques", "Martins", "Matias", "Matos", "Melo", "Mendes", "Miranda", "Monteiro", "Morais", "Moreira", "Mota", "Moura", "Nascimento", "Neto", "Neves", "Nogueira", "Nunes", "Oliveira", "Pacheco", "Paiva", "Pereira", "Pinheiro", "Pinho", "Pinto", "Pires", "Ramos", "Reis", "Ribeiro", "Rocha", "Rodrigues", "Santos", "Silva", "Simões", "Soares", "Sousa", "Sá", "Tavares", "Teixeira", "Torres", "Valente", "Vaz", "Vicente", "Vieira", ) prefixes = ("de", "da", "do") def prefix(self) -> str: return self.random_element(self.prefixes)
Provider
python
mlflow__mlflow
mlflow/anthropic/autolog.py
{ "start": 2099, "end": 5101 }
class ____: """Context manager for handling MLflow spans in both sync and async contexts.""" def __init__(self, original, instance, args, kwargs): self.original = original self.instance = instance self.inputs = construct_full_inputs(original, instance, *args, **kwargs) # These attributes are set outside the constructor. self.span = None self.output = None def __enter__(self): return self._enter_impl() def __exit__(self, exc_type, exc_val, exc_tb): self._exit_impl(exc_type, exc_val, exc_tb) async def __aenter__(self): return self._enter_impl() async def __aexit__(self, exc_type, exc_val, exc_tb): self._exit_impl(exc_type, exc_val, exc_tb) def _enter_impl(self): config = AutoLoggingConfig.init(flavor_name=mlflow.anthropic.FLAVOR_NAME) if config.log_traces: self.span = start_span_no_context( name=f"{self.instance.__class__.__name__}.{self.original.__name__}", span_type=_get_span_type(self.original.__name__), inputs=self.inputs, attributes={SpanAttributeKey.MESSAGE_FORMAT: "anthropic"}, ) _set_tool_attribute(self.span, self.inputs) return self def _exit_impl(self, exc_type, exc_val, exc_tb) -> None: if self.span: if exc_val: self.span.record_exception(exc_val) _set_token_usage_attribute(self.span, self.output) self.span.end(outputs=self.output) def _get_span_type(task_name: str) -> str: # Anthropic has a few APIs in beta, e.g., count_tokens. # Once they are stable, we can add them to the mapping. span_type_mapping = { "create": SpanType.CHAT_MODEL, } return span_type_mapping.get(task_name, SpanType.UNKNOWN) def _set_tool_attribute(span: LiveSpan, inputs: dict[str, Any]): if (tools := inputs.get("tools")) is not None: try: tools = [convert_tool_to_mlflow_chat_tool(tool) for tool in tools] set_span_chat_tools(span, tools) except Exception as e: _logger.debug(f"Failed to set tools for {span}. Error: {e}") def _set_token_usage_attribute(span: LiveSpan, output: Any): try: if usage := _parse_usage(output): span.set_attribute(SpanAttributeKey.CHAT_USAGE, usage) except Exception as e: _logger.debug(f"Failed to set token usage for {span}. Error: {e}") def _parse_usage(output: Any) -> dict[str, int] | None: try: if usage := getattr(output, "usage", None): return { TokenUsageKey.INPUT_TOKENS: usage.input_tokens, TokenUsageKey.OUTPUT_TOKENS: usage.output_tokens, TokenUsageKey.TOTAL_TOKENS: usage.input_tokens + usage.output_tokens, } except Exception as e: _logger.debug(f"Failed to parse token usage from output: {e}") return None
TracingSession
python
protocolbuffers__protobuf
python/google/protobuf/internal/duration_test.py
{ "start": 588, "end": 4008 }
class ____(unittest.TestCase): def test_duration_integer_conversion(self): self.assertEqual(1, duration.to_nanoseconds(duration.from_nanoseconds(1))) self.assertEqual(-1, duration.to_seconds(duration.from_seconds(-1))) self.assertEqual( 123, duration.to_milliseconds(duration.from_milliseconds(123)) ) self.assertEqual( 321, duration.to_microseconds(duration.from_microseconds(321)) ) def test_duration_json(self): def check_duration(message, text): self.assertEqual(text, duration.to_json_string(message)) parsed_duration = duration.from_json_string(text) self.assertEqual(message, parsed_duration) message = duration_pb2.Duration() message.seconds = 0 message.nanos = 0 check_duration(message, '0s') message.nanos = 10000000 check_duration(message, '0.010s') message.nanos = 10000 check_duration(message, '0.000010s') message.nanos = 10 check_duration(message, '0.000000010s') def test_duration_timedelta(self): message = duration.from_nanoseconds(1999999999) td = duration.to_timedelta(message) self.assertEqual(1, td.seconds) self.assertEqual(999999, td.microseconds) message = duration.from_microseconds(-1) td = duration.to_timedelta(message) converted_message = duration.from_timedelta(td) self.assertEqual(message, converted_message) def test_duration_construction(self): expected_td = datetime.timedelta(microseconds=123) message = well_known_types_test_pb2.WKTMessage( optional_duration=expected_td ) self.assertEqual(expected_td, message.optional_duration.ToTimedelta()) def test_repeated_duration_construction(self): td0 = datetime.timedelta(microseconds=123) td1 = datetime.timedelta(microseconds=456) dr = duration_pb2.Duration() message = well_known_types_test_pb2.WKTMessage(repeated_td=[td0, td1, dr]) self.assertEqual(td0, duration.to_timedelta(message.repeated_td[0])) self.assertEqual(td1, duration.to_timedelta(message.repeated_td[1])) self.assertEqual(dr, message.repeated_td[2]) def test_duration_sub_annotation(self): dt = datetime.datetime.now() dr = duration_pb2.Duration() td = datetime.timedelta(microseconds=123) # datetime - Duration self.assertEqual(dt - dr, dt - duration.to_timedelta(dr)) # timedelta - Duration and Duration - Duration self.assertEqual(td - dr, duration.from_timedelta(td) - dr) # Duration - timedelta self.assertEqual(dr - td, dr - duration.from_timedelta(td)) def test_duration_add_annotation(self): dt = datetime.datetime.now() dr = duration_pb2.Duration() dr2 = duration_pb2.Duration(seconds=100) # datetime + Duration and Duration + datetime self.assertEqual(dt + dr, dr + dt) message = well_known_types_test_pb2.WKTMessage(optional_timestamp=dt) # Duration + Timestamp self.assertEqual(dr + message.optional_timestamp, dr + dt) td = datetime.timedelta(microseconds=123) # Duration + timedelta and timedelta + Duration self.assertEqual(dr + td, td + dr) # Duration + Duration self.assertEqual(dr + dr2, dr2 + dr) def test_assign_datetime_to_duration(self): message = well_known_types_test_pb2.WKTMessage() with self.assertRaises((TypeError)): message.optional_duration = datetime.datetime.now() if __name__ == '__main__': unittest.main()
DurationTest
python
zarr-developers__zarr-python
src/zarr/core/metadata/v3.py
{ "start": 4833, "end": 5950 }
class ____(TypedDict): """ This class models allowed extra fields in array metadata. They are ignored by Zarr Python. """ must_understand: Literal[False] def check_allowed_extra_field(data: object) -> TypeGuard[AllowedExtraField]: """ Check if the extra field is allowed according to the Zarr v3 spec. The object must be a mapping with a "must_understand" key set to `False`. """ return isinstance(data, Mapping) and data.get("must_understand") is False def parse_extra_fields( data: Mapping[str, AllowedExtraField] | None, ) -> dict[str, AllowedExtraField]: if data is None: return {} else: conflict_keys = ARRAY_METADATA_KEYS & set(data.keys()) if len(conflict_keys) > 0: msg = ( "Invalid extra fields. " "The following keys: " f"{sorted(conflict_keys)} " "are invalid because they collide with keys reserved for use by the " "array metadata document." ) raise ValueError(msg) return dict(data)
AllowedExtraField
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mysql/reflection.py
{ "start": 1317, "end": 24609 }
class ____: """Parses the results of a SHOW CREATE TABLE statement.""" def __init__( self, dialect: MySQLDialect, preparer: MySQLIdentifierPreparer ): self.dialect = dialect self.preparer = preparer self._prep_regexes() def parse( self, show_create: str, charset: Optional[str] ) -> ReflectedState: state = ReflectedState() state.charset = charset for line in re.split(r"\r?\n", show_create): if line.startswith(" " + self.preparer.initial_quote): self._parse_column(line, state) # a regular table options line elif line.startswith(") "): self._parse_table_options(line, state) # an ANSI-mode table options line elif line == ")": pass elif line.startswith("CREATE "): self._parse_table_name(line, state) elif "PARTITION" in line: self._parse_partition_options(line, state) # Not present in real reflection, but may be if # loading from a file. elif not line: pass else: type_, spec = self._parse_constraints(line) if type_ is None: util.warn("Unknown schema content: %r" % line) elif type_ == "key": state.keys.append(spec) # type: ignore[arg-type] elif type_ == "fk_constraint": state.fk_constraints.append(spec) # type: ignore[arg-type] elif type_ == "ck_constraint": state.ck_constraints.append(spec) # type: ignore[arg-type] else: pass return state def _check_view(self, sql: str) -> bool: return bool(self._re_is_view.match(sql)) def _parse_constraints(self, line: str) -> Union[ tuple[None, str], tuple[Literal["partition"], str], tuple[ Literal["ck_constraint", "fk_constraint", "key"], dict[str, str] ], ]: """Parse a KEY or CONSTRAINT line. :param line: A line of SHOW CREATE TABLE output """ # KEY m = self._re_key.match(line) if m: spec = m.groupdict() # convert columns into name, length pairs # NOTE: we may want to consider SHOW INDEX as the # format of indexes in MySQL becomes more complex spec["columns"] = self._parse_keyexprs(spec["columns"]) if spec["version_sql"]: m2 = self._re_key_version_sql.match(spec["version_sql"]) if m2 and m2.groupdict()["parser"]: spec["parser"] = m2.groupdict()["parser"] if spec["parser"]: spec["parser"] = self.preparer.unformat_identifiers( spec["parser"] )[0] return "key", spec # FOREIGN KEY CONSTRAINT m = self._re_fk_constraint.match(line) if m: spec = m.groupdict() spec["table"] = self.preparer.unformat_identifiers(spec["table"]) spec["local"] = [c[0] for c in self._parse_keyexprs(spec["local"])] spec["foreign"] = [ c[0] for c in self._parse_keyexprs(spec["foreign"]) ] return "fk_constraint", spec # CHECK constraint m = self._re_ck_constraint.match(line) if m: spec = m.groupdict() return "ck_constraint", spec # PARTITION and SUBPARTITION m = self._re_partition.match(line) if m: # Punt! return "partition", line # No match. return (None, line) def _parse_table_name(self, line: str, state: ReflectedState) -> None: """Extract the table name. :param line: The first line of SHOW CREATE TABLE """ regex, cleanup = self._pr_name m = regex.match(line) if m: state.table_name = cleanup(m.group("name")) def _parse_table_options(self, line: str, state: ReflectedState) -> None: """Build a dictionary of all reflected table-level options. :param line: The final line of SHOW CREATE TABLE output. """ options = {} if line and line != ")": rest_of_line = line for regex, cleanup in self._pr_options: m = regex.search(rest_of_line) if not m: continue directive, value = m.group("directive"), m.group("val") if cleanup: value = cleanup(value) options[directive.lower()] = value rest_of_line = regex.sub("", rest_of_line) for nope in ("auto_increment", "data directory", "index directory"): options.pop(nope, None) for opt, val in options.items(): state.table_options["%s_%s" % (self.dialect.name, opt)] = val def _parse_partition_options( self, line: str, state: ReflectedState ) -> None: options = {} new_line = line[:] while new_line.startswith("(") or new_line.startswith(" "): new_line = new_line[1:] for regex, cleanup in self._pr_options: m = regex.search(new_line) if not m or "PARTITION" not in regex.pattern: continue directive = m.group("directive") directive = directive.lower() is_subpartition = directive == "subpartition" if directive == "partition" or is_subpartition: new_line = new_line.replace(") */", "") new_line = new_line.replace(",", "") if is_subpartition and new_line.endswith(")"): new_line = new_line[:-1] if self.dialect.name == "mariadb" and new_line.endswith(")"): if ( "MAXVALUE" in new_line or "MINVALUE" in new_line or "ENGINE" in new_line ): # final line of MariaDB partition endswith ")" new_line = new_line[:-1] defs = "%s_%s_definitions" % (self.dialect.name, directive) options[defs] = new_line else: directive = directive.replace(" ", "_") value = m.group("val") if cleanup: value = cleanup(value) options[directive] = value break for opt, val in options.items(): part_def = "%s_partition_definitions" % (self.dialect.name) subpart_def = "%s_subpartition_definitions" % (self.dialect.name) if opt == part_def or opt == subpart_def: # builds a string of definitions if opt not in state.table_options: state.table_options[opt] = val else: state.table_options[opt] = "%s, %s" % ( state.table_options[opt], val, ) else: state.table_options["%s_%s" % (self.dialect.name, opt)] = val def _parse_column(self, line: str, state: ReflectedState) -> None: """Extract column details. Falls back to a 'minimal support' variant if full parse fails. :param line: Any column-bearing line from SHOW CREATE TABLE """ spec = None m = self._re_column.match(line) if m: spec = m.groupdict() spec["full"] = True else: m = self._re_column_loose.match(line) if m: spec = m.groupdict() spec["full"] = False if not spec: util.warn("Unknown column definition %r" % line) return if not spec["full"]: util.warn("Incomplete reflection of column definition %r" % line) name, type_, args = spec["name"], spec["coltype"], spec["arg"] try: col_type = self.dialect.ischema_names[type_] except KeyError: util.warn( "Did not recognize type '%s' of column '%s'" % (type_, name) ) col_type = sqltypes.NullType # Column type positional arguments eg. varchar(32) if args is None or args == "": type_args = [] elif args[0] == "'" and args[-1] == "'": type_args = self._re_csv_str.findall(args) else: type_args = [int(v) for v in self._re_csv_int.findall(args)] # Column type keyword options type_kw = {} if issubclass(col_type, (DATETIME, TIME, TIMESTAMP)): if type_args: type_kw["fsp"] = type_args.pop(0) for kw in ("unsigned", "zerofill"): if spec.get(kw, False): type_kw[kw] = True for kw in ("charset", "collate"): if spec.get(kw, False): type_kw[kw] = spec[kw] if issubclass(col_type, (ENUM, SET)): type_args = _strip_values(type_args) if issubclass(col_type, SET) and "" in type_args: type_kw["retrieve_as_bitwise"] = True type_instance = col_type(*type_args, **type_kw) col_kw: dict[str, Any] = {} # NOT NULL col_kw["nullable"] = True # this can be "NULL" in the case of TIMESTAMP if spec.get("notnull", False) == "NOT NULL": col_kw["nullable"] = False # For generated columns, the nullability is marked in a different place if spec.get("notnull_generated", False) == "NOT NULL": col_kw["nullable"] = False # AUTO_INCREMENT if spec.get("autoincr", False): col_kw["autoincrement"] = True elif issubclass(col_type, sqltypes.Integer): col_kw["autoincrement"] = False # DEFAULT default = spec.get("default", None) if default == "NULL": # eliminates the need to deal with this later. default = None comment = spec.get("comment", None) if comment is not None: comment = cleanup_text(comment) sqltext = spec.get("generated") if sqltext is not None: computed = dict(sqltext=sqltext) persisted = spec.get("persistence") if persisted is not None: computed["persisted"] = persisted == "STORED" col_kw["computed"] = computed col_d = dict( name=name, type=type_instance, default=default, comment=comment ) col_d.update(col_kw) state.columns.append(col_d) # type: ignore[arg-type] def _describe_to_create( self, table_name: str, columns: Sequence[tuple[str, str, str, str, str, str]], ) -> str: """Re-format DESCRIBE output as a SHOW CREATE TABLE string. DESCRIBE is a much simpler reflection and is sufficient for reflecting views for runtime use. This method formats DDL for columns only- keys are omitted. :param columns: A sequence of DESCRIBE or SHOW COLUMNS 6-tuples. SHOW FULL COLUMNS FROM rows must be rearranged for use with this function. """ buffer = [] for row in columns: (name, col_type, nullable, default, extra) = ( row[i] for i in (0, 1, 2, 4, 5) ) line = [" "] line.append(self.preparer.quote_identifier(name)) line.append(col_type) if not nullable: line.append("NOT NULL") if default: if "auto_increment" in default: pass elif col_type.startswith("timestamp") and default.startswith( "C" ): line.append("DEFAULT") line.append(default) elif default == "NULL": line.append("DEFAULT") line.append(default) else: line.append("DEFAULT") line.append("'%s'" % default.replace("'", "''")) if extra: line.append(extra) buffer.append(" ".join(line)) return "".join( [ ( "CREATE TABLE %s (\n" % self.preparer.quote_identifier(table_name) ), ",\n".join(buffer), "\n) ", ] ) def _parse_keyexprs( self, identifiers: str ) -> list[tuple[str, Optional[int], str]]: """Unpack '"col"(2),"col" ASC'-ish strings into components.""" return [ (colname, int(length) if length else None, modifiers) for colname, length, modifiers in self._re_keyexprs.findall( identifiers ) ] def _prep_regexes(self) -> None: """Pre-compile regular expressions.""" self._pr_options: list[ tuple[re.Pattern[Any], Optional[Callable[[str], str]]] ] = [] _final = self.preparer.final_quote quotes = dict( zip( ("iq", "fq", "esc_fq"), [ re.escape(s) for s in ( self.preparer.initial_quote, _final, self.preparer._escape_identifier(_final), ) ], ) ) self._pr_name = _pr_compile( r"^CREATE (?:\w+ +)?TABLE +" r"%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s +\($" % quotes, self.preparer._unescape_identifier, ) self._re_is_view = _re_compile(r"^CREATE(?! TABLE)(\s.*)?\sVIEW") # `col`,`col2`(32),`col3`(15) DESC # self._re_keyexprs = _re_compile( r"(?:" r"(?:%(iq)s((?:%(esc_fq)s|[^%(fq)s])+)%(fq)s)" r"(?:\((\d+)\))?(?: +(ASC|DESC))?(?=\,|$))+" % quotes ) # 'foo' or 'foo','bar' or 'fo,o','ba''a''r' self._re_csv_str = _re_compile(r"\x27(?:\x27\x27|[^\x27])*\x27") # 123 or 123,456 self._re_csv_int = _re_compile(r"\d+") # `colname` <type> [type opts] # (NOT NULL | NULL) # DEFAULT ('value' | CURRENT_TIMESTAMP...) # COMMENT 'comment' # COLUMN_FORMAT (FIXED|DYNAMIC|DEFAULT) # STORAGE (DISK|MEMORY) self._re_column = _re_compile( r" " r"%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s +" r"(?P<coltype>\w+)" r"(?:\((?P<arg>(?:\d+|\d+,\d+|" r"(?:'(?:''|[^'])*',?)+))\))?" r"(?: +(?P<unsigned>UNSIGNED))?" r"(?: +(?P<zerofill>ZEROFILL))?" r"(?: +CHARACTER SET +(?P<charset>[\w_]+))?" r"(?: +COLLATE +(?P<collate>[\w_]+))?" r"(?: +(?P<notnull>(?:NOT )?NULL))?" r"(?: +DEFAULT +(?P<default>" r"(?:NULL|'(?:''|[^'])*'|\(.+?\)|[\-\w\.\(\)]+" r"(?: +ON UPDATE [\-\w\.\(\)]+)?)" r"))?" r"(?: +(?:GENERATED ALWAYS)? ?AS +(?P<generated>\(" r".*\))? ?(?P<persistence>VIRTUAL|STORED)?" r"(?: +(?P<notnull_generated>(?:NOT )?NULL))?" r")?" r"(?: +(?P<autoincr>AUTO_INCREMENT))?" r"(?: +COMMENT +'(?P<comment>(?:''|[^'])*)')?" r"(?: +COLUMN_FORMAT +(?P<colfmt>\w+))?" r"(?: +STORAGE +(?P<storage>\w+))?" r"(?: +(?P<extra>.*))?" r",?$" % quotes ) # Fallback, try to parse as little as possible self._re_column_loose = _re_compile( r" " r"%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s +" r"(?P<coltype>\w+)" r"(?:\((?P<arg>(?:\d+|\d+,\d+|\x27(?:\x27\x27|[^\x27])+\x27))\))?" r".*?(?P<notnull>(?:NOT )NULL)?" % quotes ) # (PRIMARY|UNIQUE|FULLTEXT|SPATIAL) INDEX `name` (USING (BTREE|HASH))? # (`col` (ASC|DESC)?, `col` (ASC|DESC)?) # KEY_BLOCK_SIZE size | WITH PARSER name /*!50100 WITH PARSER name */ self._re_key = _re_compile( r" " r"(?:(?P<type>\S+) )?KEY" r"(?: +%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s)?" r"(?: +USING +(?P<using_pre>\S+))?" r" +\((?P<columns>.+?)\)" r"(?: +USING +(?P<using_post>\S+))?" r"(?: +KEY_BLOCK_SIZE *[ =]? *(?P<keyblock>\S+))?" r"(?: +WITH PARSER +(?P<parser>\S+))?" r"(?: +COMMENT +(?P<comment>(\x27\x27|\x27([^\x27])*?\x27)+))?" r"(?: +/\*(?P<version_sql>.+)\*/ *)?" r",?$" % quotes ) # https://forums.mysql.com/read.php?20,567102,567111#msg-567111 # It means if the MySQL version >= \d+, execute what's in the comment self._re_key_version_sql = _re_compile( r"\!\d+ " r"(?: *WITH PARSER +(?P<parser>\S+) *)?" ) # CONSTRAINT `name` FOREIGN KEY (`local_col`) # REFERENCES `remote` (`remote_col`) # MATCH FULL | MATCH PARTIAL | MATCH SIMPLE # ON DELETE CASCADE ON UPDATE RESTRICT # # unique constraints come back as KEYs kw = quotes.copy() kw["on"] = "RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT" self._re_fk_constraint = _re_compile( r" " r"CONSTRAINT +" r"%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s +" r"FOREIGN KEY +" r"\((?P<local>[^\)]+?)\) REFERENCES +" r"(?P<table>%(iq)s[^%(fq)s]+%(fq)s" r"(?:\.%(iq)s[^%(fq)s]+%(fq)s)?) +" r"\((?P<foreign>(?:%(iq)s[^%(fq)s]+%(fq)s(?: *, *)?)+)\)" r"(?: +(?P<match>MATCH \w+))?" r"(?: +ON DELETE (?P<ondelete>%(on)s))?" r"(?: +ON UPDATE (?P<onupdate>%(on)s))?" % kw ) # CONSTRAINT `CONSTRAINT_1` CHECK (`x` > 5)' # testing on MariaDB 10.2 shows that the CHECK constraint # is returned on a line by itself, so to match without worrying # about parenthesis in the expression we go to the end of the line self._re_ck_constraint = _re_compile( r" " r"CONSTRAINT +" r"%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s +" r"CHECK +" r"\((?P<sqltext>.+)\),?" % kw ) # PARTITION # # punt! self._re_partition = _re_compile(r"(?:.*)(?:SUB)?PARTITION(?:.*)") # Table-level options (COLLATE, ENGINE, etc.) # Do the string options first, since they have quoted # strings we need to get rid of. for option in _options_of_type_string: self._add_option_string(option) for option in ( "ENGINE", "TYPE", "AUTO_INCREMENT", "AVG_ROW_LENGTH", "CHARACTER SET", "DEFAULT CHARSET", "CHECKSUM", "COLLATE", "DELAY_KEY_WRITE", "INSERT_METHOD", "MAX_ROWS", "MIN_ROWS", "PACK_KEYS", "ROW_FORMAT", "KEY_BLOCK_SIZE", "STATS_SAMPLE_PAGES", ): self._add_option_word(option) for option in ( "PARTITION BY", "SUBPARTITION BY", "PARTITIONS", "SUBPARTITIONS", "PARTITION", "SUBPARTITION", ): self._add_partition_option_word(option) self._add_option_regex("UNION", r"\([^\)]+\)") self._add_option_regex("TABLESPACE", r".*? STORAGE DISK") self._add_option_regex( "RAID_TYPE", r"\w+\s+RAID_CHUNKS\s*\=\s*\w+RAID_CHUNKSIZE\s*=\s*\w+", ) _optional_equals = r"(?:\s*(?:=\s*)|\s+)" def _add_option_string(self, directive: str) -> None: regex = r"(?P<directive>%s)%s" r"'(?P<val>(?:[^']|'')*?)'(?!')" % ( re.escape(directive), self._optional_equals, ) self._pr_options.append(_pr_compile(regex, cleanup_text)) def _add_option_word(self, directive: str) -> None: regex = r"(?P<directive>%s)%s" r"(?P<val>\w+)" % ( re.escape(directive), self._optional_equals, ) self._pr_options.append(_pr_compile(regex)) def _add_partition_option_word(self, directive: str) -> None: if directive == "PARTITION BY" or directive == "SUBPARTITION BY": regex = r"(?<!\S)(?P<directive>%s)%s" r"(?P<val>\w+.*)" % ( re.escape(directive), self._optional_equals, ) elif directive == "SUBPARTITIONS" or directive == "PARTITIONS": regex = r"(?<!\S)(?P<directive>%s)%s" r"(?P<val>\d+)" % ( re.escape(directive), self._optional_equals, ) else: regex = r"(?<!\S)(?P<directive>%s)(?!\S)" % (re.escape(directive),) self._pr_options.append(_pr_compile(regex)) def _add_option_regex(self, directive: str, regex: str) -> None: regex = r"(?P<directive>%s)%s" r"(?P<val>%s)" % ( re.escape(directive), self._optional_equals, regex, ) self._pr_options.append(_pr_compile(regex)) _options_of_type_string = ( "COMMENT", "DATA DIRECTORY", "INDEX DIRECTORY", "PASSWORD", "CONNECTION", ) @overload def _pr_compile( regex: str, cleanup: Callable[[str], str] ) -> tuple[re.Pattern[Any], Callable[[str], str]]: ... @overload def _pr_compile( regex: str, cleanup: None = None ) -> tuple[re.Pattern[Any], None]: ... def _pr_compile( regex: str, cleanup: Optional[Callable[[str], str]] = None ) -> tuple[re.Pattern[Any], Optional[Callable[[str], str]]]: """Prepare a 2-tuple of compiled regex and callable.""" return (_re_compile(regex), cleanup) def _re_compile(regex: str) -> re.Pattern[Any]: """Compile a string to regex, I and UNICODE.""" return re.compile(regex, re.I | re.UNICODE) def _strip_values(values: Sequence[str]) -> list[str]: "Strip reflected values quotes" strip_values: list[str] = [] for a in values: if a[0:1] == '"' or a[0:1] == "'": # strip enclosing quotes and unquote interior a = a[1:-1].replace(a[0] * 2, a[0]) strip_values.append(a) return strip_values def cleanup_text(raw_text: str) -> str: if "\\" in raw_text: raw_text = re.sub( _control_char_regexp, lambda s: _control_char_map[s[0]], # type: ignore[index] raw_text, ) return raw_text.replace("''", "'") _control_char_map = { "\\\\": "\\", "\\0": "\0", "\\a": "\a", "\\b": "\b", "\\t": "\t", "\\n": "\n", "\\v": "\v", "\\f": "\f", "\\r": "\r", # '\\e':'\e', } _control_char_regexp = re.compile( "|".join(re.escape(k) for k in _control_char_map) )
MySQLTableDefinitionParser
python
Textualize__textual
src/textual/scrollbar.py
{ "start": 1203, "end": 1740 }
class ____(ScrollMessage, verbose=True): """Message sent when click and dragging handle.""" __slots__ = ["x", "y", "animate"] def __init__( self, x: float | None = None, y: float | None = None, animate: bool = True, ) -> None: self.x = x self.y = y self.animate = animate super().__init__() def __rich_repr__(self) -> rich.repr.Result: yield "x", self.x, None yield "y", self.y, None yield "animate", self.animate, True
ScrollTo
python
pdm-project__pdm
src/pdm/models/working_set.py
{ "start": 2165, "end": 3367 }
class ____(Mapping[str, im.Distribution]): """A dictionary of currently installed distributions""" def __init__(self, paths: list[str] | None = None, shared_paths: list[str] | None = None) -> None: if paths is None: paths = sys.path if shared_paths is None: shared_paths = [] self._dist_map = { normalize_name(dist.metadata["Name"]): dist for dist in distributions(path=list(dict.fromkeys(paths))) if dist.metadata.get("Name") } self._shared_map = { normalize_name(dist.metadata["Name"]): dist for dist in distributions(path=list(dict.fromkeys(shared_paths))) if dist.metadata.get("Name") } self._iter_map = ChainMap(self._dist_map, self._shared_map) def __getitem__(self, key: str) -> im.Distribution: return self._iter_map[key] def is_owned(self, key: str) -> bool: return key in self._dist_map def __len__(self) -> int: return len(self._iter_map) def __iter__(self) -> Iterator[str]: return iter(self._iter_map) def __repr__(self) -> str: return repr(self._iter_map)
WorkingSet
python
pytoolz__cytoolz
cytoolz/tests/test_dicttoolz.py
{ "start": 8054, "end": 9047 }
class ____(TestDict): """Test CustomMapping as input and factory Class attributes: D: callable that inputs a dict and creates or returns a MutableMapping kw: kwargs dict to specify "factory" keyword (if applicable) """ D = CustomMapping kw = {'factory': lambda: CustomMapping()} def test_environ(): # See: https://github.com/pycytoolz/cycytoolz/issues/127 assert keymap(identity, os.environ) == os.environ assert valmap(identity, os.environ) == os.environ assert itemmap(identity, os.environ) == os.environ def test_merge_with_non_dict_mappings(): class Foo(Mapping): def __init__(self, d): self.d = d def __iter__(self): return iter(self.d) def __getitem__(self, key): return self.d[key] def __len__(self): return len(self.d) d = Foo({1: 1}) assert merge(d) is d or merge(d) == {1: 1} assert merge_with(sum, d) == {1: 1}
TestCustomMapping
python
Textualize__textual
tests/snapshot_tests/language_snippets.py
{ "start": 971, "end": 1143 }
class ____: def __init__(self, name): self.name = name def speak(self): raise NotImplementedError("Subclasses must implement this method.")
Animal
python
pandas-dev__pandas
asv_bench/benchmarks/indexing.py
{ "start": 10655, "end": 11050 }
class ____: def setup(self): dti = date_range("2016-01-01", periods=10000, tz="US/Pacific") dti2 = dti.tz_convert("UTC") self.dti = dti self.dti2 = dti2 def time_get_indexer_mismatched_tz(self): # reached via e.g. # ser = Series(range(len(dti)), index=dti) # ser[dti2] self.dti.get_indexer(self.dti2)
DatetimeIndexIndexing
python
readthedocs__readthedocs.org
readthedocs/integrations/models.py
{ "start": 7262, "end": 9677 }
class ____(models.QuerySet): """ Return a subclass of Integration, based on the integration type. .. note:: This doesn't affect queries currently, only fetching of an object """ def _get_subclass(self, integration_type): # Build a mapping of integration_type -> class dynamically class_map = { cls.integration_type_id: cls for cls in self.model.__subclasses__() if hasattr(cls, "integration_type_id") } # yapf: disable return class_map.get(integration_type) def _get_subclass_replacement(self, original): """ Replace model instance on Integration subclasses. This is based on the ``integration_type`` field, and is used to provide specific functionality to and integration via a proxy subclass of the Integration model. """ cls_replace = self._get_subclass(original.integration_type) if cls_replace is None: return original new = cls_replace() for k, v in list(original.__dict__.items()): new.__dict__[k] = v return new def get(self, *args, **kwargs): original = super().get(*args, **kwargs) return self._get_subclass_replacement(original) def subclass(self, instance=None): """ Return a subclass or list of subclasses integrations. If an instance was passed in, return a single subclasses integration instance. If this is a queryset or manager, render the list as a list using the integration subsclasses. """ if instance is None: return [self._get_subclass_replacement(_instance) for _instance in self] return self._get_subclass_replacement(instance) def create(self, **kwargs): """ Override of create method to use subclass instance instead. Instead of using the underlying Integration model to create this instance, we get the correct subclass to use instead. This allows for overrides to ``save`` and other model functions on object creation. """ model_cls = self._get_subclass(kwargs.get("integration_type")) if model_cls is None: model_cls = self.model obj = model_cls(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj
IntegrationQuerySet
python
python-openxml__python-docx
tests/opc/test_package.py
{ "start": 10615, "end": 17017 }
class ____: def it_can_unmarshal_from_a_pkg_reader( self, pkg_reader_, pkg_, part_factory_, _unmarshal_parts_, _unmarshal_relationships_, parts_dict_, ): _unmarshal_parts_.return_value = parts_dict_ Unmarshaller.unmarshal(pkg_reader_, pkg_, part_factory_) _unmarshal_parts_.assert_called_once_with(pkg_reader_, pkg_, part_factory_) _unmarshal_relationships_.assert_called_once_with(pkg_reader_, pkg_, parts_dict_) for part in parts_dict_.values(): part.after_unmarshal.assert_called_once_with() pkg_.after_unmarshal.assert_called_once_with() def it_can_unmarshal_parts( self, pkg_reader_, pkg_, part_factory_, parts_dict_, partnames_, content_types_, reltypes_, blobs_, ): # fixture ---------------------- partname_, partname_2_ = partnames_ content_type_, content_type_2_ = content_types_ reltype_, reltype_2_ = reltypes_ blob_, blob_2_ = blobs_ # exercise --------------------- parts = Unmarshaller._unmarshal_parts(pkg_reader_, pkg_, part_factory_) # verify ----------------------- assert part_factory_.call_args_list == [ call(partname_, content_type_, reltype_, blob_, pkg_), call(partname_2_, content_type_2_, reltype_2_, blob_2_, pkg_), ] assert parts == parts_dict_ def it_can_unmarshal_relationships(self): # test data -------------------- reltype = "http://reltype" # mockery ---------------------- pkg_reader = Mock(name="pkg_reader") pkg_reader.iter_srels.return_value = ( ( "/", Mock( name="srel1", rId="rId1", reltype=reltype, target_partname="partname1", is_external=False, ), ), ( "/", Mock( name="srel2", rId="rId2", reltype=reltype, target_ref="target_ref_1", is_external=True, ), ), ( "partname1", Mock( name="srel3", rId="rId3", reltype=reltype, target_partname="partname2", is_external=False, ), ), ( "partname2", Mock( name="srel4", rId="rId4", reltype=reltype, target_ref="target_ref_2", is_external=True, ), ), ) pkg = Mock(name="pkg") parts = {} for num in range(1, 3): name = "part%d" % num part = Mock(name=name) parts["partname%d" % num] = part pkg.attach_mock(part, name) # exercise --------------------- Unmarshaller._unmarshal_relationships(pkg_reader, pkg, parts) # verify ----------------------- expected_pkg_calls = [ call.load_rel(reltype, parts["partname1"], "rId1", False), call.load_rel(reltype, "target_ref_1", "rId2", True), call.part1.load_rel(reltype, parts["partname2"], "rId3", False), call.part2.load_rel(reltype, "target_ref_2", "rId4", True), ] assert pkg.mock_calls == expected_pkg_calls # fixtures --------------------------------------------- @pytest.fixture def blobs_(self, request: FixtureRequest): blob_ = loose_mock(request, spec=str, name="blob_") blob_2_ = loose_mock(request, spec=str, name="blob_2_") return blob_, blob_2_ @pytest.fixture def content_types_(self, request: FixtureRequest): content_type_ = loose_mock(request, spec=str, name="content_type_") content_type_2_ = loose_mock(request, spec=str, name="content_type_2_") return content_type_, content_type_2_ @pytest.fixture def part_factory_(self, request, parts_): part_factory_ = loose_mock(request, spec=Part) part_factory_.side_effect = parts_ return part_factory_ @pytest.fixture def partnames_(self, request: FixtureRequest): partname_ = loose_mock(request, spec=str, name="partname_") partname_2_ = loose_mock(request, spec=str, name="partname_2_") return partname_, partname_2_ @pytest.fixture def parts_(self, request: FixtureRequest): part_ = instance_mock(request, Part, name="part_") part_2_ = instance_mock(request, Part, name="part_2") return part_, part_2_ @pytest.fixture def parts_dict_(self, request, partnames_, parts_): partname_, partname_2_ = partnames_ part_, part_2_ = parts_ return {partname_: part_, partname_2_: part_2_} @pytest.fixture def pkg_(self, request: FixtureRequest): return instance_mock(request, OpcPackage) @pytest.fixture def pkg_reader_(self, request, partnames_, content_types_, reltypes_, blobs_): partname_, partname_2_ = partnames_ content_type_, content_type_2_ = content_types_ reltype_, reltype_2_ = reltypes_ blob_, blob_2_ = blobs_ iter_spart_items = ( (partname_, content_type_, reltype_, blob_), (partname_2_, content_type_2_, reltype_2_, blob_2_), ) pkg_reader_ = instance_mock(request, PackageReader) pkg_reader_.iter_sparts.return_value = iter_spart_items return pkg_reader_ @pytest.fixture def reltypes_(self, request: FixtureRequest): reltype_ = instance_mock(request, str, name="reltype_") reltype_2_ = instance_mock(request, str, name="reltype_2") return reltype_, reltype_2_ @pytest.fixture def _unmarshal_parts_(self, request: FixtureRequest): return method_mock(request, Unmarshaller, "_unmarshal_parts", autospec=False) @pytest.fixture def _unmarshal_relationships_(self, request: FixtureRequest): return method_mock(request, Unmarshaller, "_unmarshal_relationships", autospec=False)
DescribeUnmarshaller
python
pypa__pipenv
pipenv/patched/pip/_internal/resolution/resolvelib/candidates.py
{ "start": 9287, "end": 11523 }
class ____(_InstallRequirementBackedCandidate): is_editable = False def __init__( self, link: Link, template: InstallRequirement, factory: "Factory", name: Optional[NormalizedName] = None, version: Optional[Version] = None, ) -> None: source_link = link cache_entry = factory.get_wheel_cache_entry(source_link, name) if cache_entry is not None: logger.debug("Using cached wheel link: %s", cache_entry.link) link = cache_entry.link ireq = make_install_req_from_link(link, template) assert ireq.link == link if ireq.link.is_wheel and not ireq.link.is_file: wheel = Wheel(ireq.link.filename) wheel_name = canonicalize_name(wheel.name) assert name == wheel_name, f"{name!r} != {wheel_name!r} for wheel" # Version may not be present for PEP 508 direct URLs if version is not None: wheel_version = Version(wheel.version) assert ( version == wheel_version ), f"{version!r} != {wheel_version!r} for wheel {name}" if cache_entry is not None: assert ireq.link.is_wheel assert ireq.link.is_file if cache_entry.persistent and template.link is template.original_link: ireq.cached_wheel_source_link = source_link if cache_entry.origin is not None: ireq.download_info = cache_entry.origin else: # Legacy cache entry that does not have origin.json. # download_info may miss the archive_info.hashes field. ireq.download_info = direct_url_from_link( source_link, link_is_in_wheel_cache=cache_entry.persistent ) super().__init__( link=link, source_link=source_link, ireq=ireq, factory=factory, name=name, version=version, ) def _prepare_distribution(self) -> BaseDistribution: preparer = self._factory.preparer return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)
LinkCandidate
python
walkccc__LeetCode
solutions/3029. Minimum Time to Revert Word to Initial State I/3029.py
{ "start": 0, "end": 850 }
class ____: # Same as 3029. Minimum Time to Revert Word to Initial State I def minimumTimeToInitialState(self, word: str, k: int) -> int: n = len(word) maxOps = (n - 1) // k + 1 z = self._zFunction(word) for ans in range(1, maxOps): if z[ans * k] >= n - ans * k: return ans return maxOps def _zFunction(self, s: str) -> list[int]: """ Returns the z array, where z[i] is the length of the longest prefix of s[i..n) which is also a prefix of s. https://cp-algorithms.com/string/z-function.html#implementation """ n = len(s) z = [0] * n l = 0 r = 0 for i in range(1, n): if i < r: z[i] = min(r - i, z[i - l]) while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1 if i + z[i] > r: l = i r = i + z[i] return z
Solution
python
pandas-dev__pandas
pandas/tests/indexes/period/test_indexing.py
{ "start": 24667, "end": 25751 }
class ____: @pytest.mark.parametrize("freq", ["h", "D"]) def test_get_value_datetime_hourly(self, freq): # get_loc and get_value should treat datetime objects symmetrically # TODO: this test used to test get_value, which is removed in 2.0. # should this test be moved somewhere, or is what's left redundant? dti = date_range("2016-01-01", periods=3, freq="MS") pi = dti.to_period(freq) ser = Series(range(7, 10), index=pi) ts = dti[0] assert pi.get_loc(ts) == 0 assert ser[ts] == 7 assert ser.loc[ts] == 7 ts2 = ts + Timedelta(hours=3) if freq == "h": with pytest.raises(KeyError, match="2016-01-01 03:00"): pi.get_loc(ts2) with pytest.raises(KeyError, match="2016-01-01 03:00"): ser[ts2] with pytest.raises(KeyError, match="2016-01-01 03:00"): ser.loc[ts2] else: assert pi.get_loc(ts2) == 0 assert ser[ts2] == 7 assert ser.loc[ts2] == 7
TestGetValue
python
sqlalchemy__sqlalchemy
examples/dogpile_caching/model.py
{ "start": 1464, "end": 2132 }
class ____(Base): __tablename__ = "address" id = Column(Integer, primary_key=True) person_id = Column(Integer, ForeignKey("person.id"), nullable=False) street = Column(String(200), nullable=False) postal_code_id = Column(Integer, ForeignKey("postal_code.id")) postal_code = relationship(PostalCode) @property def city(self): return self.postal_code.city @property def country(self): return self.postal_code.country def __str__(self): return "%s\t%s, %s\t%s" % ( self.street, self.city.name, self.postal_code.code, self.country.name, )
Address
python
langchain-ai__langchain
libs/partners/anthropic/tests/unit_tests/middleware/test_prompt_caching.py
{ "start": 697, "end": 12413 }
class ____(BaseChatModel): """Fake model for testing middleware.""" def _generate( self, messages: list[BaseMessage], stop: list[str] | None = None, run_manager: CallbackManagerForLLMRun | None = None, **kwargs: Any, ) -> ChatResult: """Top Level call""" messages_string = "-".join([str(m.content) for m in messages]) message = AIMessage(content=messages_string, id="0") return ChatResult(generations=[ChatGeneration(message=message)]) async def _agenerate( self, messages: list[BaseMessage], stop: list[str] | None = None, run_manager: AsyncCallbackManagerForLLMRun | None = None, **kwargs: Any, ) -> ChatResult: """Async top level call""" messages_string = "-".join([str(m.content) for m in messages]) message = AIMessage(content=messages_string, id="0") return ChatResult(generations=[ChatGeneration(message=message)]) @property def _llm_type(self) -> str: return "fake-tool-call-model" def test_anthropic_prompt_caching_middleware_initialization() -> None: """Test AnthropicPromptCachingMiddleware initialization.""" # Test with custom values middleware = AnthropicPromptCachingMiddleware( type="ephemeral", ttl="1h", min_messages_to_cache=5 ) assert middleware.type == "ephemeral" assert middleware.ttl == "1h" assert middleware.min_messages_to_cache == 5 # Test with default values middleware = AnthropicPromptCachingMiddleware() assert middleware.type == "ephemeral" assert middleware.ttl == "5m" assert middleware.min_messages_to_cache == 0 # Create a mock ChatAnthropic instance mock_chat_anthropic = MagicMock(spec=ChatAnthropic) fake_request = ModelRequest( model=mock_chat_anthropic, messages=[HumanMessage("Hello")], system_prompt=None, tool_choice=None, tools=[], response_format=None, state={"messages": [HumanMessage("Hello")]}, runtime=cast(Runtime, object()), model_settings={}, ) modified_request: ModelRequest | None = None def mock_handler(req: ModelRequest) -> ModelResponse: nonlocal modified_request modified_request = req return ModelResponse(result=[AIMessage(content="mock response")]) middleware.wrap_model_call(fake_request, mock_handler) # Check that model_settings were passed through via the request assert modified_request is not None assert modified_request.model_settings == { "cache_control": {"type": "ephemeral", "ttl": "5m"} } def test_anthropic_prompt_caching_middleware_unsupported_model() -> None: """Test AnthropicPromptCachingMiddleware with unsupported model.""" fake_request = ModelRequest( model=FakeToolCallingModel(), messages=[HumanMessage("Hello")], system_prompt=None, tool_choice=None, tools=[], response_format=None, state={"messages": [HumanMessage("Hello")]}, runtime=cast(Runtime, object()), model_settings={}, ) middleware = AnthropicPromptCachingMiddleware(unsupported_model_behavior="raise") def mock_handler(req: ModelRequest) -> ModelResponse: return ModelResponse(result=[AIMessage(content="mock response")]) # Since we're in the langchain-anthropic package, ChatAnthropic is always # available. Test that it raises an error for unsupported model instances with pytest.raises( ValueError, match=( "AnthropicPromptCachingMiddleware caching middleware only supports " "Anthropic models, not instances of" ), ): middleware.wrap_model_call(fake_request, mock_handler) middleware = AnthropicPromptCachingMiddleware(unsupported_model_behavior="warn") # Test warn behavior for unsupported model instances with warnings.catch_warnings(record=True) as w: result = middleware.wrap_model_call(fake_request, mock_handler) assert isinstance(result, ModelResponse) assert len(w) == 1 assert ( "AnthropicPromptCachingMiddleware caching middleware only supports " "Anthropic models, not instances of" ) in str(w[-1].message) # Test ignore behavior middleware = AnthropicPromptCachingMiddleware(unsupported_model_behavior="ignore") result = middleware.wrap_model_call(fake_request, mock_handler) assert isinstance(result, ModelResponse) async def test_anthropic_prompt_caching_middleware_async() -> None: """Test AnthropicPromptCachingMiddleware async path.""" # Test with custom values middleware = AnthropicPromptCachingMiddleware( type="ephemeral", ttl="1h", min_messages_to_cache=5 ) # Create a mock ChatAnthropic instance mock_chat_anthropic = MagicMock(spec=ChatAnthropic) fake_request = ModelRequest( model=mock_chat_anthropic, messages=[HumanMessage("Hello")] * 6, system_prompt=None, tool_choice=None, tools=[], response_format=None, state={"messages": [HumanMessage("Hello")] * 6}, runtime=cast(Runtime, object()), model_settings={}, ) modified_request: ModelRequest | None = None async def mock_handler(req: ModelRequest) -> ModelResponse: nonlocal modified_request modified_request = req return ModelResponse(result=[AIMessage(content="mock response")]) result = await middleware.awrap_model_call(fake_request, mock_handler) assert isinstance(result, ModelResponse) # Check that model_settings were passed through via the request assert modified_request is not None assert modified_request.model_settings == { "cache_control": {"type": "ephemeral", "ttl": "1h"} } async def test_anthropic_prompt_caching_middleware_async_unsupported_model() -> None: """Test AnthropicPromptCachingMiddleware async path with unsupported model.""" fake_request = ModelRequest( model=FakeToolCallingModel(), messages=[HumanMessage("Hello")], system_prompt=None, tool_choice=None, tools=[], response_format=None, state={"messages": [HumanMessage("Hello")]}, runtime=cast(Runtime, object()), model_settings={}, ) middleware = AnthropicPromptCachingMiddleware(unsupported_model_behavior="raise") async def mock_handler(req: ModelRequest) -> ModelResponse: return ModelResponse(result=[AIMessage(content="mock response")]) # Test that it raises an error for unsupported model instances with pytest.raises( ValueError, match=( "AnthropicPromptCachingMiddleware caching middleware only supports " "Anthropic models, not instances of" ), ): await middleware.awrap_model_call(fake_request, mock_handler) middleware = AnthropicPromptCachingMiddleware(unsupported_model_behavior="warn") # Test warn behavior for unsupported model instances with warnings.catch_warnings(record=True) as w: result = await middleware.awrap_model_call(fake_request, mock_handler) assert isinstance(result, ModelResponse) assert len(w) == 1 assert ( "AnthropicPromptCachingMiddleware caching middleware only supports " "Anthropic models, not instances of" ) in str(w[-1].message) # Test ignore behavior middleware = AnthropicPromptCachingMiddleware(unsupported_model_behavior="ignore") result = await middleware.awrap_model_call(fake_request, mock_handler) assert isinstance(result, ModelResponse) async def test_anthropic_prompt_caching_middleware_async_min_messages() -> None: """Test async path respects min_messages_to_cache.""" middleware = AnthropicPromptCachingMiddleware(min_messages_to_cache=5) # Test with fewer messages than minimum fake_request = ModelRequest( model=FakeToolCallingModel(), messages=[HumanMessage("Hello")] * 3, system_prompt=None, tool_choice=None, tools=[], response_format=None, state={"messages": [HumanMessage("Hello")] * 3}, runtime=cast(Runtime, object()), model_settings={}, ) modified_request: ModelRequest | None = None async def mock_handler(req: ModelRequest) -> ModelResponse: nonlocal modified_request modified_request = req return ModelResponse(result=[AIMessage(content="mock response")]) result = await middleware.awrap_model_call(fake_request, mock_handler) assert isinstance(result, ModelResponse) # Cache control should NOT be added when message count is below minimum assert modified_request is not None assert modified_request.model_settings == {} async def test_anthropic_prompt_caching_middleware_async_with_system_prompt() -> None: """Test async path counts system prompt in message count.""" middleware = AnthropicPromptCachingMiddleware( type="ephemeral", ttl="1h", min_messages_to_cache=3 ) # Create a mock ChatAnthropic instance mock_chat_anthropic = MagicMock(spec=ChatAnthropic) # Test with system prompt: 2 messages + 1 system = 3 total (meets minimum) fake_request = ModelRequest( model=mock_chat_anthropic, messages=[HumanMessage("Hello"), HumanMessage("World")], system_prompt="You are a helpful assistant", tool_choice=None, tools=[], response_format=None, state={"messages": [HumanMessage("Hello"), HumanMessage("World")]}, runtime=cast(Runtime, object()), model_settings={}, ) modified_request: ModelRequest | None = None async def mock_handler(req: ModelRequest) -> ModelResponse: nonlocal modified_request modified_request = req return ModelResponse(result=[AIMessage(content="mock response")]) result = await middleware.awrap_model_call(fake_request, mock_handler) assert isinstance(result, ModelResponse) # Cache control should be added when system prompt pushes count to minimum assert modified_request is not None assert modified_request.model_settings == { "cache_control": {"type": "ephemeral", "ttl": "1h"} } async def test_anthropic_prompt_caching_middleware_async_default_values() -> None: """Test async path with default middleware initialization.""" # Test with default values (min_messages_to_cache=0) middleware = AnthropicPromptCachingMiddleware() # Create a mock ChatAnthropic instance mock_chat_anthropic = MagicMock(spec=ChatAnthropic) # Single message should trigger caching with default settings fake_request = ModelRequest( model=mock_chat_anthropic, messages=[HumanMessage("Hello")], system_prompt=None, tool_choice=None, tools=[], response_format=None, state={"messages": [HumanMessage("Hello")]}, runtime=cast(Runtime, object()), model_settings={}, ) modified_request: ModelRequest | None = None async def mock_handler(req: ModelRequest) -> ModelResponse: nonlocal modified_request modified_request = req return ModelResponse(result=[AIMessage(content="mock response")]) result = await middleware.awrap_model_call(fake_request, mock_handler) assert isinstance(result, ModelResponse) # Check that model_settings were added with default values assert modified_request is not None assert modified_request.model_settings == { "cache_control": {"type": "ephemeral", "ttl": "5m"} }
FakeToolCallingModel
python
python-openxml__python-docx
tests/test_table.py
{ "start": 11361, "end": 18978 }
class ____: """Unit-test suite for `docx.table._Cell` objects.""" @pytest.mark.parametrize( ("tc_cxml", "expected_value"), [ ("w:tc", 1), ("w:tc/w:tcPr", 1), ("w:tc/w:tcPr/w:gridSpan{w:val=1}", 1), ("w:tc/w:tcPr/w:gridSpan{w:val=4}", 4), ], ) def it_knows_its_grid_span(self, tc_cxml: str, expected_value: int, parent_: Mock): cell = _Cell(cast(CT_Tc, element(tc_cxml)), parent_) assert cell.grid_span == expected_value @pytest.mark.parametrize( ("tc_cxml", "expected_text"), [ ("w:tc", ""), ('w:tc/w:p/w:r/w:t"foobar"', "foobar"), ('w:tc/(w:p/w:r/w:t"foo",w:p/w:r/w:t"bar")', "foo\nbar"), ('w:tc/(w:tcPr,w:p/w:r/w:t"foobar")', "foobar"), ('w:tc/w:p/w:r/(w:t"fo",w:tab,w:t"ob",w:br,w:t"ar",w:br)', "fo\tob\nar\n"), ], ) def it_knows_what_text_it_contains(self, tc_cxml: str, expected_text: str, parent_: Mock): cell = _Cell(cast(CT_Tc, element(tc_cxml)), parent_) text = cell.text assert text == expected_text @pytest.mark.parametrize( ("tc_cxml", "new_text", "expected_cxml"), [ ("w:tc/w:p", "foobar", 'w:tc/w:p/w:r/w:t"foobar"'), ( "w:tc/w:p", "fo\tob\rar\n", 'w:tc/w:p/w:r/(w:t"fo",w:tab,w:t"ob",w:br,w:t"ar",w:br)', ), ( "w:tc/(w:tcPr, w:p, w:tbl, w:p)", "foobar", 'w:tc/(w:tcPr, w:p/w:r/w:t"foobar")', ), ], ) def it_can_replace_its_content_with_a_string_of_text( self, tc_cxml: str, new_text: str, expected_cxml: str, parent_: Mock ): cell = _Cell(cast(CT_Tc, element(tc_cxml)), parent_) cell.text = new_text assert cell._tc.xml == xml(expected_cxml) @pytest.mark.parametrize( ("tc_cxml", "expected_value"), [ ("w:tc", None), ("w:tc/w:tcPr", None), ("w:tc/w:tcPr/w:vAlign{w:val=bottom}", WD_ALIGN_VERTICAL.BOTTOM), ("w:tc/w:tcPr/w:vAlign{w:val=top}", WD_ALIGN_VERTICAL.TOP), ], ) def it_knows_its_vertical_alignment( self, tc_cxml: str, expected_value: WD_ALIGN_VERTICAL | None, parent_: Mock ): cell = _Cell(cast(CT_Tc, element(tc_cxml)), parent_) assert cell.vertical_alignment == expected_value @pytest.mark.parametrize( ("tc_cxml", "new_value", "expected_cxml"), [ ("w:tc", WD_ALIGN_VERTICAL.TOP, "w:tc/w:tcPr/w:vAlign{w:val=top}"), ( "w:tc/w:tcPr", WD_ALIGN_VERTICAL.CENTER, "w:tc/w:tcPr/w:vAlign{w:val=center}", ), ( "w:tc/w:tcPr/w:vAlign{w:val=center}", WD_ALIGN_VERTICAL.BOTTOM, "w:tc/w:tcPr/w:vAlign{w:val=bottom}", ), ("w:tc/w:tcPr/w:vAlign{w:val=center}", None, "w:tc/w:tcPr"), ("w:tc", None, "w:tc/w:tcPr"), ("w:tc/w:tcPr", None, "w:tc/w:tcPr"), ], ) def it_can_change_its_vertical_alignment( self, tc_cxml: str, new_value: WD_ALIGN_VERTICAL | None, expected_cxml: str, parent_: Mock ): cell = _Cell(cast(CT_Tc, element(tc_cxml)), parent_) cell.vertical_alignment = new_value assert cell._element.xml == xml(expected_cxml) @pytest.mark.parametrize( ("tc_cxml", "expected_value"), [ ("w:tc", None), ("w:tc/w:tcPr", None), ("w:tc/w:tcPr/w:tcW{w:w=25%,w:type=pct}", None), ("w:tc/w:tcPr/w:tcW{w:w=1440,w:type=dxa}", 914400), ], ) def it_knows_its_width_in_EMU(self, tc_cxml: str, expected_value: int | None, parent_: Mock): cell = _Cell(cast(CT_Tc, element(tc_cxml)), parent_) assert cell.width == expected_value @pytest.mark.parametrize( ("tc_cxml", "new_value", "expected_cxml"), [ ("w:tc", Inches(1), "w:tc/w:tcPr/w:tcW{w:w=1440,w:type=dxa}"), ( "w:tc/w:tcPr/w:tcW{w:w=25%,w:type=pct}", Inches(2), "w:tc/w:tcPr/w:tcW{w:w=2880,w:type=dxa}", ), ], ) def it_can_change_its_width( self, tc_cxml: str, new_value: Length, expected_cxml: str, parent_: Mock ): cell = _Cell(cast(CT_Tc, element(tc_cxml)), parent_) cell.width = new_value assert cell.width == new_value assert cell._tc.xml == xml(expected_cxml) def it_provides_access_to_the_paragraphs_it_contains(self, parent_: Mock): cell = _Cell(cast(CT_Tc, element("w:tc/(w:p, w:p)")), parent_) paragraphs = cell.paragraphs # -- every w:p produces a Paragraph instance -- assert len(paragraphs) == 2 assert all(isinstance(p, Paragraph) for p in paragraphs) # -- the return value is iterable and indexable -- assert all(p is paragraphs[idx] for idx, p in enumerate(paragraphs)) @pytest.mark.parametrize( ("tc_cxml", "expected_table_count"), [ ("w:tc", 0), ("w:tc/w:tbl", 1), ("w:tc/(w:tbl,w:tbl)", 2), ("w:tc/(w:p,w:tbl)", 1), ("w:tc/(w:tbl,w:tbl,w:p)", 2), ], ) def it_provides_access_to_the_tables_it_contains( self, tc_cxml: str, expected_table_count: int, parent_: Mock ): cell = _Cell(cast(CT_Tc, element(tc_cxml)), parent_) tables = cell.tables # --- test len(), iterable, and indexed access assert len(tables) == expected_table_count assert all(isinstance(t, Table) for t in tables) assert all(t is tables[idx] for idx, t in enumerate(tables)) @pytest.mark.parametrize( ("tc_cxml", "expected_cxml"), [ ("w:tc", "w:tc/w:p"), ("w:tc/w:p", "w:tc/(w:p, w:p)"), ("w:tc/w:tbl", "w:tc/(w:tbl, w:p)"), ], ) def it_can_add_a_paragraph(self, tc_cxml: str, expected_cxml: str, parent_: Mock): cell = _Cell(cast(CT_Tc, element(tc_cxml)), parent_) p = cell.add_paragraph() assert isinstance(p, Paragraph) assert cell._tc.xml == xml(expected_cxml) def it_can_add_a_table(self, parent_: Mock): cell = _Cell(cast(CT_Tc, element("w:tc/w:p")), parent_) table = cell.add_table(rows=2, cols=2) assert isinstance(table, Table) assert cell._element.xml == snippet_seq("new-tbl")[1] def it_can_merge_itself_with_other_cells( self, tc_: Mock, tc_2_: Mock, parent_: Mock, merged_tc_: Mock ): cell, other_cell = _Cell(tc_, parent_), _Cell(tc_2_, parent_) tc_.merge.return_value = merged_tc_ merged_cell = cell.merge(other_cell) assert isinstance(merged_cell, _Cell) tc_.merge.assert_called_once_with(other_cell._tc) assert merged_cell._tc is merged_tc_ assert merged_cell._parent is cell._parent # fixtures ------------------------------------------------------- @pytest.fixture def merged_tc_(self, request: FixtureRequest): return instance_mock(request, CT_Tc) @pytest.fixture def parent_(self, request: FixtureRequest): return instance_mock(request, Table) @pytest.fixture def tc_(self, request: FixtureRequest): return instance_mock(request, CT_Tc) @pytest.fixture def tc_2_(self, request: FixtureRequest): return instance_mock(request, CT_Tc)
Describe_Cell
python
aio-libs__aiohttp
tests/test_web_exceptions.py
{ "start": 8877, "end": 10398 }
class ____: async def test_ctor(self) -> None: resp = web.HTTPMethodNotAllowed( "GET", ["POST", "PUT"], headers={"X-Custom": "value"}, reason="Unsupported", text="text", content_type="custom", ) assert resp.method == "GET" assert resp.allowed_methods == {"POST", "PUT"} assert resp.text == "text" compare: Mapping[str, str] = { "X-Custom": "value", "Content-Type": "custom", "Allow": "POST,PUT", } assert resp.headers == compare assert resp.reason == "Unsupported" assert resp.status == 405 def test_pickle(self) -> None: resp = web.HTTPMethodNotAllowed( method="GET", allowed_methods=("POST", "PUT"), headers={"X-Custom": "value"}, reason="Unsupported", text="text", content_type="custom", ) resp.foo = "bar" # type: ignore[attr-defined] for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): pickled = pickle.dumps(resp, proto) resp2 = pickle.loads(pickled) assert resp2.method == "GET" assert resp2.allowed_methods == {"POST", "PUT"} assert resp2.text == "text" assert resp2.headers == resp.headers assert resp2.reason == "Unsupported" assert resp2.status == 405 assert resp2.foo == "bar"
TestHTTPMethodNotAllowed
python
ray-project__ray
python/ray/serve/_private/utils.py
{ "start": 2093, "end": 2130 }
class ____(Enum): VALUE = 1
DEFAULT
python
django__django
tests/gis_tests/geo3d/models.py
{ "start": 1187, "end": 1258 }
class ____(SimpleModel): point = models.PointField(null=True)
Point2D
python
doocs__leetcode
solution/rating.py
{ "start": 90, "end": 6618 }
class ____: def __init__(self, region='CN', retry=3): self.retry = retry self.region = region if region == 'CN': self.url = 'https://leetcode.cn/graphql' self.page_query = Template( "{\n localRankingV2(page:$page) {\nmyRank {\nattendedContestCount\n" "currentRatingRanking\ndataRegion\nisDeleted\nuser {\nrealName\n" "userAvatar\nuserSlug\n__typename\n}\n__typename\n}\npage\ntotalUsers\n" "userPerPage\nrankingNodes {\nattendedContestCount\ncurrentRatingRanking\n" "dataRegion\nisDeleted\nuser {\nrealName\nuserAvatar\nuserSlug\n__typename\n}\n__" "typename\n}\n__typename\n }\n}\n" ) else: self.url = 'https://leetcode.com/graphql' self.page_query = Template( "{\nglobalRanking(page:$page){\ntotalUsers\nuserPerPage\nmyRank{\nranking\n" "currentGlobalRanking\ncurrentRating\ndataRegion\nuser{\nnameColor\nactiveBadge{\n" "displayName\nicon\n__typename\n}\n__typename\n}\n__typename\n}\nrankingNodes{\n" "ranking\ncurrentRating\ncurrentGlobalRanking\ndataRegion\nuser{\nusername\nnameColor\n" "activeBadge{\ndisplayName\nicon\n__typename\n}\nprofile{\nuserAvatar\ncountryCode\n" "countryName\nrealName\n__typename\n}\n__typename\n}\n__typename\n}\n__typename\n}\n}\n" ) def load_page(self, page): query = self.page_query.substitute(page=page) for _ in range(self.retry): resp = requests.post(url=self.url, json={'query': query}, verify=False) if resp.status_code != 200: continue nodes = resp.json()['data'][ 'localRankingV2' if self.region == 'CN' else 'globalRanking' ]['rankingNodes'] if self.region == 'CN': return [ (int(v['currentRatingRanking']), v['user']['userSlug']) for v in nodes ] else: return [ (int(v['currentGlobalRanking']), v['user']['username']) for v in nodes ] return [] def _user_ranking(self, region, uid): if region == 'CN': key = 'userSlug' url = 'https://leetcode.cn/graphql/noj-go/' query = ( "\nquery userContestRankingInfo($userSlug:String!){\nuserContestRanking" "(userSlug:$userSlug){\nattendedContestsCount\nrating\nglobalRanking\nlocalRanking\n" "globalTotalParticipants\nlocalTotalParticipants\ntopPercentage\n}\n" "userContestRankingHistory(userSlug:$userSlug){\nattended\ntotalProblems\n" "trendingDirection\nfinishTimeInSeconds\nrating\nscore\nranking\ncontest{\n" "title\ntitleCn\nstartTime\n}\n}\n}\n" ) else: key = 'username' url = 'https://leetcode.com/graphql' query = ( "\nquery userContestRankingInfo($username:String!){\nuserContestRanking" "(username:$username){\nattendedContestsCount\nrating\nglobalRanking\n" "totalParticipants\ntopPercentage\nbadge{\nname\n}\n}\nuserContestRankingHistory" "(username:$username){\nattended\ntrendDirection\nproblemsSolved\n" "totalProblems\nfinishTimeInSeconds\nrating\nranking\ncontest{\n" "title\nstartTime\n}\n}\n}\n " ) variables = {key: uid} for _ in range(self.retry): resp = requests.post( url=url, json={'query': query, 'variables': variables}, verify=False ) if resp.status_code != 200: continue res = resp.json() if 'errors' in res: break ranking = res['data']['userContestRanking'] if ranking and 'rating' in ranking: score = float(ranking['rating']) if 'localRanking' in ranking: return int(ranking['localRanking']), score if 'globalRanking' in ranking: return int(ranking['globalRanking']), score return None, None def get_user_ranking(self, uid): for region in ['CN', 'US']: # 美国站会有国服用户,这里最多需要查询两次 ranking, score = self._user_ranking(region, uid) if score is not None: return ranking, score return None def get_1600_count(self): left, right = 1, 4000 while left < right: mid = (left + right + 1) >> 1 page = self.load_page(mid) print(f'第 {mid} 页:', page) if not page: return 0 ranking, score = self.get_user_ranking(page[0][1]) if score >= 1600: left = mid else: right = mid - 1 page = [uid for _, uid in self.load_page(left) if uid] print('校准中...') left, right = 0, len(page) - 1 while left < right: mid = (left + right + 1) >> 1 ranking, score = self.get_user_ranking(page[mid]) if score >= 1600: left = mid else: right = mid - 1 return self.get_user_ranking(page[left])[0] def get_user(self, rank): p = (rank - 1) // 25 + 1 offset = (rank - 1) % 25 page = self.load_page(p) _, score = self.get_user_ranking(page[offset][1]) return score, page[offset][1] def fetch_ranking_data(self): total = self.get_1600_count() if not total: return print(f'[{self.region}] 1600 分以上共计 {total} 人') guardian = int(total * 0.05) knight = int(total * 0.25) g_first, g_last = self.get_user(1), self.get_user(guardian) print( f'Guardian(top 5%): 共 {guardian} 名,守门员 {g_last[0]} 分(uid: {g_last[1]}),最高 {g_first[0]} 分(uid: {g_first[1]})' ) k_first, k_last = self.get_user(guardian + 1), self.get_user(knight) print( f'Knight(top 25%): 共 {knight} 名,守门员 {k_last[0]} 分(uid: {k_last[1]}),最高 {k_first[0]} 分(uid: {k_first[1]})' ) # 国服竞赛排名 lk = Ranking(region='CN') lk.fetch_ranking_data() print('\n------------------------------\n') # 全球竞赛排名 gk = Ranking(region='US') gk.fetch_ranking_data()
Ranking
python
ray-project__ray
python/ray/serve/tests/unit/test_deployment_state.py
{ "start": 13251, "end": 13743 }
class ____: """Fakes the DeploymentReplica class.""" def __init__(self, version: DeploymentVersion): self._version = version @property def version(self): return self._version def update_state(self, state): pass def replica(version: Optional[DeploymentVersion] = None) -> FakeDeploymentReplica: version = version or DeploymentVersion(get_random_string(), DeploymentConfig(), {}) return FakeDeploymentReplica(version)
FakeDeploymentReplica
python
python-markdown__markdown
tests/test_syntax/inline/test_code.py
{ "start": 781, "end": 2324 }
class ____(TestCase): def test_code_comments(self): self.assertMarkdownRenders( self.dedent( """ Some code `<!--` that is not HTML `-->` in a paragraph. Some code `<!--` that is not HTML `-->` in a paragraph. """ ), self.dedent( """ <p>Some code <code>&lt;!--</code> that is not HTML <code>--&gt;</code> in a paragraph.</p> <p>Some code <code>&lt;!--</code> that is not HTML <code>--&gt;</code> in a paragraph.</p> """ ) ) def test_code_html(self): self.assertMarkdownRenders( self.dedent( """ <p>html</p> Paragraph with code: `<p>test</p>`. """ ), self.dedent( """ <p>html</p> <p>Paragraph with code: <code>&lt;p&gt;test&lt;/p&gt;</code>.</p> """ ) ) def test_noname_tag(self): # Browsers ignore `</>`, but a Markdown parser should not, and should treat it as data # but not a tag. self.assertMarkdownRenders( self.dedent( """ `</>` """ ), self.dedent( """ <p><code>&lt;/&gt;</code></p> """ ) )
TestCode
python
facebook__pyre-check
client/commands/tests/pyre_server_options_test.py
{ "start": 454, "end": 940 }
class ____(frontend_configuration.OpenSource): def __init__(self) -> None: self.configuration = configuration_module.Configuration( global_root=Path("test"), targets=[], relative_local_root="local", ) def get_server_start_command( self, download_if_needed: bool ) -> frontend_configuration.ServerStartCommand: return frontend_configuration.DefaultServerStartCommand("/fake/binary")
FakeFrontendConfiguration
python
django__django
tests/queries/models.py
{ "start": 18418, "end": 18586 }
class ____(models.Model): json_field = models.JSONField(blank=True, null=True) class Meta: required_db_features = {"supports_json_field"}
JSONFieldNullable
python
cherrypy__cherrypy
cherrypy/tutorial/tut05_derived_objects.py
{ "start": 1867, "end": 2605 }
class ____(Page): """Another page app.""" title = 'Another Page' @cherrypy.expose def index(self): """Produce HTTP response body of another page app index URI.""" return ( self.header() + """ <p> And this is the amazing second page! </p> """ + self.footer() ) tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf') if __name__ == '__main__': # CherryPy always starts with app.root when trying to map request URIs # to objects, so we need to mount a request handler root. A request # to '/' will be mapped to HelloWorld().index(). cherrypy.quickstart(HomePage(), config=tutconf)
AnotherPage
python
ray-project__ray
python/ray/serve/tests/test_telemetry_1.py
{ "start": 3150, "end": 6176 }
class ____: pass stub_app = Stub.bind() @pytest.mark.skipif(sys.platform == "win32", reason="File path incorrect on Windows.") def test_rest_api(manage_ray_with_telemetry, tmp_dir): """ Check that telemetry works with REST API. """ storage = manage_ray_with_telemetry # Check that REST API telemetry is not set check_telemetry(ServeUsageTag.REST_API_VERSION, expected=None) config = { "applications": [ { "name": "stub_app", "import_path": "ray.serve.tests.test_telemetry_1.stub_app", "route_prefix": "/stub", }, ] } config_file_path = f"{tmp_dir}/config.yaml" with open(config_file_path, "w+") as f: yaml.safe_dump(config, f) subprocess.check_output(["serve", "deploy", config_file_path]) client = _get_global_client() # Make sure the applications are RUNNING. wait_for_condition(check_apps_running, apps=["stub_app"], timeout=15) current_num_reports = ray.get(storage.get_reports_received.remote()) wait_for_condition( lambda: ray.get(storage.get_reports_received.remote()) > current_num_reports, timeout=5, ) report = ray.get(storage.get_report.remote()) # Check all telemetry relevant to the Serve apps on this cluster assert ServeUsageTag.REST_API_VERSION.get_value_from_report(report) == "v2" assert ServeUsageTag.API_VERSION.get_value_from_report(report) == "v2" assert int(ServeUsageTag.NUM_GPU_DEPLOYMENTS.get_value_from_report(report)) == 0 # Assert num of deployments from controller. assert len(client.get_all_deployment_statuses()) == 2 assert int(ServeUsageTag.NUM_APPS.get_value_from_report(report)) == 2 assert int(ServeUsageTag.NUM_DEPLOYMENTS.get_value_from_report(report)) == 2 # Check that Serve telemetry not relevant to the running apps is omitted assert ServeUsageTag.FASTAPI_USED.get_value_from_report(report) is None assert ServeUsageTag.GRPC_INGRESS_USED.get_value_from_report(report) is None assert ServeUsageTag.HTTP_ADAPTER_USED.get_value_from_report(report) is None assert ServeUsageTag.DAG_DRIVER_USED.get_value_from_report(report) is None assert ServeUsageTag.AUTO_NUM_REPLICAS_USED.get_value_from_report(report) is None # Check that app deletions are tracked. new_config = {"applications": []} with open(config_file_path, "w+") as f: yaml.safe_dump(new_config, f) subprocess.check_output(["serve", "deploy", config_file_path]) wait_for_condition( lambda: int( ServeUsageTag.NUM_APPS.get_value_from_report( ray.get(storage.get_report.remote()) ) ) == 1, timeout=15, ) report = ray.get(storage.get_report.remote()) assert int(ServeUsageTag.NUM_APPS.get_value_from_report(report)) == 1 assert int(ServeUsageTag.NUM_DEPLOYMENTS.get_value_from_report(report)) == 1 @serve.deployment(ray_actor_options={"num_cpus": 0})
Stub
python
kamyu104__LeetCode-Solutions
Python/increasing-triplet-subsequence.py
{ "start": 45, "end": 532 }
class ____(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ min_num, a, b = float("inf"), float("inf"), float("inf") for c in nums: if min_num >= c: min_num = c elif b >= c: a, b = min_num, c else: # a < b < c return True return False # Time: O(n * logk) # Space: O(k) # Generalization of k-uplet.
Solution
python
neetcode-gh__leetcode
python/0090-subsets-ii.py
{ "start": 0, "end": 614 }
class ____: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: res = [] nums.sort() def backtrack(i, subset): if i == len(nums): res.append(subset[::]) return # All subsets that include nums[i] subset.append(nums[i]) backtrack(i + 1, subset) subset.pop() # All subsets that don't include nums[i] while i + 1 < len(nums) and nums[i] == nums[i + 1]: i += 1 backtrack(i + 1, subset) backtrack(0, []) return res
Solution
python
tensorflow__tensorflow
tensorflow/tools/docs/generate2_test.py
{ "start": 1948, "end": 3204 }
class ____(googletest.TestCase): @mock.patch.object(generate2, 'tf', fake_tf) def test_end_to_end(self): generate2.MIN_NUM_FILES_EXPECTED = 1 output_dir = pathlib.Path(googletest.GetTempDir())/'output' if os.path.exists(output_dir): shutil.rmtree(output_dir) os.makedirs(output_dir) generate2.build_docs( output_dir=output_dir, code_url_prefix='', search_hints=True, ) raw_ops_page = (output_dir/'tf/raw_ops.md').read_text() self.assertIn('/tf/raw_ops/Add.md', raw_ops_page) toc = yaml.safe_load((output_dir / 'tf/_toc.yaml').read_text()) self.assertEqual({ 'title': 'Overview', 'path': '/tf_overview' }, toc['toc'][0]['section'][0]) redirects = yaml.safe_load((output_dir / 'tf/_redirects.yaml').read_text()) self.assertIn({'from': '/tf_overview', 'to': '/tf'}, redirects['redirects']) if version.parse(fake_tf.__version__) >= version.parse('2.14'): self.assertIn( '<a id=Add href="/tf/raw_ops/Add.md">Add</a> | ✔️ | ✔️ |', raw_ops_page ) self.assertIn( '<a id=Print href="/tf/raw_ops/Print.md">Print</a> | ✔️ | ❌ |', raw_ops_page, ) if __name__ == '__main__': googletest.main()
Generate2Test
python
PrefectHQ__prefect
tests/server/orchestration/api/test_block_types.py
{ "start": 17794, "end": 20633 }
class ____: async def test_install_system_block_types(self, client): response = await client.post("/block_types/filter") block_types = parse_obj_as(List[BlockType], response.json()) assert len(block_types) == 0 r = await client.post("/block_types/install_system_block_types") assert r.status_code == status.HTTP_200_OK response = await client.post("/block_types/filter") block_types = parse_obj_as(List[BlockType], response.json()) assert len(block_types) > 0 async def test_install_system_block_types_multiple_times(self, client): response = await client.post("/block_types/filter") block_types = parse_obj_as(List[BlockType], response.json()) assert len(block_types) == 0 await client.post("/block_types/install_system_block_types") await client.post("/block_types/install_system_block_types") await client.post("/block_types/install_system_block_types") async def test_create_system_block_type( self, hosted_api_client, session, ignore_prefect_deprecation_warnings ): # install system blocks await hosted_api_client.post("/block_types/install_system_block_types") # create a datetime block secret_block_type = await hosted_api_client.get("/block_types/slug/secret") secret_block_schema = await hosted_api_client.post( "/block_schemas/filter", json=dict( block_schemas=dict( block_type_id=dict(any_=[secret_block_type.json()["id"]]) ), limit=1, ), ) block = prefect.blocks.system.Secret(value="sk-1234567890") response = await hosted_api_client.post( "/block_documents/", json=block._to_block_document( name="my-test-secret", block_type_id=secret_block_type.json()["id"], block_schema_id=secret_block_schema.json()[0]["id"], ).model_dump( mode="json", exclude_unset=True, exclude={"id", "block_schema", "block_type", "block_type_name"}, context={"include_secrets": True}, ), ) assert response.status_code == status.HTTP_201_CREATED, response.text # load the secret block api_block = await prefect.blocks.system.Secret.load("my-test-secret") assert api_block.get() == "sk-1234567890" async def test_system_block_types_are_protected(self, client, session): # install system blocks await client.post("/block_types/install_system_block_types") # read date-time system block response = await client.get("/block_types/slug/secret") assert response.json()["is_protected"]
TestSystemBlockTypes
python
huggingface__transformers
src/transformers/models/depth_anything/modeling_depth_anything.py
{ "start": 4936, "end": 6318 }
class ____(nn.Module): """Feature fusion layer, merges feature maps from different stages. Args: config (`[DepthAnythingConfig]`): Model configuration class defining the model architecture. """ def __init__(self, config): super().__init__() self.projection = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=1, bias=True) self.residual_layer1 = DepthAnythingPreActResidualLayer(config) self.residual_layer2 = DepthAnythingPreActResidualLayer(config) def forward(self, hidden_state, residual=None, size=None): if residual is not None: if hidden_state.shape != residual.shape: residual = nn.functional.interpolate( residual, size=(hidden_state.shape[2], hidden_state.shape[3]), mode="bilinear", align_corners=False ) hidden_state = hidden_state + self.residual_layer1(residual) hidden_state = self.residual_layer2(hidden_state) modifier = {"scale_factor": 2} if size is None else {"size": size} hidden_state = nn.functional.interpolate( hidden_state, **modifier, mode="bilinear", align_corners=True, ) hidden_state = self.projection(hidden_state) return hidden_state
DepthAnythingFeatureFusionLayer
python
pytorch__pytorch
torch/_dynamo/guards.py
{ "start": 36049, "end": 36114 }
class ____: code_list: list[str] guard: Guard
GuardCodeList
python
kamyu104__LeetCode-Solutions
Python/guess-the-word.py
{ "start": 67, "end": 708 }
class ____(object): def findSecretWord(self, wordlist, master): """ :type wordlist: List[Str] :type master: Master :rtype: None """ possible = range(len(wordlist)) n = 0 while n < 6: count = [collections.Counter(w[i] for w in wordlist) for i in xrange(6)] guess = max(possible, key=lambda x: sum(count[i][c] for i, c in enumerate(wordlist[x]))) n = master.guess(wordlist[guess]) possible = [j for j in possible if sum(a == b for a, b in itertools.izip(wordlist[guess], wordlist[j])) == n] # Time: O(n^2) # Space: O(n)
Solution
python
getsentry__sentry
src/sentry/search/events/types.py
{ "start": 2544, "end": 2752 }
class ____(TypedDict): data: SnubaData meta: EventsMeta SAMPLING_MODES = Literal[ "BEST_EFFORT", "PREFLIGHT", "NORMAL", "HIGHEST_ACCURACY", "HIGHEST_ACCURACY_FLEX_TIME" ] @dataclass
EventsResponse
python
django__django
tests/admin_views/admin.py
{ "start": 24125, "end": 24290 }
class ____(admin.ModelAdmin): list_display = ["id", "name"] list_display_links = ["id"] list_editable = ["name"] list_per_page = 2
UnorderedObjectAdmin
python
PrefectHQ__prefect
src/prefect/blocks/abstract.py
{ "start": 4917, "end": 6085 }
class ____(Block, ABC, Generic[T]): """ Block that represents an entity in an external service that can trigger a long running execution. """ @property def logger(self) -> LoggerOrAdapter: """ Returns a logger based on whether the JobBlock is called from within a flow or task run context. If a run context is present, the logger property returns a run logger. Else, it returns a default logger labeled with the class's name. Returns: The run logger or a default logger with the class's name. """ try: return get_run_logger() except MissingContextError: return get_logger(self.__class__.__name__) @abstractmethod async def trigger(self) -> JobRun[T]: """ Triggers a job run in an external service and returns a JobRun object to track the execution of the run. """ # TODO: This interface is heavily influenced by # [PEP 249](https://peps.python.org/pep-0249/) # Primarily intended for use with relational databases. # A separate interface may be necessary for # non relational databases.
JobBlock
python
pyca__cryptography
src/cryptography/hazmat/primitives/ciphers/algorithms.py
{ "start": 2697, "end": 3229 }
class ____(CipherAlgorithm): name = "ChaCha20" key_sizes = frozenset([256]) def __init__(self, key: utils.Buffer, nonce: utils.Buffer): self.key = _verify_key_size(self, key) utils._check_byteslike("nonce", nonce) if len(nonce) != 16: raise ValueError("nonce must be 128-bits (16 bytes)") self._nonce = nonce @property def nonce(self) -> utils.Buffer: return self._nonce @property def key_size(self) -> int: return len(self.key) * 8
ChaCha20
python
doocs__leetcode
solution/2600-2699/2657.Find the Prefix Common Array of Two Arrays/Solution3.py
{ "start": 0, "end": 274 }
class ____: def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]: ans = [] x = y = 0 for a, b in zip(A, B): x |= 1 << a y |= 1 << b ans.append((x & y).bit_count()) return ans
Solution
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/model_query_transitive_extends.py
{ "start": 737, "end": 807 }
class ____(Test2_C1): def foo(self, attribute): ...
Test2_C2
python
fluentpython__example-code
21-class-metaprog/evaltime.py
{ "start": 75, "end": 402 }
class ____(): print('<[2]> ClassOne body') def __init__(self): print('<[3]> ClassOne.__init__') def __del__(self): print('<[4]> ClassOne.__del__') def method_x(self): print('<[5]> ClassOne.method_x') class ClassTwo(object): print('<[6]> ClassTwo body') @deco_alpha
ClassOne
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 10928, "end": 11289 }
class ____(BiffRecord): """ This record is part of the worksheet/workbook protection. It specifies whether a worksheet or a workbook is protected against modification. Protection is not active, if this record is omitted. """ _REC_ID = 0x0012 def __init__(self, protect): self._rec_data = pack('<H', protect)
ProtectRecord
python
google__jax
jax/_src/core.py
{ "start": 17159, "end": 18308 }
class ____: __slots__ = ["count", "aval", "initial_qdd", "final_qdd"] count: int aval: AbstractValue # these are only useful for jaxpr binders but rather than create a separate # type for those, breaking existing interpreters, we add fields here. initial_qdd : QuasiDynamicData | None final_qdd : QuasiDynamicData | None def __init__(self, aval: AbstractValue, initial_qdd=None, final_qdd=None): assert isinstance(aval, AbstractValue), aval self.count = next(_var_counter) self.aval = aval self.initial_qdd = initial_qdd self.final_qdd = final_qdd def __repr__(self): return f'Var(id={id(self)}):{self.aval.str_short()}' def pretty_print(self, context: JaxprPpContext, *, print_dtype: bool = True): del print_dtype # unused return f"{context.var_names[self]}" gensym = lambda: Var # In a jaxpr, `dropvar` can appear in place of a bound variable to indicate that # the assignment is dropped, i.e. that an expression's output value will never # be read. In that sense, `dropvar` is not a variable, but it is convenient to # treat it as a special case of one. Its `aval` is similarly inexact.
Var
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 43080, "end": 43750 }
class ____(PipesContextLoader): """Context loader that reads context from a JSON file on GCS. Args: client (google.cloud.storage.Client): A google.cloud.storage.Client object. """ def __init__(self, client: "GCSClient"): self._client = client @contextmanager def load_context(self, params: PipesParams) -> Iterator[PipesContextData]: bucket = _assert_env_param_type(params, "bucket", str, self.__class__) key = _assert_env_param_type(params, "key", str, self.__class__) obj = self._client.get_bucket(bucket).blob(key).download_as_bytes() yield json.loads(obj.decode("utf-8"))
PipesGCSContextLoader
python
ansible__ansible
test/integration/targets/ansible-test-container/runme.py
{ "start": 25757, "end": 26318 }
class ____(ApplicationError): """An error from executing a subprocess.""" def __init__(self, result: SubprocessResult) -> None: self.result = result message = f'Command `{shlex.join(result.command)}` exited with status: {result.status}' stdout = (result.stdout or '').strip() stderr = (result.stderr or '').strip() if stdout: message += f'\n>>> Standard Output\n{stdout}' if stderr: message += f'\n>>> Standard Error\n{stderr}' super().__init__(message)
SubprocessError
python
patrick-kidger__equinox
equinox/_module/_module.py
{ "start": 3743, "end": 4598 }
class ____(eqx.Module): vmap_linear: Callable def __init__(self, ...): self.vmap_linear = eqx.filter_vmap(eqx.nn.Linear(...)) def __call__(self, ...): ... = self.vmap_linear(...) ``` """ def _warn_jax_transformed_function(cls: "_ModuleMeta", x: object) -> None: # not `isinstance`, just in case JAX every tries to override `__instancecheck__`. if type(x) in _transform_types: while True: try: x = getattr(x, "__wrapped__") except AttributeError: break try: jtu.tree_map(_is_array_like, x) except _JaxTransformException: warnings.warn( _MSG_JAX_XFM_FUNC.format(cls.__module__, cls.__qualname__), stacklevel=3, ) break
MyModule
python
pytorch__pytorch
tools/code_coverage/package/tool/parser/coverage_record.py
{ "start": 73, "end": 409 }
class ____(NamedTuple): filepath: str covered_lines: list[int] uncovered_lines: list[int] | None = None def to_dict(self) -> dict[str, Any]: return { "filepath": self.filepath, "covered_lines": self.covered_lines, "uncovered_lines": self.uncovered_lines, }
CoverageRecord
python
scrapy__scrapy
tests/test_addons.py
{ "start": 1541, "end": 7307 }
class ____: def test_load_settings(self): settings_dict = { "ADDONS": {"tests.test_addons.SimpleAddon": 0}, } crawler = get_crawler(settings_dict=settings_dict) manager = crawler.addons assert isinstance(manager.addons[0], SimpleAddon) def test_notconfigured(self): class NotConfiguredAddon: def update_settings(self, settings): raise NotConfigured settings_dict = { "ADDONS": {NotConfiguredAddon: 0}, } crawler = get_crawler(settings_dict=settings_dict) manager = crawler.addons assert not manager.addons def test_load_settings_order(self): # Get three addons with different settings addonlist = [] for i in range(3): addon = get_addon_cls({"KEY1": i}) addon.number = i addonlist.append(addon) # Test for every possible ordering for ordered_addons in itertools.permutations(addonlist): expected_order = [a.number for a in ordered_addons] settings = {"ADDONS": {a: i for i, a in enumerate(ordered_addons)}} crawler = get_crawler(settings_dict=settings) manager = crawler.addons assert [a.number for a in manager.addons] == expected_order assert crawler.settings.getint("KEY1") == expected_order[-1] def test_build_from_crawler(self): settings_dict = { "ADDONS": {"tests.test_addons.CreateInstanceAddon": 0}, "MYADDON": {"MYADDON_KEY": "val"}, } crawler = get_crawler(settings_dict=settings_dict) manager = crawler.addons assert isinstance(manager.addons[0], CreateInstanceAddon) assert crawler.settings.get("MYADDON_KEY") == "val" def test_settings_priority(self): config = { "KEY": 15, # priority=addon } settings_dict = { "ADDONS": {get_addon_cls(config): 1}, **get_reactor_settings(), } crawler = get_crawler(settings_dict=settings_dict) assert crawler.settings.getint("KEY") == 15 settings = Settings(settings_dict) settings.set("KEY", 0, priority="default") runner = CrawlerRunner(settings) crawler = runner.create_crawler(Spider) crawler._apply_settings() assert crawler.settings.getint("KEY") == 15 settings_dict = { "KEY": 20, # priority=project "ADDONS": {get_addon_cls(config): 1}, **get_reactor_settings(), } settings = Settings(settings_dict) settings.set("KEY", 0, priority="default") runner = CrawlerRunner(settings) crawler = runner.create_crawler(Spider) assert crawler.settings.getint("KEY") == 20 def test_fallback_workflow(self): FALLBACK_SETTING = "MY_FALLBACK_DOWNLOAD_HANDLER" class AddonWithFallback: def update_settings(self, settings): if not settings.get(FALLBACK_SETTING): settings.set( FALLBACK_SETTING, settings.getwithbase("DOWNLOAD_HANDLERS")["https"], "addon", ) settings["DOWNLOAD_HANDLERS"]["https"] = "AddonHandler" settings_dict = { "ADDONS": {AddonWithFallback: 1}, } crawler = get_crawler(settings_dict=settings_dict) assert ( crawler.settings.getwithbase("DOWNLOAD_HANDLERS")["https"] == "AddonHandler" ) assert ( crawler.settings.get(FALLBACK_SETTING) == "scrapy.core.downloader.handlers.http11.HTTP11DownloadHandler" ) settings_dict = { "ADDONS": {AddonWithFallback: 1}, "DOWNLOAD_HANDLERS": {"https": "UserHandler"}, } crawler = get_crawler(settings_dict=settings_dict) assert ( crawler.settings.getwithbase("DOWNLOAD_HANDLERS")["https"] == "AddonHandler" ) assert crawler.settings.get(FALLBACK_SETTING) == "UserHandler" def test_logging_message(self): class LoggedAddon: def update_settings(self, settings): pass with ( patch("scrapy.addons.logger") as logger_mock, patch("scrapy.addons.build_from_crawler") as build_from_crawler_mock, ): settings_dict = { "ADDONS": {LoggedAddon: 1}, } addon = LoggedAddon() build_from_crawler_mock.return_value = addon crawler = get_crawler(settings_dict=settings_dict) logger_mock.info.assert_called_once_with( "Enabled addons:\n%(addons)s", {"addons": [addon]}, extra={"crawler": crawler}, ) @inlineCallbacks def test_enable_addon_in_spider(self): class MySpider(Spider): name = "myspider" @classmethod def from_crawler(cls, crawler, *args, **kwargs): spider = super().from_crawler(crawler, *args, **kwargs) addon_config = {"KEY": "addon"} addon_cls = get_addon_cls(addon_config) spider.settings.set("ADDONS", {addon_cls: 1}, priority="spider") return spider settings = Settings() settings.setdict(get_reactor_settings()) settings.set("KEY", "default", priority="default") runner = CrawlerRunner(settings) crawler = runner.create_crawler(MySpider) assert crawler.settings.get("KEY") == "default" yield crawler.crawl() assert crawler.settings.get("KEY") == "addon"
TestAddonManager
python
python__mypy
mypy/nodes.py
{ "start": 52487, "end": 52873 }
class ____(Statement): """An expression as a statement, such as print(s).""" __slots__ = ("expr",) __match_args__ = ("expr",) expr: Expression def __init__(self, expr: Expression) -> None: super().__init__() self.expr = expr def accept(self, visitor: StatementVisitor[T]) -> T: return visitor.visit_expression_stmt(self)
ExpressionStmt
python
walkccc__LeetCode
solutions/2585. Number of Ways to Earn Points/2585-2.py
{ "start": 0, "end": 456 }
class ____: def waysToReachTarget(self, target: int, types: list[list[int]]) -> int: MOD = 1_000_000_007 # dp[j] := the number of ways to earn j points with the types so far dp = [1] + [0] * target for count, mark in types: for j in range(target, -1, -1): for solved in range(1, count + 1): if j - solved * mark >= 0: dp[j] += dp[j - solved * mark] dp[j] %= MOD return dp[target]
Solution
python
GoogleCloudPlatform__python-docs-samples
firestore/cloud-client/snippets.py
{ "start": 3066, "end": 32749 }
class ____: def __init__(self, name, state, country, capital=False, population=0, regions=[]): self.name = name self.state = state self.country = country self.capital = capital self.population = population self.regions = regions @staticmethod def from_dict(source): # [START_EXCLUDE] city = City(source["name"], source["state"], source["country"]) if "capital" in source: city.capital = source["capital"] if "population" in source: city.population = source["population"] if "regions" in source: city.regions = source["regions"] return city # [END_EXCLUDE] def to_dict(self): # [START_EXCLUDE] dest = {"name": self.name, "state": self.state, "country": self.country} if self.capital: dest["capital"] = self.capital if self.population: dest["population"] = self.population if self.regions: dest["regions"] = self.regions return dest # [END_EXCLUDE] def __repr__(self): return f"City(\ name={self.name}, \ country={self.country}, \ population={self.population}, \ capital={self.capital}, \ regions={self.regions}\ )" # [END firestore_data_custom_type_definition] def add_example_data(): db = firestore.Client() # [START firestore_data_get_dataset] cities_ref = db.collection("cities") cities_ref.document("BJ").set( City("Beijing", None, "China", True, 21500000, ["hebei"]).to_dict() ) cities_ref.document("SF").set( City( "San Francisco", "CA", "USA", False, 860000, ["west_coast", "norcal"] ).to_dict() ) cities_ref.document("LA").set( City( "Los Angeles", "CA", "USA", False, 3900000, ["west_coast", "socal"] ).to_dict() ) cities_ref.document("DC").set( City("Washington D.C.", None, "USA", True, 680000, ["east_coast"]).to_dict() ) cities_ref.document("TOK").set( City("Tokyo", None, "Japan", True, 9000000, ["kanto", "honshu"]).to_dict() ) # [END firestore_data_get_dataset] def add_custom_class_with_id(): db = firestore.Client() # [START firestore_data_set_from_custom_type] city = City(name="Los Angeles", state="CA", country="USA") db.collection("cities").document("LA").set(city.to_dict()) # [END firestore_data_set_from_custom_type] def add_data_with_id(): db = firestore.Client() data = {} # [START firestore_data_set_id_specified] db.collection("cities").document("new-city-id").set(data) # [END firestore_data_set_id_specified] def add_custom_class_generated_id(): db = firestore.Client() # [START firestore_data_set_id_random_collection] city = {"name": "Tokyo", "country": "Japan"} update_time, city_ref = db.collection("cities").add(city) print(f"Added document with id {city_ref.id}") # [END firestore_data_set_id_random_collection] def add_new_doc(): db = firestore.Client() # [START firestore_data_set_id_random_document_ref] new_city_ref = db.collection("cities").document() # later... new_city_ref.set( { # ... } ) # [END firestore_data_set_id_random_document_ref] def get_check_exists(): db = firestore.Client() # [START firestore_data_get_as_map] doc_ref = db.collection("cities").document("SF") doc = doc_ref.get() if doc.exists: print(f"Document data: {doc.to_dict()}") else: print("No such document!") # [END firestore_data_get_as_map] def get_custom_class(): db = firestore.Client() # [START firestore_data_get_as_custom_type] doc_ref = db.collection("cities").document("BJ") doc = doc_ref.get() city = City.from_dict(doc.to_dict()) print(city) # [END firestore_data_get_as_custom_type] def get_simple_query(): db = firestore.Client() # [START firestore_data_query] # Note: Use of CollectionRef stream() is prefered to get() docs = ( db.collection("cities") .where(filter=FieldFilter("capital", "==", True)) .stream() ) for doc in docs: print(f"{doc.id} => {doc.to_dict()}") # [END firestore_data_query] def array_contains_filter(): db = firestore.Client() # [START firestore_query_filter_array_contains] cities_ref = db.collection("cities") query = cities_ref.where( filter=FieldFilter("regions", "array_contains", "west_coast") ) # [END firestore_query_filter_array_contains] docs = query.stream() for doc in docs: print(f"{doc.id} => {doc.to_dict()}") def get_full_collection(): db = firestore.Client() # [START firestore_data_get_all_documents] docs = db.collection("cities").stream() for doc in docs: print(f"{doc.id} => {doc.to_dict()}") # [END firestore_data_get_all_documents] def structure_doc_ref(): db = firestore.Client() # [START firestore_data_reference_document] a_lovelace_ref = db.collection("users").document("alovelace") # [END firestore_data_reference_document] print(a_lovelace_ref) def structure_collection_ref(): db = firestore.Client() # [START firestore_data_reference_collection] users_ref = db.collection("users") # [END firestore_data_reference_collection] print(users_ref) def structure_doc_ref_alternate(): db = firestore.Client() # [START firestore_data_reference_document_path] a_lovelace_ref = db.document("users/alovelace") # [END firestore_data_reference_document_path] return a_lovelace_ref def structure_subcollection_ref(): db = firestore.Client() # [START firestore_data_reference_subcollection] room_a_ref = db.collection("rooms").document("roomA") message_ref = room_a_ref.collection("messages").document("message1") # [END firestore_data_reference_subcollection] print(message_ref) def update_doc(): db = firestore.Client() db.collection("cities").document("DC").set( City("Washington D.C.", None, "USA", True, 680000, ["east_coast"]).to_dict() ) # [START firestore_data_set_field] city_ref = db.collection("cities").document("DC") # Set the capital field city_ref.update({"capital": True}) # [END firestore_data_set_field] def update_doc_array(): db = firestore.Client() db.collection("cities").document("DC").set( City("Washington D.C.", None, "USA", True, 680000, ["east_coast"]).to_dict() ) # [START firestore_data_set_array_operations] city_ref = db.collection("cities").document("DC") # Atomically add a new region to the 'regions' array field. city_ref.update({"regions": firestore.ArrayUnion(["greater_virginia"])}) # // Atomically remove a region from the 'regions' array field. city_ref.update({"regions": firestore.ArrayRemove(["east_coast"])}) # [END firestore_data_set_array_operations] city = city_ref.get() print(f"Updated the regions field of the DC. {city.to_dict()}") def update_multiple(): db = firestore.Client() db.collection("cities").document("DC").set( City("Washington D.C.", None, "USA", True, 680000, ["east_coast"]).to_dict() ) # [START firestore_update_multiple] doc_ref = db.collection("cities").document("DC") doc_ref.update({"name": "Washington D.C.", "country": "USA", "capital": True}) # [END firestore_update_multiple] def update_create_if_missing(): db = firestore.Client() # [START firestore_data_set_doc_upsert] city_ref = db.collection("cities").document("BJ") city_ref.set({"capital": True}, merge=True) # [END firestore_data_set_doc_upsert] def update_nested(): db = firestore.Client() # [START firestore_data_set_nested_fields] # Create an initial document to update frank_ref = db.collection("users").document("frank") frank_ref.set( { "name": "Frank", "favorites": {"food": "Pizza", "color": "Blue", "subject": "Recess"}, "age": 12, } ) # Update age and favorite color frank_ref.update({"age": 13, "favorites.color": "Red"}) # [END firestore_data_set_nested_fields] def update_server_timestamp(): db = firestore.Client() # [START firestore_data_set_server_timestamp] city_ref = db.collection("objects").document("some-id") city_ref.update({"timestamp": firestore.SERVER_TIMESTAMP}) # [END firestore_data_set_server_timestamp] def update_data_transaction(): db = firestore.Client() # [START firestore_transaction_document_update] transaction = db.transaction() city_ref = db.collection("cities").document("SF") @firestore.transactional def update_in_transaction(transaction, city_ref): snapshot = city_ref.get(transaction=transaction) transaction.update(city_ref, {"population": snapshot.get("population") + 1}) update_in_transaction(transaction, city_ref) # [END firestore_transaction_document_update] def update_data_transaction_result(): db = firestore.Client() # [START firestore_transaction_document_update_conditional] transaction = db.transaction() city_ref = db.collection("cities").document("SF") @firestore.transactional def update_in_transaction(transaction, city_ref): snapshot = city_ref.get(transaction=transaction) new_population = snapshot.get("population") + 1 if new_population < 1000000: transaction.update(city_ref, {"population": new_population}) return True else: return False result = update_in_transaction(transaction, city_ref) if result: print("Population updated") else: print("Sorry! Population is too big.") # [END firestore_transaction_document_update_conditional] def update_data_batch(): db = firestore.Client() # [START firestore_data_batch_writes] batch = db.batch() # Set the data for NYC nyc_ref = db.collection("cities").document("NYC") batch.set(nyc_ref, {"name": "New York City"}) # Update the population for SF sf_ref = db.collection("cities").document("SF") batch.update(sf_ref, {"population": 1000000}) # Delete DEN den_ref = db.collection("cities").document("DEN") batch.delete(den_ref) # Commit the batch batch.commit() # [END firestore_data_batch_writes] def compound_query_example(): db = firestore.Client() # [START firestore_query_filter_eq_string] # Create a reference to the cities collection cities_ref = db.collection("cities") # Create a query against the collection query_ref = cities_ref.where(filter=FieldFilter("state", "==", "CA")) # [END firestore_query_filter_eq_string] return query_ref def compound_query_simple(): db = firestore.Client() # [START firestore_query_filter_eq_boolean] cities_ref = db.collection("cities") query = cities_ref.where(filter=FieldFilter("capital", "==", True)) # [END firestore_query_filter_eq_boolean] print(query) def compound_query_single_clause(): db = firestore.Client() # [START firestore_query_filter_single_examples] cities_ref = db.collection("cities") cities_ref.where(filter=FieldFilter("state", "==", "CA")) cities_ref.where(filter=FieldFilter("population", "<", 1000000)) cities_ref.where(filter=FieldFilter("name", ">=", "San Francisco")) # [END firestore_query_filter_single_examples] def compound_query_valid_multi_clause(): db = firestore.Client( add_unique_string=False ) # Flag for testing purposes, needs index to be precreated # [START firestore_query_filter_compound_multi_eq] cities_ref = db.collection("cities") denver_query = cities_ref.where(filter=FieldFilter("state", "==", "CO")).where( filter=FieldFilter("name", "==", "Denver") ) large_us_cities_query = cities_ref.where( filter=FieldFilter("state", "==", "CA") ).where(filter=FieldFilter("population", ">", 1000000)) # [END firestore_query_filter_compound_multi_eq] print(denver_query) print(large_us_cities_query) return denver_query, large_us_cities_query def compound_query_valid_single_field(): db = firestore.Client() # [START firestore_query_filter_range_valid] cities_ref = db.collection("cities") cities_ref.where(filter=FieldFilter("state", ">=", "CA")).where( filter=FieldFilter("state", "<=", "IN") ) # [END firestore_query_filter_range_valid] def compound_query_invalid_multi_field(): db = firestore.Client() # [START firestore_query_filter_range_invalid] cities_ref = db.collection("cities") cities_ref.where(filter=FieldFilter("state", ">=", "CA")).where( filter=FieldFilter("population", ">=", 1000000) ) # [END firestore_query_filter_range_invalid] def order_simple_limit(): db = firestore.Client() # [START firestore_order_simple_limit] query = db.collection("cities").order_by("name").limit(3).stream() # [END firestore_order_simple_limit] return query def order_simple_limit_desc(): db = firestore.Client() # [START firestore_query_order_desc_limit] cities_ref = db.collection("cities") query = cities_ref.order_by("name", direction=firestore.Query.DESCENDING).limit(3) results = query.stream() # [END firestore_query_order_desc_limit] print(results) return results def order_multiple(): db = firestore.Client( add_unique_string=False ) # Flag for testing purposes, needs index to be precreated # [START firestore_query_order_multi] cities_ref = db.collection("cities") ordered_city_ref = cities_ref.order_by("state").order_by( "population", direction=firestore.Query.DESCENDING ) # [END firestore_query_order_multi] return ordered_city_ref def order_where_limit(): db = firestore.Client() # [START firestore_query_order_limit_field_valid] cities_ref = db.collection("cities") query = ( cities_ref.where(filter=FieldFilter("population", ">", 2500000)) .order_by("population") .limit(2) ) results = query.stream() # [END firestore_query_order_limit_field_valid] print(results) return results def order_limit_to_last(): db = firestore.Client() # [START firestore_query_order_limit] cities_ref = db.collection("cities") query = cities_ref.order_by("name").limit_to_last(2) results = query.get() # [END firestore_query_order_limit] print(results) return results def order_where_valid(): db = firestore.Client() # [START firestore_query_order_with_filter] cities_ref = db.collection("cities") query = cities_ref.where(filter=FieldFilter("population", ">", 2500000)).order_by( "population" ) results = query.stream() # [END firestore_query_order_with_filter] print(results) return results def order_where_invalid(): db = firestore.Client( add_unique_string=False ) # Flag for testing purposes, needs index to be precreated # [START firestore_query_order_field_invalid] cities_ref = db.collection("cities") query = cities_ref.where(filter=FieldFilter("population", ">", 2500000)).order_by( "country" ) results = query.stream() # [END firestore_query_order_field_invalid] print(results) return results def cursor_simple_start_at(): db = firestore.Client() # [START firestore_query_cursor_start_at_field_value_single] cities_ref = db.collection("cities") query_start_at = cities_ref.order_by("population").start_at({"population": 1000000}) # [END firestore_query_cursor_start_at_field_value_single] return query_start_at def cursor_simple_end_at(): db = firestore.Client() # [START firestore_query_cursor_end_at_field_value_single] cities_ref = db.collection("cities") query_end_at = cities_ref.order_by("population").end_at({"population": 1000000}) # [END firestore_query_cursor_end_at_field_value_single] return query_end_at def snapshot_cursors(): db = firestore.Client() # [START firestore_query_cursor_start_at_document] doc_ref = db.collection("cities").document("SF") snapshot = doc_ref.get() start_at_snapshot = ( db.collection("cities").order_by("population").start_at(snapshot) ) # [END firestore_query_cursor_start_at_document] results = start_at_snapshot.limit(10).stream() return results def cursor_paginate(): db = firestore.Client() # [START firestore_query_cursor_pagination] cities_ref = db.collection("cities") first_query = cities_ref.order_by("population").limit(3) # Get the last document from the results docs = first_query.stream() last_doc = list(docs)[-1] # Construct a new query starting at this document # Note: this will not have the desired effect if # multiple cities have the exact same population value last_pop = last_doc.to_dict()["population"] next_query = ( cities_ref.order_by("population").start_after({"population": last_pop}).limit(3) ) # Use the query for pagination # ... # [END firestore_query_cursor_pagination] return next_query def listen_document(): db = firestore.Client() # [START firestore_listen_document] # Create an Event for notifying main thread. callback_done = threading.Event() # Create a callback on_snapshot function to capture changes def on_snapshot(doc_snapshot, changes, read_time): for doc in doc_snapshot: print(f"Received document snapshot: {doc.id}") callback_done.set() doc_ref = db.collection("cities").document("SF") # Watch the document doc_watch = doc_ref.on_snapshot(on_snapshot) # [END firestore_listen_document] # Creating document data = { "name": "San Francisco", "state": "CA", "country": "USA", "capital": False, "population": 860000, } doc_ref.set(data) # Wait for the callback. callback_done.wait(timeout=60) # [START firestore_listen_detach] # Terminate watch on a document doc_watch.unsubscribe() # [END firestore_listen_detach] def listen_multiple(): db = firestore.Client() # [START firestore_listen_query_snapshots] # Create an Event for notifying main thread. callback_done = threading.Event() # Create a callback on_snapshot function to capture changes def on_snapshot(col_snapshot, changes, read_time): print("Callback received query snapshot.") print("Current cities in California:") for doc in col_snapshot: print(f"{doc.id}") callback_done.set() col_query = db.collection("cities").where(filter=FieldFilter("state", "==", "CA")) # Watch the collection query query_watch = col_query.on_snapshot(on_snapshot) # [END firestore_listen_query_snapshots] # Creating document data = { "name": "San Francisco", "state": "CA", "country": "USA", "capital": False, "population": 860000, } db.collection("cities").document("SF").set(data) # Wait for the callback. callback_done.wait(timeout=60) query_watch.unsubscribe() def listen_for_changes(): db = firestore.Client() # [START firestore_listen_query_changes] # Create an Event for notifying main thread. delete_done = threading.Event() # Create a callback on_snapshot function to capture changes def on_snapshot(col_snapshot, changes, read_time): print("Callback received query snapshot.") print("Current cities in California: ") for change in changes: if change.type.name == "ADDED": print(f"New city: {change.document.id}") elif change.type.name == "MODIFIED": print(f"Modified city: {change.document.id}") elif change.type.name == "REMOVED": print(f"Removed city: {change.document.id}") delete_done.set() col_query = db.collection("cities").where(filter=FieldFilter("state", "==", "CA")) # Watch the collection query query_watch = col_query.on_snapshot(on_snapshot) # [END firestore_listen_query_changes] mtv_document = db.collection("cities").document("MTV") # Creating document mtv_document.set( { "name": "Mountain View", "state": "CA", "country": "USA", "capital": False, "population": 80000, } ) sleep(1) # Modifying document mtv_document.update( { "name": "Mountain View", "state": "CA", "country": "USA", "capital": False, "population": 90000, } ) sleep(1) # Delete document mtv_document.delete() # Wait for the callback captures the deletion. delete_done.wait(timeout=60) query_watch.unsubscribe() def cursor_multiple_conditions(): db = firestore.Client( add_unique_string=False ) # Flag for testing purposes, needs index to be precreated # [START firestore_query_cursor_start_at_field_value_multi] start_at_name = ( db.collection("cities").order_by("name").start_at({"name": "Springfield"}) ) start_at_name_and_state = ( db.collection("cities") .order_by("name") .order_by("state") .start_at({"name": "Springfield", "state": "Missouri"}) ) # [END firestore_query_cursor_start_at_field_value_multi] return start_at_name, start_at_name_and_state def delete_single_doc(): db = firestore.Client() # [START firestore_data_delete_doc] db.collection("cities").document("DC").delete() # [END firestore_data_delete_doc] def delete_field(): db = firestore.Client() # [START firestore_data_delete_field] city_ref = db.collection("cities").document("BJ") city_ref.update({"capital": firestore.DELETE_FIELD}) # [END firestore_data_delete_field] def delete_full_collection(): db = firestore.Client() # [START firestore_data_delete_collection] def delete_collection(coll_ref, batch_size): if batch_size == 0: return docs = coll_ref.list_documents(page_size=batch_size) deleted = 0 for doc in docs: print(f"Deleting doc {doc.id} => {doc.get().to_dict()}") doc.delete() deleted = deleted + 1 if deleted >= batch_size: return delete_collection(coll_ref, batch_size) # [END firestore_data_delete_collection] delete_collection(db.collection("cities"), 10) delete_collection(db.collection("data"), 10) delete_collection(db.collection("objects"), 10) delete_collection(db.collection("users"), 10) delete_collection(db.collection("users"), 0) def collection_group_query(db): # [START firestore_query_collection_group_dataset] cities = db.collection("cities") sf_landmarks = cities.document("SF").collection("landmarks") sf_landmarks.document().set({"name": "Golden Gate Bridge", "type": "bridge"}) sf_landmarks.document().set({"name": "Legion of Honor", "type": "museum"}) la_landmarks = cities.document("LA").collection("landmarks") la_landmarks.document().set({"name": "Griffith Park", "type": "park"}) la_landmarks.document().set({"name": "The Getty", "type": "museum"}) dc_landmarks = cities.document("DC").collection("landmarks") dc_landmarks.document().set({"name": "Lincoln Memorial", "type": "memorial"}) dc_landmarks.document().set( {"name": "National Air and Space Museum", "type": "museum"} ) tok_landmarks = cities.document("TOK").collection("landmarks") tok_landmarks.document().set({"name": "Ueno Park", "type": "park"}) tok_landmarks.document().set( {"name": "National Museum of Nature and Science", "type": "museum"} ) bj_landmarks = cities.document("BJ").collection("landmarks") bj_landmarks.document().set({"name": "Jingshan Park", "type": "park"}) bj_landmarks.document().set( {"name": "Beijing Ancient Observatory", "type": "museum"} ) # [END firestore_query_collection_group_dataset] # [START firestore_query_collection_group_filter_eq] museums = db.collection_group("landmarks").where( filter=FieldFilter("type", "==", "museum") ) docs = museums.stream() for doc in docs: print(f"{doc.id} => {doc.to_dict()}") # [END firestore_query_collection_group_filter_eq] return docs def array_contains_any_queries(db): # [START firestore_query_filter_array_contains_any] cities_ref = db.collection("cities") query = cities_ref.where( filter=FieldFilter( "regions", "array_contains_any", ["west_coast", "east_coast"] ) ) return query # [END firestore_query_filter_array_contains_any] def in_query_without_array(db): # [START firestore_query_filter_in] cities_ref = db.collection("cities") query = cities_ref.where(filter=FieldFilter("country", "in", ["USA", "Japan"])) return query # [END firestore_query_filter_in] def in_query_with_array(db): # [START firestore_query_filter_in_with_array] cities_ref = db.collection("cities") query = cities_ref.where( filter=FieldFilter("regions", "in", [["west_coast"], ["east_coast"]]) ) return query # [END firestore_query_filter_in_with_array] def not_in_query(db): # [START firestore_query_filter_not_in] cities_ref = db.collection("cities") query = cities_ref.where(filter=FieldFilter("country", "not-in", ["USA", "Japan"])) return query # [END firestore_query_filter_not_in] def not_equal_query(db): # [START firestore_query_filter_not_equal] cities_ref = db.collection("cities") query = cities_ref.where(filter=FieldFilter("capital", "!=", False)) return query # [END firestore_query_filter_not_equal] def update_document_increment(db): # [START firestore_data_set_numeric_increment] washington_ref = db.collection("cities").document("DC") washington_ref.update({"population": firestore.Increment(50)}) # [END firestore_data_set_numeric_increment] def list_document_subcollections(): db = firestore.Client() # [START firestore_data_get_sub_collections] city_ref = db.collection("cities").document("SF") collections = city_ref.collections() for collection in collections: for doc in collection.stream(): print(f"{doc.id} => {doc.to_dict()}") # [END firestore_data_get_sub_collections] def _setup_bundle(): from google.cloud import firestore db = firestore.Client() db.collection("stories").document("news-item").set({"title": "Wow!"}) def create_and_build_bundle(): _setup_bundle() # [START firestore_create_and_build_bundle] from google.cloud import firestore from google.cloud.firestore_bundle import FirestoreBundle db = firestore.Client() bundle = FirestoreBundle("latest-stories") doc_snapshot = db.collection("stories").document("news-item").get() query = db.collection("stories")._query() # Build the bundle # Note how `query` is named "latest-stories-query" bundle_buffer: str = ( bundle.add_document(doc_snapshot) .add_named_query( "latest-stories-query", query, ) .build() ) # [END firestore_create_and_build_bundle] return bundle, bundle_buffer def regional_endpoint(): # [START firestore_regional_endpoint] ENDPOINT = "nam5-firestore.googleapis.com" client_options = ClientOptions(api_endpoint=ENDPOINT) db = firestore.Client(client_options=client_options) cities_query = db.collection("cities").limit(2).get() for r in cities_query: print(r) # [END firestore_regional_endpoint] return cities_query def query_filter_compound_multi_ineq(): from google.cloud import firestore db = firestore.Client( add_unique_string=False ) # Flag for testing purposes, needs index to be precreated # [START firestore_query_filter_compound_multi_ineq] query = ( db.collection("cities") .where(filter=FieldFilter("population", ">", 1_000_000)) .where(filter=FieldFilter("density", "<", 10_000)) ) # [END firestore_query_filter_compound_multi_ineq] return query def query_indexing_considerations(): db = firestore.Client( add_unique_string=False ) # Flag for testing purposes, needs index to be precreated # [START firestore_query_indexing_considerations] query = ( db.collection("employees") .where(filter=FieldFilter("salary", ">", 100_000)) .where(filter=FieldFilter("experience", ">", 0)) .order_by("salary") .order_by("experience") ) # [END firestore_query_indexing_considerations] return query def query_order_fields(): db = firestore.Client() # [START firestore_query_order_fields] query = ( db.collection("employees") .where(filter=FieldFilter("salary", ">", 100_000)) .order_by("salary") ) results = query.stream() # Order results by `experience` sorted_results = sorted(results, key=lambda x: x.get("experience")) # [END firestore_query_order_fields] return sorted_results
City
python
run-llama__llama_index
llama-index-integrations/postprocessor/llama-index-postprocessor-contextual-rerank/tests/test_contextual_rerank.py
{ "start": 292, "end": 2344 }
class ____(TestCase): def test_contextual_rerank(self): nodes = [ NodeWithScore(node=TextNode(text="the capital of france is paris")), NodeWithScore( node=TextNode(text="the capital of the United States is Washington DC") ), ] exp_rerank_response = RerankCreateResponse( results=[ {"index": 0, "relevance_score": 0.616}, {"index": 1, "relevance_score": 0.445}, ] ) expected_nodes = [ NodeWithScore( node=TextNode(text="the capital of france is paris"), score=0.616 ), NodeWithScore( node=TextNode(text="the capital of the United States is Washington DC"), score=0.445, ), ] query = "What is the capital of France?" # Mock the ContextualAI client contextual_client = mock.MagicMock() contextual_client.rerank.create.return_value = exp_rerank_response contextual_rerank = ContextualRerank( api_key="blah", model="ctxl-rerank-en-v1-instruct", top_n=2, client=contextual_client, ) actual_nodes = contextual_rerank.postprocess_nodes(nodes, query_str=query) assert len(actual_nodes) == 2 for actual_node_with_score, expected_node_with_score in zip( actual_nodes, expected_nodes ): print(actual_node_with_score.score) self.assertEqual( actual_node_with_score.node.get_content(), expected_node_with_score.node.get_content(), ) self.assertAlmostEqual( actual_node_with_score.score, expected_node_with_score.score, places=3, ) def test_class(self): names_of_base_classes = [b.__name__ for b in ContextualRerank.__mro__] assert BaseNodePostprocessor.__name__ in names_of_base_classes
TestContextualRerank
python
bokeh__bokeh
src/bokeh/models/widgets/tables.py
{ "start": 18132, "end": 18441 }
class ____(CellEditor): ''' Select cell editor. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) options = List(String, help=""" The list of options to select from. """)
SelectEditor
python
huggingface__transformers
src/transformers/models/glm4/modular_glm4.py
{ "start": 3464, "end": 3510 }
class ____(GlmAttention): pass
Glm4Attention
python
numba__numba
numba/core/caching.py
{ "start": 16087, "end": 16968 }
class ____(CacheImpl): """ Implements the logic to cache CodeLibrary objects. """ _filename_prefix = None # must be overridden def reduce(self, codelib): """ Returns a serialized CodeLibrary """ return codelib.serialize_using_object_code() def rebuild(self, target_context, payload): """ Returns the unserialized CodeLibrary """ return target_context.codegen().unserialize_library(payload) def check_cachable(self, codelib): """ Check cachability of the given CodeLibrary. """ return not codelib.has_dynamic_globals def get_filename_base(self, fullname, abiflags): parent = super(CodeLibraryCacheImpl, self) res = parent.get_filename_base(fullname, abiflags) return '-'.join([self._filename_prefix, res])
CodeLibraryCacheImpl
python
pennersr__django-allauth
allauth/socialaccount/providers/openid/models.py
{ "start": 31, "end": 357 }
class ____(models.Model): server_url = models.CharField(max_length=255) handle = models.CharField(max_length=255) secret = models.TextField() issued = models.IntegerField() lifetime = models.IntegerField() assoc_type = models.TextField() def __str__(self): return self.server_url
OpenIDStore
python
huggingface__transformers
tests/models/efficientnet/test_modeling_efficientnet.py
{ "start": 8429, "end": 9417 }
class ____(unittest.TestCase): @cached_property def default_image_processor(self): return AutoImageProcessor.from_pretrained("google/efficientnet-b7") if is_vision_available() else None @slow def test_inference_image_classification_head(self): model = EfficientNetForImageClassification.from_pretrained("google/efficientnet-b7").to(torch_device) image_processor = self.default_image_processor image = prepare_img() inputs = image_processor(images=image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the logits expected_shape = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape, expected_shape) expected_slice = torch.tensor([-0.2962, 0.4487, 0.4499]).to(torch_device) torch.testing.assert_close(outputs.logits[0, :3], expected_slice, rtol=1e-4, atol=1e-4)
EfficientNetModelIntegrationTest
python
ApeWorX__ape
src/ape/pytest/fixtures.py
{ "start": 18926, "end": 22934 }
class ____(ManagerAccessMixin): supported: bool = True snapshots: SnapshotRegistry = SnapshotRegistry() def __init__( self, config_wrapper: "ConfigWrapper", receipt_capture: "ReceiptCapture", chain_snapshots: Optional[dict] = None, ): self.config_wrapper = config_wrapper self.receipt_capture = receipt_capture self._chain_snapshots = chain_snapshots @cached_property def _track_transactions(self) -> bool: return ( self.network_manager.provider is not None and self.provider.is_connected and (self.config_wrapper.track_gas or self.config_wrapper.track_coverage) ) @property def chain_snapshots(self) -> dict: return self._chain_snapshots or self.chain_manager._snapshots def get_snapshot(self, scope: Scope) -> Snapshot: return self.snapshots[scope] def extend_fixtures(self, scope: Scope, fixtures: Iterable[str]): self.snapshots.extend_fixtures(scope, fixtures) def next_snapshots(self, scope: Scope) -> Iterator[Snapshot]: yield from self.snapshots.next_snapshots(scope) def isolation(self, scope: Scope) -> Iterator[None]: """ Isolation logic used to implement isolation fixtures for each pytest scope. When tracing support is available, will also assist in capturing receipts. """ self.set_snapshot(scope) if self._track_transactions: did_yield = False try: with self.receipt_capture: yield did_yield = True except BlockNotFoundError: if not did_yield: # Prevent double yielding. yield else: yield self.restore(scope) def set_snapshot(self, scope: Scope): # Also can be used to re-set snapshot. if not self.supported or not self.config_wrapper.get_isolation(scope): return try: snapshot_id = self.take_snapshot() except Exception: self.supported = False else: if snapshot_id is not None: self.snapshots.set_snapshot_id(scope, snapshot_id) @allow_disconnected def take_snapshot(self) -> Optional["SnapshotID"]: try: return self.chain_manager.snapshot() except NotImplementedError: logger.warning( "The connected provider does not support snapshotting. " "Tests will not be completely isolated." ) # To avoid trying again self.supported = False return None @allow_disconnected def restore(self, scope: Scope): # NOTE: self._supported may have gotten set to False # someplace else _after_ snapshotting succeeded. if not self.supported or not self.config_wrapper.get_isolation(scope): return self.restore_snapshot(scope) @allow_disconnected def restore_snapshot(self, scope: Scope): snapshot_id = self.snapshots.get_snapshot_id(scope) if snapshot_id is None: return elif snapshot_id not in self.chain_snapshots[self.chain_manager.chain_id]: # Still clear out. self.snapshots.clear_snapshot_id(scope) return try: self._restore(snapshot_id) except NotImplementedError: logger.warning( "The connected provider does not support snapshotting. " "Tests will not be completely isolated." ) # To avoid trying again self.supported = False except Exception as err: logger.error(f"Unhandled error with restoring snapshot: {err}") self.snapshots.clear_snapshot_id(scope) def _restore(self, snapshot_id: "SnapshotID"): self.chain_manager.restore(snapshot_id)
IsolationManager
python
getsentry__sentry
tests/acceptance/test_trace_view_from_explore.py
{ "start": 481, "end": 3665 }
class ____(AcceptanceTestCase, TraceTestCase, SnubaTestCase): viewname = "sentry-api-0-organization-events" FEATURES = [ "organizations:visibility-explore-view", "organizations:performance-view", "organizations:trace-spans-format", ] def setUp(self) -> None: super().setUp() self.snuba_eventstream = SnubaEventStream() self.start = self.day_ago = before_now(days=1).replace( hour=10, minute=0, second=0, microsecond=0 ) self.start_minus_two_minutes = self.start - timedelta(minutes=2) self.organization = self.create_organization(owner=self.user, name="Rowdy Tiger") self.team = self.create_team( organization=self.organization, name="Mariachi Band", members=[self.user] ) self.project = self.create_project( organization=self.organization, teams=[self.team], name="Bengal" ) self.login_as(self.user) self.page = ExploreSpansPage(self.browser, self.client) self.trace_view_page = TraceViewWaterfallPage(self.browser, self.client) self.dismiss_assistant(which="tour.explore.spans") @patch("django.utils.timezone.now") @pytest.mark.skip(reason="This test is flaky and needs to be fixed") def test_navigation(self, mock_now: MagicMock) -> None: mock_now.return_value = self.start assert ( self.browser.driver.get_window_size().get("width") == 1680 ) # This test makes assertions based on the current default window size. with self.feature(self.FEATURES): self.create_event( trace_id=self.trace_id, start_timestamp=self.start_minus_two_minutes, transaction="root", spans=[ { "same_process_as_parent": True, "op": "http.server", "description": f"GET gen1-{root_span_id}", "span_id": root_span_id, "trace_id": self.trace_id, } for i, root_span_id in enumerate(self.root_span_ids) ], parent_span_id=None, project_id=self.project.id, milliseconds=3000, is_eap=True, ) # Visit explore spans table self.page.visit_explore_spans(self.organization.slug) # Click on the first span in the explore spans table self.page.click_on_span_id(self.root_span_ids[0][:8]) # Wait for the trace view to load and check that the spans are in the trace view waterfall self.trace_view_page.wait_until_loaded() for span_id in self.root_span_ids: span_row = self.trace_view_page.get_trace_span_row( "http.server", f"GET gen1-{span_id}" ) assert span_row is not None normalized_text = self.trace_view_page.normalize_span_row_text(span_row.text) assert normalized_text == f"http.server - GET gen1-{span_id}"
TraceViewFromExploreTest
python
tensorflow__tensorflow
tensorflow/python/keras/engine/data_adapter.py
{ "start": 14856, "end": 18336 }
class ____(TensorLikeDataAdapter): """Adapter that handles array-like data without forcing it into memory. This adapter handles array-like datasets that may be too big to fully fit into memory. Specifically, this adapter handles any Python class which implements: `__get_item__`, `__len__`, `shape`, and `dtype` with the same meanings as Numpy, but it ignores any case where all the inputs are Tensors or Numpy arrays (because that case is handled by the base TensorLikeDataAdapter). It ignores scipy sparse matrices and Composite Tensors because those are handled by the CompositeTensorDataAdapter. It also does not handle lists/tuples of scalars, because those are handled by the ListsOfScalarsDataAdapter. """ @staticmethod def can_handle(x, y=None): flat_inputs = nest.flatten(x) if y is not None: flat_inputs += nest.flatten(y) def _is_array_like(v): """Return True if v is a Tensor, array, or is array-like.""" return ( hasattr(v, "__getitem__") and hasattr(v, "shape") and hasattr(v, "dtype") and hasattr(v, "__len__") ) if (not TensorLikeDataAdapter.can_handle(x, y) and not CompositeTensorDataAdapter.can_handle(x, y)): return all(_is_array_like(v) for v in flat_inputs) else: return False def __init__(self, *args, **kwargs): logging.warning( "Keras is training/fitting/evaluating on array-like data. Keras may " "not be optimized for this format, so if your input data format is " "supported by TensorFlow I/O (https://github.com/tensorflow/io) we " "recommend using that to load a Dataset instead.") super(GenericArrayLikeDataAdapter, self).__init__(*args, **kwargs) def slice_inputs(self, indices_dataset, inputs): """Slice inputs into a Dataset of batches. Given a Dataset of batch indices and the unsliced inputs, this step slices the inputs in a parallelized fashion and produces a dataset of input batches. Args: indices_dataset: A Dataset of batched indices inputs: A python data structure that contains the inputs, targets, and possibly sample weights. Returns: A Dataset of input batches matching the batch indices. """ flat_inputs = nest.flatten(inputs) def dynamic_shape_like(t): shape = list(t.shape) shape[0] = None return tuple(shape) flat_dtypes = [inp.dtype for inp in flat_inputs] contiguous = True if self._shuffle and self._shuffle != "batch": contiguous = False def grab_batch(indices): """Grab a batch of data from the inputs.""" # This uses a py_function to avoid converting the array-like # into a Tensor before slicing it, because converting the array-like # to a Tensor may force it into memory.. def py_method(ind): def slice_array(data): return training_utils.slice_arrays(data, ind.numpy(), contiguous=contiguous) return [slice_array(inp) for inp in flat_inputs] flat_out = script_ops.eager_py_func(py_method, [indices], flat_dtypes) for v, original_inp in zip(flat_out, flat_inputs): v.set_shape(dynamic_shape_like(original_inp)) return nest.pack_sequence_as(inputs, flat_out) dataset = indices_dataset.map( grab_batch, num_parallel_calls=dataset_ops.AUTOTUNE) return dataset
GenericArrayLikeDataAdapter
python
getsentry__sentry
tests/sentry/web/frontend/test_vercel_extension_configuration.py
{ "start": 550, "end": 6302 }
class ____(TestCase): path = "/extensions/vercel/configure/" def setUp(self) -> None: self.user = self.create_user() self.org = self.create_organization() with assume_test_silo_mode(SiloMode.REGION): OrganizationMember.objects.create( user_id=self.user.id, organization=self.org, role="admin" ) responses.reset() # need oauth mocks access_json = { "user_id": "my_user_id", "access_token": "my_access_token", "installation_id": "my_config_id", } responses.add( responses.POST, VercelIdentityProvider.oauth_access_token_url, json=access_json ) responses.add( responses.GET, f"{VercelClient.base_url}{VercelClient.GET_USER_URL}", json={"user": {"name": "my_user_name"}}, ) responses.add( responses.GET, f"{VercelClient.base_url}{VercelClient.GET_PROJECTS_URL}", json={"projects": [], "pagination": {"count": 0, "next": None}}, ) self.params = { "configurationId": "config_id", "code": "my-code", "next": "https://example.com", } @responses.activate @with_feature("organizations:integrations-deployment") def test_logged_in_one_org(self) -> None: self.login_as(self.user) resp = self.client.get(self.path, self.params) mock_request = responses.calls[0].request req_params = parse_qs(mock_request.body) assert req_params["code"] == ["my-code"] # Goes straight to Vercel OAuth assert resp.status_code == 302 assert resp.headers["Location"].startswith( f"http://testserver/settings/{self.org.slug}/integrations/vercel/" ) assert resp.headers["Location"].endswith("?next=https%3A%2F%2Fexample.com") @responses.activate def test_logged_in_as_member(self) -> None: with ( assume_test_silo_mode(SiloMode.REGION), unguarded_write(using=router.db_for_write(OrganizationMember)), ): OrganizationMember.objects.filter(user_id=self.user.id, organization=self.org).update( role="member" ) self.login_as(self.user) resp = self.client.get(self.path, self.params) assert resp.status_code == 302 assert resp.headers["Location"].startswith("/extensions/vercel/link/?") expected_query_string = { "configurationId": ["config_id"], "code": ["my-code"], "next": ["https://example.com"], } parsed_url = urlparse(resp.headers["Location"]) assert parse_qs(parsed_url.query) == expected_query_string @responses.activate def test_logged_in_many_orgs(self) -> None: self.login_as(self.user) org = self.create_organization() with assume_test_silo_mode(SiloMode.REGION): OrganizationMember.objects.create(user_id=self.user.id, organization=org) resp = self.client.get(self.path, self.params) assert resp.status_code == 302 assert resp.headers["Location"].startswith("/extensions/vercel/link/?") expected_query_string = { "configurationId": ["config_id"], "code": ["my-code"], "next": ["https://example.com"], } parsed_url = urlparse(resp.headers["Location"]) assert parse_qs(parsed_url.query) == expected_query_string @responses.activate def test_choose_org(self) -> None: self.login_as(self.user) org = self.create_organization() with assume_test_silo_mode(SiloMode.REGION): OrganizationMember.objects.create(user_id=self.user.id, organization=org) self.params["orgSlug"] = org.slug resp = self.client.get(self.path, self.params) # Goes straight to Vercel OAuth assert resp.status_code == 302 assert resp.headers["Location"].startswith("/extensions/vercel/link/?") expected_query_string = { "configurationId": ["config_id"], "code": ["my-code"], "next": ["https://example.com"], "orgSlug": [org.slug], } parsed_url = urlparse(resp.headers["Location"]) assert parse_qs(parsed_url.query) == expected_query_string @responses.activate def test_logged_out(self) -> None: resp = self.client.get(self.path, self.params) assert resp.status_code == 302 # URL encoded post-login redirect URL= assert resp.headers["Location"].startswith("/auth/login/?") # URL encoded post-login redirect URL= assert ( "next=%2Fextensions%2Fvercel%2Fconfigure%2F%3FconfigurationId%3Dconfig_id%26code%3Dmy-code%26next%3Dhttps%253A%252F%252Fexample.com" in resp.headers["Location"] ) @responses.activate @with_feature("organizations:integrations-deployment") def test_logged_in_one_org_customer_domain(self) -> None: self.login_as(self.user) resp = self.client.get( self.path, self.params, HTTP_HOST=f"{self.org.slug}.testserver", ) mock_request = responses.calls[0].request req_params = parse_qs(mock_request.body) assert req_params["code"] == ["my-code"] # Goes straight to Vercel OAuth assert resp.status_code == 302 assert resp.headers["Location"].startswith( f"http://{self.org.slug}.testserver/settings/integrations/vercel/" ) assert resp.headers["Location"].endswith("?next=https%3A%2F%2Fexample.com")
VercelExtensionConfigurationTest
python
realpython__materials
inheritance-and-composition/inheritance/productivity.py
{ "start": 0, "end": 306 }
class ____: def track(self, employees, hours): print("Tracking Employee Productivity") print("==============================") for employee in employees: result = employee.work(hours) print(f"{employee.name}: {result}") print("")
ProductivitySystem
python
openai__openai-python
src/openai/types/responses/response_computer_tool_call_output_item.py
{ "start": 639, "end": 1527 }
class ____(BaseModel): id: str """The unique ID of the computer call tool output.""" call_id: str """The ID of the computer tool call that produced the output.""" output: ResponseComputerToolCallOutputScreenshot """A computer screenshot image used with the computer use tool.""" type: Literal["computer_call_output"] """The type of the computer tool call output. Always `computer_call_output`.""" acknowledged_safety_checks: Optional[List[AcknowledgedSafetyCheck]] = None """ The safety checks reported by the API that have been acknowledged by the developer. """ status: Optional[Literal["in_progress", "completed", "incomplete"]] = None """The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items are returned via API. """
ResponseComputerToolCallOutputItem
python
encode__django-rest-framework
tests/test_filters.py
{ "start": 17459, "end": 18905 }
class ____(TestCase): @classmethod def setUpTestData(cls): SearchFilterModel.objects.create(title='abc', text='def') SearchFilterModel.objects.create(title='ghi', text='jkl') def test_search_in_annotated_field(self): class SearchListView(generics.ListAPIView): queryset = SearchFilterModel.objects.annotate( title_text=Upper( Concat(models.F('title'), models.F('text')) ) ).all() serializer_class = SearchFilterAnnotatedSerializer filter_backends = (filters.SearchFilter,) search_fields = ('title_text',) view = SearchListView.as_view() request = factory.get('/', {'search': 'ABCDEF'}) response = view(request) assert len(response.data) == 1 assert response.data[0]['title_text'] == 'ABCDEF' def test_must_call_distinct_subsequent_m2m_fields(self): f = filters.SearchFilter() queryset = SearchFilterModelM2M.objects.annotate( title_text=Upper( Concat(models.F('title'), models.F('text')) ) ).all() # Sanity check that m2m must call distinct assert f.must_call_distinct(queryset, ['attributes']) # Annotated field should not prevent m2m must call distinct assert f.must_call_distinct(queryset, ['title_text', 'attributes'])
SearchFilterAnnotatedFieldTests
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dlp.py
{ "start": 24936, "end": 25902 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook") def test_update_deidentify_template(self, mock_hook): mock_hook.return_value.update_deidentify_template.return_value = DeidentifyTemplate() operator = CloudDLPUpdateDeidentifyTemplateOperator( template_id=TEMPLATE_ID, organization_id=ORGANIZATION_ID, task_id="id" ) operator.execute(context=mock.MagicMock()) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=None, ) mock_hook.return_value.update_deidentify_template.assert_called_once_with( template_id=TEMPLATE_ID, organization_id=ORGANIZATION_ID, project_id=None, deidentify_template=None, update_mask=None, retry=DEFAULT, timeout=None, metadata=(), )
TestCloudDLPUpdateDeidentifyTemplateOperator
python
pyodide__pyodide
src/py/_pyodide/_core_docs.py
{ "start": 15300, "end": 17976 }
class ____(JsProxy, Generic[T]): """A :py:class:`~pyodide.ffi.JsProxy` of a :js:class:`Promise` or some other `thenable <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables>`_ JavaScript object. A JavaScript object is considered to be a :js:class:`Promise` if it has a ``then`` method. """ _js_type_flags = ["IS_AWAITABLE"] @overload def then( self, onfulfilled: None, onrejected: Callable[[BaseException], Awaitable[S]], / ) -> "JsPromise[S]": ... @overload def then( self, onfulfilled: None, onrejected: Callable[[BaseException], S], / ) -> "JsPromise[S]": ... @overload def then( self, onfulfilled: Callable[[T], Awaitable[S]], onrejected: Callable[[BaseException], Awaitable[S]] | None = None, /, ) -> "JsPromise[S]": ... @overload def then( self, onfulfilled: Callable[[T], S], onrejected: Callable[[BaseException], S] | None = None, /, ) -> "JsPromise[S]": ... @docs_argspec( "(self, onfulfilled: Callable[[T], Awaitable[S] | S] | None, onrejected: Callable[[BaseException], Awaitable[S] | S] | None = None, /) -> 'JsPromise[S]'" ) def then( self, onfulfilled: Any, onrejected: Any = None, ) -> Any: """The :js:meth:`Promise.then` API, wrapped to manage the lifetimes of the handlers. Pyodide will automatically release the references to the handlers when the promise resolves. """ pass @overload def catch( self, onrejected: Callable[[BaseException], Awaitable[S]], / ) -> "JsPromise[S]": ... @overload def catch(self, onrejected: Callable[[BaseException], S], /) -> "JsPromise[S]": ... @docs_argspec( "(self, onrejected: Callable[[BaseException], Awaitable[S] | S], /) -> 'JsPromise[S]'" ) def catch(self, onrejected: Any, /) -> Any: """The :js:meth:`Promise.catch` API, wrapped to manage the lifetimes of the handler. Pyodide will automatically release the references to the handler when the promise resolves. """ pass def finally_(self, onfinally: Callable[[], None], /) -> "JsPromise[T]": """The :js:meth:`Promise.finally` API, wrapped to manage the lifetimes of the handler. Pyodide will automatically release the references to the handler when the promise resolves. Note the trailing underscore in the name; this is needed because ``finally`` is a reserved keyword in Python. """ return self
JsPromise
python
PyCQA__pylint
tests/functional/i/inconsistent/inconsistent_returns_noreturn.py
{ "start": 1621, "end": 3641 }
class ____: def _no_return_method(self) -> typing.NoReturn: sys.exit(1) def _falsely_no_return_method(self) -> typing.NoReturn: return 1 def _does_return_method(self) -> int: return 1 def bug_pylint_8747(self, s: str) -> int: """Every return is consistent because self._no_return_method hints NoReturn""" try: n = int(s) if n < 1: raise ValueError return n except ValueError: self._no_return_method() def bug_pylint_8747_wrong(self, s: str) -> int: # [inconsistent-return-statements] """Every return is not consistent because self._does_return_method() returns a value""" try: n = int(s) if n < 1: raise ValueError return n except ValueError: self._does_return_method() def bug_pylint_8747_incorrect_annotation(self, s: str) -> int: """Every return is consistent since pylint does not attempt to detect that the NoReturn annotation is incorrect and the function actually returns """ try: n = int(s) if n < 1: raise ValueError return n except ValueError: self._falsely_no_return_method() # https://github.com/pylint-dev/pylint/issues/7565 def never_is_handled_like_noreturn(arg: typing.Union[int, str]) -> int: if isinstance(arg, int): return 1 if isinstance(arg, str): return 2 assert_never(arg) def declared_to_not_return() -> None: return def config_takes_precedence_over_inference(arg: typing.Union[int, str]) -> int: if isinstance(arg, int): return 1 if isinstance(arg, str): return 2 declared_to_not_return() def unrelated() -> None: return # +1: [inconsistent-return-statements] def ensure_message(arg: typing.Union[int, str]) -> int: if isinstance(arg, int): return 1 unrelated()
ClassUnderTest
python
hyperopt__hyperopt
hyperopt/mongoexp.py
{ "start": 21476, "end": 34662 }
class ____(Trials): """Trials maps on to an entire mongo collection. It's basically a wrapper around MongoJobs for now. As a concession to performance, this object permits trial filtering based on the exp_key, but I feel that's a hack. The case of `cmd` is similar-- the exp_key and cmd are semantically coupled. WRITING TO THE DATABASE ----------------------- The trials object is meant for *reading* a trials database. Writing to a database is different enough from writing to an in-memory collection that no attempt has been made to abstract away that difference. If you want to update the documents within a MongoTrials collection, then retrieve the `.handle` attribute (a MongoJobs instance) and use lower-level methods, or pymongo's interface directly. When you are done writing, call refresh() or refresh_tids() to bring the MongoTrials up to date. """ asynchronous = True def __init__(self, arg, exp_key=None, cmd=None, workdir=None, refresh=True): if not _has_mongo: raise Exception( "MongoTrials cannot import pymongo classes. Make sure that pymongo " "is available in your environment. E.g., try running 'import pymongo'" ) if isinstance(arg, MongoJobs): self.handle = arg else: connection_string = arg self.handle = MongoJobs.new_from_connection_str(connection_string) self.handle.create_indexes() self._exp_key = exp_key self.cmd = cmd self.workdir = workdir if refresh: self.refresh() def view(self, exp_key=None, cmd=None, workdir=None, refresh=True): rval = self.__class__( self.handle, exp_key=self._exp_key if exp_key is None else exp_key, cmd=self.cmd if cmd is None else cmd, workdir=self.workdir if workdir is None else workdir, refresh=refresh, ) return rval def refresh_tids(self, tids): """Sync documents with `['tid']` in the list of `tids` from the database (not *to* the database). Local trial documents whose tid is not in `tids` are not affected by this call. Local trial documents whose tid is in `tids` may be: * *deleted* (if db no longer has corresponding document), or * *updated* (if db has an updated document) or, * *left alone* (if db document matches local one). Additionally, if the db has a matching document, but there is no local trial with a matching tid, then the db document will be *inserted* into the local collection. """ exp_key = self._exp_key query = {"exp_key": exp_key} if exp_key != None else {} t0 = time.time() query["state"] = {"$ne": JOB_STATE_ERROR} if tids is not None: query["tid"] = {"$in": list(tids)} orig_trials = getattr(self, "_trials", []) _trials = orig_trials[:] # copy to make sure it doesn't get screwed up if _trials: db_data = list(self.handle.jobs.find(query, projection=["_id", "version"])) # -- pull down a fresh list of ids from mongo if db_data: # make numpy data arrays db_data = numpy.rec.array( [(x["_id"], int(x["version"])) for x in db_data], names=["_id", "version"], ) db_data.sort(order=["_id", "version"]) db_data = db_data[get_most_recent_inds(db_data)] existing_data = numpy.rec.array( [(x["_id"], int(x["version"])) for x in _trials], names=["_id", "version"], ) existing_data.sort(order=["_id", "version"]) # which records are in db but not in existing, and vice versa db_in_existing = fast_isin(db_data["_id"], existing_data["_id"]) existing_in_db = fast_isin(existing_data["_id"], db_data["_id"]) # filtering out out-of-date records _trials = [_trials[_ind] for _ind in existing_in_db.nonzero()[0]] # new data is what's in db that's not in existing new_data = db_data[numpy.invert(db_in_existing)] # having removed the new and out of data data, # concentrating on data in db and existing for state changes db_data = db_data[db_in_existing] existing_data = existing_data[existing_in_db] try: assert len(db_data) == len(existing_data) assert (existing_data["_id"] == db_data["_id"]).all() assert (existing_data["version"] <= db_data["version"]).all() except: report_path = os.path.join( os.getcwd(), "hyperopt_refresh_crash_report_" + str(numpy.random.randint(1e8)) + ".pkl", ) logger.error( "HYPEROPT REFRESH ERROR: writing error file to %s" % report_path ) _file = open(report_path, "w") pickler.dump( {"db_data": db_data, "existing_data": existing_data}, _file ) _file.close() raise same_version = existing_data["version"] == db_data["version"] _trials = [_trials[_ind] for _ind in same_version.nonzero()[0]] version_changes = existing_data[numpy.invert(same_version)] # actually get the updated records update_ids = new_data["_id"].tolist() + version_changes["_id"].tolist() num_new = len(update_ids) update_query = copy.deepcopy(query) update_query["_id"] = {"$in": update_ids} updated_trials = list(self.handle.jobs.find(update_query)) _trials.extend(updated_trials) else: num_new = 0 _trials = [] else: # this case is for performance, though should be able to be removed # without breaking correctness. _trials = list(self.handle.jobs.find(query)) if _trials: _trials = [_trials[_i] for _i in get_most_recent_inds(_trials)] num_new = len(_trials) logger.debug( "Refresh data download took %f seconds for %d ids" % (time.time() - t0, num_new) ) if tids is not None: # -- If tids were given, then _trials only contains # documents with matching tids. Here we augment these # fresh matching documents, with our current ones whose # tids don't match. new_trials = _trials tids_set = set(tids) assert all(t["tid"] in tids_set for t in new_trials) old_trials = [t for t in orig_trials if t["tid"] not in tids_set] _trials = new_trials + old_trials # -- reassign new trials to self, in order of increasing tid jarray = numpy.array([j["_id"] for j in _trials]) jobsort = jarray.argsort() self._trials = [_trials[_idx] for _idx in jobsort] self._specs = [_trials[_idx]["spec"] for _idx in jobsort] self._results = [_trials[_idx]["result"] for _idx in jobsort] self._miscs = [_trials[_idx]["misc"] for _idx in jobsort] def refresh(self): self.refresh_tids(None) def _insert_trial_docs(self, docs): rval = [] for doc in docs: rval.append(self.handle.jobs.insert(doc)) return rval def count_by_state_unsynced(self, arg): exp_key = self._exp_key # TODO: consider searching by SON rather than dict if isinstance(arg, int): if arg not in JOB_STATES: raise ValueError("invalid state", arg) query = dict(state=arg) else: assert hasattr(arg, "__iter__") states = list(arg) assert all([x in JOB_STATES for x in states]) query = dict(state={"$in": states}) if exp_key != None: query["exp_key"] = exp_key rval = self.handle.jobs.find(query).count() return rval def delete_all(self, cond=None): cond = {} if cond is None else dict(cond) if self._exp_key: cond["exp_key"] = self._exp_key # -- remove all documents matching condition self.handle.delete_all(cond) gfs = self.handle.gfs for filename in gfs.list(): try: fdoc = gfs.get_last_version(filename=filename, **cond) except gridfs.errors.NoFile: continue gfs.delete(fdoc._id) self.refresh() def new_trial_ids(self, last_id): db = self.handle.db # N.B. that the exp key is *not* used here. It was once, but it caused # a nasty bug: tids were generated by a global experiment # with exp_key=None, running a suggest() that introduced sub-experiments # with exp_keys, which ran jobs that did result injection. The tids of # injected jobs were sometimes unique within an experiment, and # sometimes not. Hilarious! # # Solution: tids are generated to be unique across the db, not just # within an exp_key. # # -- mongo docs say you can't upsert an empty document query = {"a": 0} doc = None while doc is None: doc = db.job_ids.find_and_modify( query, {"$inc": {"last_id": last_id}}, upsert=True ) if doc is None: logger.warning("no last_id found, re-trying") time.sleep(1.0) lid = doc.get("last_id", 0) return list(range(lid, lid + last_id)) def trial_attachments(self, trial): """ Attachments to a single trial (e.g. learned weights) Returns a dictionary interface to the attachments. """ # don't offer more here than in MongoCtrl class Attachments: def __init__(self, handle: MongoJobs): self.handle = handle def __contains__(self, name): return name in self.handle.attachment_names(doc=trial) def __len__(self): return len(self.handle.attachment_names(doc=trial)) def __iter__(self): return iter(self.handle.attachment_names(doc=trial)) def __getitem__(self, name): try: return self.handle.get_attachment(doc=trial, name=name) except OperationFailure: raise KeyError(name) def __setitem__(self, name, value): self.handle.set_attachment( doc=trial, blob=value, name=name, collection=self.handle.db.jobs ) def __delitem__(self, name): raise NotImplementedError("delete trial_attachment") def keys(self): return [k for k in self] def values(self): return [self[k] for k in self] def items(self): return [(k, self[k]) for k in self] return Attachments(self.handle) @property def attachments(self): """ Attachments to a Trials set (such as bandit args). Support syntax for load: self.attachments[name] Support syntax for store: self.attachments[name] = value """ gfs = self.handle.gfs query = {} if self._exp_key: query["exp_key"] = self._exp_key class Attachments: def __iter__(_self): if query: # -- gfs.list does not accept query kwargs # (at least, as of pymongo 2.4) filenames = [fname for fname in gfs.list() if fname in _self] else: filenames = gfs.list() return iter(filenames) def __contains__(_self, name): return gfs.exists(filename=name, **query) def __getitem__(_self, name): try: rval = gfs.get_version(filename=name, **query).read() return rval except gridfs.NoFile: raise KeyError(name) def __setitem__(_self, name, value): if gfs.exists(filename=name, **query): gout = gfs.get_last_version(filename=name, **query) gfs.delete(gout._id) gfs.put(value, filename=name, encoding="utf-8", **query) def __delitem__(_self, name): gout = gfs.get_last_version(filename=name, **query) gfs.delete(gout._id) return Attachments()
MongoTrials
python
django-import-export__django-import-export
tests/core/tests/admin_integration/test_export.py
{ "start": 15382, "end": 16533 }
class ____(AdminTestMixin, TestCase): fixtures = ["category", "book", "author"] def test_export_filters_by_form_param(self): # issue 1578 author = Author.objects.get(name="Ian Fleming") data = { "format": "0", "author": str(author.id), "ebookresource_id": True, "ebookresource_author_email": True, "ebookresource_name": True, "ebookresource_published": True, } self._prepend_form_prefix(data) date_str = datetime.now().strftime("%Y-%m-%d") response = self._post_url_response(self.ebook_export_url, data) self.assertTrue(response.has_header("Content-Disposition")) self.assertEqual(response["Content-Type"], "text/csv") self.assertEqual( response["Content-Disposition"], f'attachment; filename="EBook-{date_str}.csv"', ) self.assertEqual( b"id,Email of the author,name,published_date\r\n" b"5,ian@example.com,The Man with the Golden Gun,1965-04-01\r\n", response.content, )
FilteredExportAdminIntegrationTest
python
pytorch__pytorch
torch/jit/frontend.py
{ "start": 22778, "end": 28769 }
class ____(Builder): augassign_map = { ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.Mod: "%", ast.BitOr: "|", ast.BitAnd: "&", ast.BitXor: "^", ast.LShift: "<<", ast.RShift: ">>", ast.Pow: "**", } @staticmethod def build_Expr(ctx, stmt): value = stmt.value if value.__class__.__name__ == "Str": # If a statement is a string literal expression, # then it is a docstring. Just ignore it. return None else: return ExprStmt(build_expr(ctx, value)) @staticmethod def build_Assign(ctx, stmt): rhs = build_expr(ctx, stmt.value) lhs = [build_expr(ctx, x) for x in stmt.targets] return Assign(lhs, rhs) @staticmethod def build_AnnAssign(ctx, stmt): if stmt.value is None: raise UnsupportedNodeError(ctx, stmt, reason="without assigned value") # Disallow type annotations on instance attributes outside of __init__ if ( type(stmt.target) is ast.Attribute and stmt.target.value.id == "self" # type: ignore[attr-defined] and ctx.funcname != "__init__" ): start = stmt.col_offset end = start + len(f"self.{stmt.target.attr}") if hasattr(stmt.annotation, "id"): end += len(f": {stmt.annotation.id}") sr = ctx.make_range(stmt.lineno, start, end) raise ValueError( "Type annotations on instance attributes must be declared in " f"__init__, not '{ctx.funcname}': {sr}" ) rhs = build_expr(ctx, stmt.value) lhs = build_expr(ctx, stmt.target) the_type = build_expr(ctx, stmt.annotation) return Assign([lhs], rhs, the_type) @staticmethod def build_Delete(ctx, stmt): r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("del")) return Delete(r, [build_expr(ctx, target) for target in stmt.targets]) @staticmethod def build_Return(ctx, stmt): r = ctx.make_range( stmt.lineno, stmt.col_offset, stmt.col_offset + len("return") ) return Return(r, None if stmt.value is None else build_expr(ctx, stmt.value)) @staticmethod def build_Raise(ctx, stmt): r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("raise")) expr = build_expr(ctx, stmt.exc) return Raise(r, expr) @staticmethod def build_Assert(ctx, stmt): r = ctx.make_range( stmt.lineno, stmt.col_offset, stmt.col_offset + len("assert") ) test = build_expr(ctx, stmt.test) msg = build_expr(ctx, stmt.msg) if stmt.msg is not None else None return Assert(r, test, msg) @staticmethod def build_AugAssign(ctx, stmt): lhs = build_expr(ctx, stmt.target) rhs = build_expr(ctx, stmt.value) op = type(stmt.op) if op in StmtBuilder.augassign_map: op_token = StmtBuilder.augassign_map[op] else: raise NotSupportedError( find_before(ctx, rhs.range().start, "=", offsets=(-1, 0)), "unsupported kind of augmented assignment: " + op.__name__, ) return AugAssign(lhs, op_token, rhs) @staticmethod def build_While(ctx, stmt): if stmt.orelse: # TODO: try to recover the location of else:? Python doesn't give us useful # annotations in this case raise NotSupportedError( None, "else branches of while loops aren't supported" ) r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("while")) return While(r, build_expr(ctx, stmt.test), build_stmts(ctx, stmt.body)) @staticmethod def build_For(ctx, stmt): r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("for")) if stmt.orelse: raise NotSupportedError(r, "else branches of for loops aren't supported") return For( r, [build_expr(ctx, stmt.target)], [build_expr(ctx, stmt.iter)], build_stmts(ctx, stmt.body), ) @staticmethod def build_If(ctx, stmt): r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("if")) return If( r, build_expr(ctx, stmt.test), build_stmts(ctx, stmt.body), build_stmts(ctx, stmt.orelse), ) @staticmethod def build_Print(ctx, stmt): r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("print")) if stmt.dest: raise NotSupportedError( r, "print statements with non-default destinations aren't supported" ) args = [build_expr(ctx, val) for val in stmt.values] return ExprStmt(Apply(Var(Ident(r, "print")), args, [])) @staticmethod def build_Pass(ctx, stmt): r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("pass")) return Pass(r) @staticmethod def build_Break(ctx, stmt): r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("break")) return Break(r) @staticmethod def build_Continue(ctx, stmt): r = ctx.make_range( stmt.lineno, stmt.col_offset, stmt.col_offset + len("continue") ) return Continue(r) @staticmethod def build_With(ctx, stmt): r = ctx.make_range(stmt.lineno, stmt.col_offset, stmt.col_offset + len("with")) # Handle ignore context manager if is_torch_jit_ignore_context_manager(stmt): assign_ast = build_ignore_context_manager(ctx, stmt) return build_stmt(ctx, assign_ast) return With(r, build_withitems(ctx, stmt.items), build_stmts(ctx, stmt.body))
StmtBuilder
python
doocs__leetcode
solution/0800-0899/0840.Magic Squares In Grid/Solution.py
{ "start": 0, "end": 1005 }
class ____: def numMagicSquaresInside(self, grid: List[List[int]]) -> int: def check(i: int, j: int) -> int: if i + 3 > m or j + 3 > n: return 0 s = set() row = [0] * 3 col = [0] * 3 a = b = 0 for x in range(i, i + 3): for y in range(j, j + 3): v = grid[x][y] if v < 1 or v > 9: return 0 s.add(v) row[x - i] += v col[y - j] += v if x - i == y - j: a += v if x - i == 2 - (y - j): b += v if len(s) != 9 or a != b: return 0 if any(x != a for x in row) or any(x != a for x in col): return 0 return 1 m, n = len(grid), len(grid[0]) return sum(check(i, j) for i in range(m) for j in range(n))
Solution
python
huggingface__transformers
src/transformers/models/nllb_moe/modeling_nllb_moe.py
{ "start": 2400, "end": 6972 }
class ____(nn.Module): """This module produces sinusoidal positional embeddings of any length.""" def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None): super().__init__() self.offset = 2 self.embedding_dim = embedding_dim self.padding_idx = padding_idx self.make_weights(num_positions + self.offset, embedding_dim, padding_idx) def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None): emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx) if hasattr(self, "weights"): # in forward put the weights on the correct dtype and device of the param emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device) self.register_buffer("weights", emb_weights, persistent=False) @staticmethod def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None): """ Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of "Attention Is All You Need". """ half_dim = embedding_dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb) emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0) emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1) if embedding_dim % 2 == 1: # zero pad emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1) if padding_idx is not None: emb[padding_idx, :] = 0 return emb.to(torch.get_default_dtype()) @torch.no_grad() def forward( self, input_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, past_key_values_length: int = 0, ): if input_ids is not None: bsz, seq_len = input_ids.size() # Create the position ids from the input token ids. Any padded tokens remain padded. position_ids = self.create_position_ids_from_input_ids( input_ids, self.padding_idx, past_key_values_length ).to(input_ids.device) else: bsz, seq_len = inputs_embeds.size()[:-1] position_ids = self.create_position_ids_from_inputs_embeds( inputs_embeds, past_key_values_length, self.padding_idx ) # expand embeddings if needed max_pos = self.padding_idx + 1 + seq_len + past_key_values_length if max_pos > self.weights.size(0): self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx) return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach() @staticmethod def create_position_ids_from_inputs_embeds(inputs_embeds, past_key_values_length, padding_idx): """ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids. Args: inputs_embeds: torch.Tensor Returns: torch.Tensor """ input_shape = inputs_embeds.size()[:-1] sequence_length = input_shape[1] position_ids = torch.arange( padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device ) return position_ids.unsqueeze(0).expand(input_shape).contiguous() + past_key_values_length @staticmethod # Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings.create_position_ids_from_input_ids def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0): """ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`. Args: x: torch.Tensor x: Returns: torch.Tensor """ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA. mask = input_ids.ne(padding_idx).int() incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask return incremental_indices.long() + padding_idx
NllbMoeSinusoidalPositionalEmbedding
python
PyCQA__pylint
tests/functional/u/unnecessary/unnecessary_dunder_call.py
{ "start": 1409, "end": 1864 }
class ____(dict): def __init__(self) -> None: super().__init__() self._entry_ids = {} def __setitem__(self, key, entry) -> None: super().__setitem__(key, entry) self._entry_ids.__setitem__(entry.id, entry) self._entry_ids.__delitem__(entry.id) def __delitem__(self, key: str) -> None: entry = self[key] self._entry_ids.__delitem__(entry.id) super().__delitem__(key)
CustomRegistry
python
h5py__h5py
h5py/tests/test_dataset.py
{ "start": 30153, "end": 30523 }
class ____(BaseDataset): """ Feature: Datasets can use shuffling filter """ def test_shuffle(self): """ Enable shuffle filter """ dset = self.f.create_dataset(make_name(), (20, 30), shuffle=True) self.assertTrue(dset.shuffle) @ut.skipIf('fletcher32' not in h5py.filters.encode, "FLETCHER32 is not installed")
TestCreateShuffle
python
readthedocs__readthedocs.org
readthedocs/builds/views.py
{ "start": 1537, "end": 2664 }
class ____( FilterContextMixin, ProjectSpamMixin, BuildBase, ListView, ): filterset_class = BuildListFilter def _get_versions(self, project): project.versions(manager=INTERNAL).public( user=self.request.user, ) def get_project(self): # Call ``.get_queryset()`` to get the current project from ``kwargs`` self.get_queryset() return self.project def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) active_builds = ( self.get_queryset() .exclude( state__in=BUILD_FINAL_STATES, ) .values("id") ) context["project"] = self.project context["active_builds"] = active_builds context["versions"] = self._get_versions(self.project) builds = self.get_queryset() context["filter"] = self.get_filterset( queryset=builds, project=self.project, ) builds = self.get_filtered_queryset() context["build_qs"] = builds return context
BuildList
python
bokeh__bokeh
src/bokeh/models/tools.py
{ "start": 77169, "end": 82857 }
class ____(EditTool, Drag, Tap): ''' *toolbar icon*: |line_edit_icon| The LineEditTool allows editing the intersection points of one or more ``Line`` glyphs. Glyphs to be edited are defined via the ``renderers`` property and a renderer for the intersections is set via the ``intersection_renderer`` property (must render a point-like Glyph (a subclass of ``XYGlyph``). The tool will modify the columns on the data source corresponding to the ``x`` and ``y`` values of the glyph. Any additional columns in the data source will be padded with the declared ``empty_value``, when adding a new point. The supported actions include: * Show intersections: press an existing line * Move point: Drag an existing point and let go of the mouse button to release it. .. |line_edit_icon| image:: /_images/icons/line-edit.svg :height: 24px :alt: Icon of a line with a point on it with an arrow pointing at it representing the line-edit tool in the toolbar. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) renderers = List(GlyphRendererOf(Line), help=""" A list of renderers corresponding to glyphs that may be edited. """) intersection_renderer = GlyphRendererOf(LineGlyph)(help=""" The renderer used to render the intersections of a selected line """) dimensions = Enum(Dimensions, default="both", help=""" Which dimensions this edit tool is constrained to act in. By default the line edit tool allows moving points in any dimension, but can be configured to only allow horizontal movement across the width of the plot, or vertical across the height of the plot. """) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- Tool.register_alias("pan", lambda: PanTool(dimensions="both")) Tool.register_alias("xpan", lambda: PanTool(dimensions="width")) Tool.register_alias("ypan", lambda: PanTool(dimensions="height")) Tool.register_alias("pan_left", lambda: ClickPanTool(direction="left")) Tool.register_alias("pan_right", lambda: ClickPanTool(direction="right")) Tool.register_alias("pan_up", lambda: ClickPanTool(direction="up")) Tool.register_alias("pan_down", lambda: ClickPanTool(direction="down")) Tool.register_alias("pan_west", lambda: ClickPanTool(direction="west")) Tool.register_alias("pan_east", lambda: ClickPanTool(direction="east")) Tool.register_alias("pan_north", lambda: ClickPanTool(direction="north")) Tool.register_alias("pan_south", lambda: ClickPanTool(direction="south")) Tool.register_alias("xwheel_pan", lambda: WheelPanTool(dimension="width")) Tool.register_alias("ywheel_pan", lambda: WheelPanTool(dimension="height")) Tool.register_alias("wheel_zoom", lambda: WheelZoomTool(dimensions="both")) Tool.register_alias("xwheel_zoom", lambda: WheelZoomTool(dimensions="width")) Tool.register_alias("ywheel_zoom", lambda: WheelZoomTool(dimensions="height")) Tool.register_alias("zoom_in", lambda: ZoomInTool(dimensions="both")) Tool.register_alias("xzoom_in", lambda: ZoomInTool(dimensions="width")) Tool.register_alias("yzoom_in", lambda: ZoomInTool(dimensions="height")) Tool.register_alias("zoom_out", lambda: ZoomOutTool(dimensions="both")) Tool.register_alias("xzoom_out", lambda: ZoomOutTool(dimensions="width")) Tool.register_alias("yzoom_out", lambda: ZoomOutTool(dimensions="height")) Tool.register_alias("click", lambda: TapTool(behavior="inspect")) Tool.register_alias("tap", lambda: TapTool()) Tool.register_alias("doubletap", lambda: TapTool(gesture="doubletap")) Tool.register_alias("crosshair", lambda: CrosshairTool()) Tool.register_alias("xcrosshair", lambda: CrosshairTool(dimensions="width")) Tool.register_alias("ycrosshair", lambda: CrosshairTool(dimensions="height")) Tool.register_alias("box_select", lambda: BoxSelectTool()) Tool.register_alias("xbox_select", lambda: BoxSelectTool(dimensions="width")) Tool.register_alias("ybox_select", lambda: BoxSelectTool(dimensions="height")) Tool.register_alias("poly_select", lambda: PolySelectTool()) Tool.register_alias("lasso_select", lambda: LassoSelectTool()) Tool.register_alias("box_zoom", lambda: BoxZoomTool(dimensions="both")) Tool.register_alias("xbox_zoom", lambda: BoxZoomTool(dimensions="width")) Tool.register_alias("ybox_zoom", lambda: BoxZoomTool(dimensions="height")) Tool.register_alias("auto_box_zoom", lambda: BoxZoomTool(dimensions="auto")) Tool.register_alias("save", lambda: SaveTool()) Tool.register_alias("copy", lambda: CopyTool()) Tool.register_alias("undo", lambda: UndoTool()) Tool.register_alias("redo", lambda: RedoTool()) Tool.register_alias("reset", lambda: ResetTool()) Tool.register_alias("help", lambda: HelpTool()) Tool.register_alias("examine", lambda: ExamineTool()) Tool.register_alias("fullscreen", lambda: FullscreenTool()) Tool.register_alias("box_edit", lambda: BoxEditTool()) Tool.register_alias("line_edit", lambda: LineEditTool()) Tool.register_alias("point_draw", lambda: PointDrawTool()) Tool.register_alias("poly_draw", lambda: PolyDrawTool()) Tool.register_alias("poly_edit", lambda: PolyEditTool()) Tool.register_alias("freehand_draw", lambda: FreehandDrawTool()) Tool.register_alias("hover", lambda: HoverTool(tooltips=[ ("index", "$index"), ("data (x, y)", "($x, $y)"), ("screen (x, y)", "($sx, $sy)"), ]))
LineEditTool
python
airbytehq__airbyte
airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py
{ "start": 8876, "end": 9391 }
class ____(IssueWatchers, GeneratorMixin): """ https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issue-watchers/#api-rest-api-3-issue-issueidorkey-watchers-post """ def generate(self): issues_stream = Issues(authenticator=self._session.auth, domain=self._domain) for issue in issues_stream.read_records(sync_mode=SyncMode.full_refresh): payload = None self.generate_record(payload, stream_slice={"key": issue["key"]})
IssueWatchersGenerator
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/cachecontrol/adapter.py
{ "start": 810, "end": 6355 }
class ____(HTTPAdapter): invalidating_methods = {"PUT", "PATCH", "DELETE"} def __init__( self, cache: BaseCache | None = None, cache_etags: bool = True, controller_class: type[CacheController] | None = None, serializer: Serializer | None = None, heuristic: BaseHeuristic | None = None, cacheable_methods: Collection[str] | None = None, *args: Any, **kw: Any, ) -> None: super().__init__(*args, **kw) self.cache = DictCache() if cache is None else cache self.heuristic = heuristic self.cacheable_methods = cacheable_methods or ("GET",) controller_factory = controller_class or CacheController self.controller = controller_factory( self.cache, cache_etags=cache_etags, serializer=serializer ) def send( self, request: PreparedRequest, stream: bool = False, timeout: None | float | tuple[float, float] | tuple[float, None] = None, verify: bool | str = True, cert: (None | bytes | str | tuple[bytes | str, bytes | str]) = None, proxies: Mapping[str, str] | None = None, cacheable_methods: Collection[str] | None = None, ) -> Response: """ Send a request. Use the request information to see if it exists in the cache and cache the response if we need to and can. """ cacheable = cacheable_methods or self.cacheable_methods if request.method in cacheable: try: cached_response = self.controller.cached_request(request) except zlib.error: cached_response = None if cached_response: return self.build_response(request, cached_response, from_cache=True) # check for etags and add headers if appropriate request.headers.update(self.controller.conditional_headers(request)) resp = super().send(request, stream, timeout, verify, cert, proxies) return resp def build_response( self, request: PreparedRequest, response: HTTPResponse, from_cache: bool = False, cacheable_methods: Collection[str] | None = None, ) -> Response: """ Build a response by making a request or using the cache. This will end up calling send and returning a potentially cached response """ cacheable = cacheable_methods or self.cacheable_methods if not from_cache and request.method in cacheable: # Check for any heuristics that might update headers # before trying to cache. if self.heuristic: response = self.heuristic.apply(response) # apply any expiration heuristics if response.status == 304: # We must have sent an ETag request. This could mean # that we've been expired already or that we simply # have an etag. In either case, we want to try and # update the cache if that is the case. cached_response = self.controller.update_cached_response( request, response ) if cached_response is not response: from_cache = True # We are done with the server response, read a # possible response body (compliant servers will # not return one, but we cannot be 100% sure) and # release the connection back to the pool. response.read(decode_content=False) response.release_conn() response = cached_response # We always cache the 301 responses elif int(response.status) in PERMANENT_REDIRECT_STATUSES: self.controller.cache_response(request, response) else: # Wrap the response file with a wrapper that will cache the # response when the stream has been consumed. response._fp = CallbackFileWrapper( # type: ignore[assignment] response._fp, # type: ignore[arg-type] functools.partial( self.controller.cache_response, request, response ), ) if response.chunked: super_update_chunk_length = response._update_chunk_length def _update_chunk_length(self: HTTPResponse) -> None: super_update_chunk_length() if self.chunk_left == 0: self._fp._close() # type: ignore[union-attr] response._update_chunk_length = types.MethodType( # type: ignore[method-assign] _update_chunk_length, response ) resp: Response = super().build_response(request, response) # type: ignore[no-untyped-call] # See if we should invalidate the cache. if request.method in self.invalidating_methods and resp.ok: assert request.url is not None cache_url = self.controller.cache_url(request.url) self.cache.delete(cache_url) # Give the request a from_cache attr to let people use it resp.from_cache = from_cache # type: ignore[attr-defined] return resp def close(self) -> None: self.cache.close() super().close() # type: ignore[no-untyped-call]
CacheControlAdapter
python
PrefectHQ__prefect
tests/_internal/compatibility/test_async_dispatch.py
{ "start": 6391, "end": 8685 }
class ____: def test_dispatches_to_async_in_async_flow(self): """ Verify that async_dispatch dispatches to async in async flow The test function is sync, but the flow is async, so we should dispatch to the async implementation. """ async def my_afunction() -> str: return "async" @async_dispatch(my_afunction) def my_function() -> str: return "sync" @flow async def my_flow() -> str: return await my_function() assert run_coro_as_sync(my_flow()) == "async" async def test_dispatches_to_sync_in_sync_flow(self): """ Verify that async_dispatch dispatches to sync in sync flow The test function is async, but the flow is sync, so we should dispatch to the sync implementation. """ async def my_afunction() -> str: return "async" @async_dispatch(my_afunction) def my_function() -> str: return "sync" @flow def my_flow() -> str: return my_function() assert my_flow() == "sync" def test_dispatches_to_async_in_an_async_task(self): """ Verify that async_dispatch dispatches to async in an async task The test function is sync, but the task is async, so we should dispatch to the async implementation. """ async def my_afunction() -> str: return "async" @async_dispatch(my_afunction) def my_function() -> str: return "sync" @task async def my_task() -> str: return await my_function() assert run_coro_as_sync(my_task()) == "async" async def test_dispatches_to_sync_in_a_sync_task(self): """ Verify that async_dispatch dispatches to sync in a sync task The test function is async, but the task is sync, so we should dispatch to the sync implementation. """ async def my_afunction() -> str: return "async" @async_dispatch(my_afunction) def my_function() -> str: return "sync" @task def my_task() -> str: return my_function() assert my_task() == "sync"
TestIsInARunContext
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 3091, "end": 8265 }
class ____(TestCase): def count_unique_get_attr_nodes(self, gm, args, expected): subgraph_attr_names = set() for node in gm.graph.nodes: if node.op == "get_attr": subgraph_attr_names.add(node.target) self.assertEqual(len(subgraph_attr_names), expected) def test_simple(self): @nested_compile_region def gn(x, y): return torch.mul(x, y) def fn(x, y): return gn(x, y) x = torch.randn(8, requires_grad=True) y = torch.randn(8, requires_grad=True) ref = fn(x, y) x_clone = x.detach().clone().requires_grad_(True) y_clone = y.detach().clone().requires_grad_(True) res = torch.compile(fn, backend="inductor", fullgraph=True)(x_clone, y_clone) # Run backward ref.sum().backward() res.sum().backward() self.assertEqual(ref, res) self.assertEqual(x.grad, x_clone.grad) self.assertEqual(y.grad, y_clone.grad) def test_module_forward(self): class Mod(torch.nn.Module): def __init__(self): super().__init__() self.c = 5 @nested_compile_region def forward(self, x, y): return torch.mul(x, y).sin() + self.c mod = Mod() def fn(x, y): return mod(x, y) + mod(x, y) x = torch.randn(8, requires_grad=True) y = torch.randn(8, requires_grad=True) ref = fn(x, y) x_clone = x.detach().clone().requires_grad_(True) y_clone = y.detach().clone().requires_grad_(True) res = torch.compile(fn, backend="inductor", fullgraph=True)(x_clone, y_clone) # Run backward ref.sum().backward() res.sum().backward() self.assertEqual(ref, res) self.assertEqual(x.grad, x_clone.grad) self.assertEqual(y.grad, y_clone.grad) def test_gen_schema(self): class Mod(torch.nn.Module): def __init__(self): super().__init__() self.c = 5 @nested_compile_region def forward(self, x, y): return torch.mul(x, y).sin() + self.c mod = Mod() def fn(x, y): return mod(x, y) + mod(x, y) x = torch.randn(8, requires_grad=True) y = torch.randn(8, requires_grad=True) x_clone = x.detach().clone().requires_grad_(True) y_clone = y.detach().clone().requires_grad_(True) backend = AotEagerAndRecordGraphs() res = torch.compile(fn, backend=backend, fullgraph=True)(x_clone, y_clone) res.sum().backward() self.assertEqual(len(backend.fw_graphs), 1) self.assertEqual(len(backend.bw_graphs), 1) fw_schema = find_hop_schema( backend.fw_graphs[0], torch.ops.higher_order.invoke_subgraph ) bw_schema = find_hop_schema( backend.bw_graphs[0], torch.ops.higher_order.invoke_subgraph ) self.assertExpectedInline( str(fw_schema[0]), """invoke_subgraph(Any subgraph, str identifier, Tensor arg0, Tensor arg1) -> (Tensor, Tensor, Tensor)""", ) self.assertExpectedInline( str(fw_schema[1]), """invoke_subgraph(Any subgraph, str identifier, Tensor arg0, Tensor arg1) -> (Tensor, Tensor, Tensor)""", ) self.assertExpectedInline( str(bw_schema[0]), """invoke_subgraph(Any subgraph, str identifier, Tensor arg0, Tensor arg1, Tensor arg2) -> (Tensor, Tensor)""", ) self.assertExpectedInline( str(bw_schema[1]), """invoke_subgraph(Any subgraph, str identifier, Tensor arg0, Tensor arg1, Tensor arg2) -> (Tensor, Tensor)""", ) def test_gen_schema_with_buffer_mutation(self): class Mod(torch.nn.Module): def __init__(self): super().__init__() self.c = 5 self.register_buffer("buf", torch.ones(8, requires_grad=False)) @nested_compile_region def forward(self, x, y): self.buf.add_(1) return torch.mul(x, y).sin() + self.c + self.buf mod_ref = Mod() mod = Mod() def fn(mod, x, y): return mod(x, y) + mod(x, y) x = torch.randn(8, requires_grad=True) y = torch.randn(8, requires_grad=True) ref = fn(mod_ref, x, y) x_clone = x.detach().clone().requires_grad_(True) y_clone = y.detach().clone().requires_grad_(True) backend = EagerAndRecordGraphs() with ( torch.no_grad(), ): res = torch.compile(fn, backend=backend, fullgraph=True)( mod, x_clone, y_clone ) self.assertEqual(len(backend.graphs), 1) fw_schema = find_hop_schema( backend.graphs[0], torch.ops.higher_order.invoke_subgraph ) if not TEST_WITH_CROSSREF: self.assertExpectedInline( normalize_gm(backend.graphs[0].print_readable(print_output=False)), """\
TestInvokeSubgraphCompile
python
scipy__scipy
benchmarks/benchmarks/array_api.py
{ "start": 202, "end": 967 }
class ____(XPBenchmark): def setup(self, backend): def f(x): _ = array_namespace(x) return x super().setup(backend, f) self.x = self.synchronize(self.xp.empty(0)) # Populate @lru_cache and jax.jit. Note that this benefits all backends. self.func(self.x) def time_array_namespace(self, backend): """scipy wrapper around array_api_compat.array_namespace""" array_namespace(self.x) def time_compat_namespace(self, backend): """Bare array_api_compat.array_namespace""" compat_namespace(self.x) def time_trivial_func(self, backend): """Trivial function that internally calls `xp=array_namespace(*args)`""" self.func(self.x)
ArrayNamespace
python
doocs__leetcode
solution/2000-2099/2078.Two Furthest Houses With Different Colors/Solution.py
{ "start": 0, "end": 275 }
class ____: def maxDistance(self, colors: List[int]) -> int: ans, n = 0, len(colors) for i in range(n): for j in range(i + 1, n): if colors[i] != colors[j]: ans = max(ans, abs(i - j)) return ans
Solution
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 60142, "end": 60492 }
class ____(BaseModel): usage: Optional["Usage"] = Field(default=None, description="") time: Optional[float] = Field(default=None, description="Time spent to process this request") status: Optional[str] = Field(default=None, description="") result: Optional["CollectionsResponse"] = Field(default=None, description="")
InlineResponse2003
python
numba__numba
numba/tests/test_complex.py
{ "start": 253, "end": 2657 }
class ____(object): def basic_values(self): reals = [-0.0, +0.0, 1, -1, +1.5, -3.5, float('-inf'), float('+inf')] if sys.platform != 'win32': reals += [float('nan')] return [complex(x, y) for x, y in itertools.product(reals, reals)] def more_values(self): reals = [-0.0, +0.0, 1, -1, -math.pi, +math.pi, float('-inf'), float('+inf')] if sys.platform != 'win32': reals += [float('nan')] return [complex(x, y) for x, y in itertools.product(reals, reals)] def non_nan_values(self): reals = [-0.0, +0.0, 1, -1, -math.pi, +math.pi, float('inf'), float('-inf')] return [complex(x, y) for x, y in itertools.product(reals, reals)] def run_unary(self, pyfunc, x_types, x_values, ulps=1, abs_tol=None, flags=enable_pyobj_flags): for tx in x_types: cfunc = jit((tx,), **flags)(pyfunc) prec = 'single' if tx in (types.float32, types.complex64) else 'double' for vx in x_values: try: expected = pyfunc(vx) except ValueError as e: self.assertIn("math domain error", str(e)) continue got = cfunc(vx) msg = 'for input %r with prec %r' % (vx, prec) self.assertPreciseEqual(got, expected, prec=prec, ulps=ulps, abs_tol=abs_tol, msg=msg) def run_binary(self, pyfunc, value_types, values, ulps=1, flags=enable_pyobj_flags): for tx, ty in value_types: cfunc = jit((tx, ty), **flags)(pyfunc) prec = ('single' if set([tx, ty]) & set([types.float32, types.complex64]) else 'double') for vx, vy in values: try: expected = pyfunc(vx, vy) except ValueError as e: self.assertIn("math domain error", str(e)) continue except ZeroDivisionError: continue got = cfunc(vx, vy) msg = 'for input %r with prec %r' % ((vx, vy), prec) self.assertPreciseEqual(got, expected, prec=prec, ulps=ulps, msg=msg)
BaseComplexTest
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 55612, "end": 55956 }
class ____(BaseModel): usage: Optional["Usage"] = Field(default=None, description="") time: Optional[float] = Field(default=None, description="Time spent to process this request") status: Optional[str] = Field(default=None, description="") result: Optional[List["Record"]] = Field(default=None, description="")
InlineResponse20013