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
getsentry__sentry
src/sentry/workflow_engine/endpoints/organization_test_fire_action.py
{ "start": 1868, "end": 1962 }
class ____(TypedDict): actions: list[str] @region_silo_endpoint
TestFireActionErrorsResponse
python
wandb__wandb
wandb/vendor/pygments/lexers/dsls.py
{ "start": 7519, "end": 10542 }
class ____(RegexLexer): """ For `Bro <http://bro-ids.org/>`_ scripts. .. versionadded:: 1.5 """ name = 'Bro' aliases = ['bro'] filenames = ['*.bro'] _hex = r'[0-9a-fA-F_]' _float = r'((\d*\.?\d+)|(\d+\.?\d*))([eE][-+]?\d+)?' _h = r'[A-Za-z0-9][-A-Za-z0-9]*' tokens = { ...
BroLexer
python
nedbat__coveragepy
tests/test_plugins.py
{ "start": 844, "end": 1056 }
class ____(TPluginConfig): """A plugin configure thing when we don't really need one.""" def get_plugin_options(self, plugin: str) -> TConfigSectionOut: return {} # pragma: never called
NullConfig
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataplex.py
{ "start": 110183, "end": 114896 }
class ____(DataplexCatalogBaseOperator): """ Update an EntryGroup resource. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:DataplexCatalogUpdateEntryGroupOperator` :param project_id: Required. The ID of the Google Cloud pro...
DataplexCatalogUpdateEntryGroupOperator
python
Netflix__metaflow
metaflow/parameters.py
{ "start": 3214, "end": 8843 }
class ____(object): """ This a wrapper object for a user-defined function that is called at deploy time to populate fields in a Parameter. The wrapper is needed to make Click show the actual value returned by the function instead of a function pointer in its help text. Also, this object curries ...
DeployTimeField
python
Lightning-AI__lightning
tests/tests_pytorch/accelerators/test_xla.py
{ "start": 1502, "end": 4046 }
class ____(BoringModel): def __init__(self): super(BoringModel, self).__init__() self.layer_1 = nn.Linear(32, 10, bias=False) self.layer_2 = nn.Linear(10, 32, bias=False) self.layer_3 = nn.Linear(32, 10, bias=False) self.layer_3.weight = self.layer_1.weight def forward(s...
WeightSharingModule
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/uninitialized_attributes.py
{ "start": 58, "end": 123 }
class ____(Base): attr3: int #: docstring attr4: str
Derived
python
tensorflow__tensorflow
tensorflow/python/keras/layers/legacy_rnn/rnn_cell_wrapper_impl.py
{ "start": 13668, "end": 16940 }
class ____(object): """RNNCell wrapper that ensures cell inputs are added to the outputs.""" def __init__(self, cell, residual_fn=None, **kwargs): """Constructs a `ResidualWrapper` for `cell`. Args: cell: An instance of `RNNCell`. residual_fn: (Optional) The function to map raw cell inputs and...
ResidualWrapperBase
python
django__django
tests/aggregation_regress/models.py
{ "start": 3288, "end": 3603 }
class ____(models.Model): recipe = models.ForeignKey("RecipeUnmanaged", models.CASCADE) author = models.ForeignKey( AuthorUnmanaged, models.CASCADE, db_column="authorproxy_id" ) class Meta: managed = False db_table = Recipe.tasters.through._meta.db_table
RecipeTasterUnmanaged
python
anthropics__anthropic-sdk-python
src/anthropic/resources/beta/beta.py
{ "start": 4685, "end": 5342 }
class ____: def __init__(self, beta: Beta) -> None: self._beta = beta @cached_property def models(self) -> ModelsWithStreamingResponse: return ModelsWithStreamingResponse(self._beta.models) @cached_property def messages(self) -> MessagesWithStreamingResponse: return Message...
BetaWithStreamingResponse
python
scipy__scipy
scipy/_lib/tests/test_bunch.py
{ "start": 279, "end": 6389 }
class ____: # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Tests with Result # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def setup_method(self): # Set up an instance of Result. self.result = Result(x=1, y=2, z=3, w=99, beta=0.5) ...
TestMakeTupleBunch
python
coleifer__peewee
playhouse/pool.py
{ "start": 9700, "end": 10017 }
class ____(PooledDatabase, MySQLDatabase): def _is_closed(self, conn): if self.server_version[0] == 8: args = () else: args = (False,) try: conn.ping(*args) except: return True else: return False
PooledMySQLDatabase
python
RaRe-Technologies__gensim
gensim/test/test_poincare.py
{ "start": 1515, "end": 10813 }
class ____(unittest.TestCase): def setUp(self): self.data = PoincareRelations(datapath('poincare_hypernyms.tsv')) self.data_large = PoincareRelations(datapath('poincare_hypernyms_large.tsv')) def models_equal(self, model_1, model_2): self.assertEqual(len(model_1.kv), len(model_2.kv)) ...
TestPoincareModel
python
spack__spack
lib/spack/spack/util/elf.py
{ "start": 564, "end": 780 }
class ____(NamedTuple): sh_name: int sh_type: int sh_flags: int sh_addr: int sh_offset: int sh_size: int sh_link: int sh_info: int sh_addralign: int sh_entsize: int
SectionHeader
python
docker__docker-py
tests/unit/utils_test.py
{ "start": 9235, "end": 12364 }
class ____(unittest.TestCase): def test_parse_host(self): invalid_hosts = [ '0.0.0.0', 'tcp://', 'udp://127.0.0.1', 'udp://127.0.0.1:2375', 'ssh://:22/path', 'tcp://netloc:3333/path?q=1', 'unix:///sock/path#fragment', ...
ParseHostTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/util_test.py
{ "start": 21147, "end": 22716 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testNonEmptyConstantTensor(self): x = array_ops.zeros((2, 3, 4)) shape = du.prefer_static_shape(x) self.assertIsInstance(shape, np.ndarray) self.assertAllEqual(np.array([2, 3, 4]), shape) @test_util.run_deprecated_v1 def testEmptyCons...
PreferStaticShapeTest
python
huggingface__transformers
src/transformers/models/splinter/modeling_splinter.py
{ "start": 8443, "end": 9099 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_f...
SplinterIntermediate
python
has2k1__plotnine
tests/test_geom_smooth.py
{ "start": 6025, "end": 7057 }
class ____: p = ggplot(data, aes("x", "y")) + geom_point() def test_lm(self): p = self.p + stat_smooth( method="lm", formula="y ~ np.sin(x)", fill="red", se=True ) assert p == "lm_formula" def test_lm_weights(self): p = ( self.p + aes(wei...
TestFormula
python
huggingface__transformers
tests/models/auto/test_processor_auto.py
{ "start": 20998, "end": 27685 }
class ____(unittest.TestCase): vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] @classmethod def setUpClass(cls): cls._token = TOKEN def test_push_to_hub_via_save_pretrained(self): with TemporaryHubRepo(token=self._token) as tmp_repo: processor =...
ProcessorPushToHubTester
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/response_model/tutorial001_py310.py
{ "start": 99, "end": 1050 }
class ____(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: int | None = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": ...
Hero
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0124_remove_zh_locale.py
{ "start": 150, "end": 14444 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0123_deprecate_old_vcs"), ] operations = [ migrations.AlterField( model_name="historicalproject", name="language", field=models.CharField( cho...
Migration
python
kamyu104__LeetCode-Solutions
Python/minimum-weighted-subgraph-with-the-required-paths-ii.py
{ "start": 786, "end": 2703 }
class ____(object): def minimumWeight(self, edges, queries): """ :type edges: List[List[int]] :type queries: List[List[int]] :rtype: List[int] """ def iter_dfs(): lookup = [False]*len(adj) lookup2 = [[] for _ in xrange(len(adj))] fo...
Solution
python
networkx__networkx
networkx/exception.py
{ "start": 464, "end": 551 }
class ____(Exception): """Base class for exceptions in NetworkX."""
NetworkXException
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_assorted_poly.py
{ "start": 72935, "end": 78939 }
class ____(AssertsCompiledSQL, fixtures.TestBase): """tests for #8168 which was fixed by #8456""" __dialect__ = "default" @testing.fixture def mapping(self, decl_base): Base = decl_base def go(scenario, use_poly, use_poly_on_retailer): class Customer(Base): ...
Issue8168Test
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/sqltypes.py
{ "start": 120997, "end": 121182 }
class ____(BigInteger): """The SQL BIGINT type. .. seealso:: :class:`_types.BigInteger` - documentation for the base type. """ __visit_name__ = "BIGINT"
BIGINT
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_selection.py
{ "start": 43391, "end": 44027 }
class ____(AssetSelection): """Used to represent a UI asset selection by column tag. This should not be resolved against an in-process asset graph. """ key: str value: str def resolve_inner( self, asset_graph: BaseAssetGraph, allow_missing: bool ) -> AbstractSet[AssetKey]: ...
ColumnTagAssetSelection
python
dagster-io__dagster
python_modules/libraries/dagster-powerbi/dagster_powerbi/resource.py
{ "start": 16716, "end": 17940 }
class ____(StateBackedDefinitionsLoader[PowerBIWorkspaceData]): workspace: PowerBIWorkspace translator: DagsterPowerBITranslator use_workspace_scan: bool @property def defs_key(self) -> str: return f"{POWER_BI_RECONSTRUCTION_METADATA_KEY_PREFIX}/{self.workspace.workspace_id}" def fetch...
PowerBIWorkspaceDefsLoader
python
numba__numba
numba/core/datamodel/models.py
{ "start": 33869, "end": 34202 }
class ____(StructModel): def __init__(self, dmm, fe_type): members = [('index', types.EphemeralPointer(types.intp)), ('tuple', fe_type.container,)] super(UniTupleIter, self).__init__(dmm, fe_type, members) @register_default(types.misc.SliceLiteral) @register_default(types.SliceT...
UniTupleIter
python
pydata__xarray
xarray/namedarray/_typing.py
{ "start": 565, "end": 1179 }
class ____(Enum): token: Final = 0 _default = Default.token # https://stackoverflow.com/questions/74633074/how-to-type-hint-a-generic-numpy-array _T_co = TypeVar("_T_co", covariant=True) _dtype = np.dtype _DType = TypeVar("_DType", bound=np.dtype[Any]) _DType_co = TypeVar("_DType_co", covariant=True, bound=np.d...
Default
python
faif__python-patterns
patterns/structural/mvc.py
{ "start": 246, "end": 664 }
class ____(ABC): """The Model is the data layer of the application.""" @abstractmethod def __iter__(self) -> Any: pass @abstractmethod def get(self, item: str) -> dict: """Returns an object with a .items() call method that iterates over key,value pairs of its information.""...
Model
python
tornadoweb__tornado
tornado/template.py
{ "start": 21795, "end": 22661 }
class ____(_Node): def __init__(self, method: str, line: int, body: _Node) -> None: self.method = method self.line = line self.body = body def each_child(self) -> Iterable["_Node"]: return (self.body,) def generate(self, writer: "_CodeWriter") -> None: method_name =...
_ApplyBlock
python
ansible__ansible
lib/ansible/_internal/_ssh/_ssh_agent.py
{ "start": 7684, "end": 10326 }
class ____(Msg): @staticmethod def from_private_key(private_key: CryptoPrivateKey) -> PrivateKeyMsg: match private_key: case RSAPrivateKey(): rsa_pn: RSAPrivateNumbers = private_key.private_numbers() return RSAPrivateKeyMsg( KeyAlgo.RSA, ...
PrivateKeyMsg
python
pytorch__pytorch
torch/storage.py
{ "start": 51308, "end": 52396 }
class ____(TypedStorage, metaclass=_LegacyStorageMeta): @classmethod def _new_shared(cls, size): # type: ignore[override] """Create a new storage in shared memory with the same data type.""" untyped_storage = torch.UntypedStorage._new_shared(size * cls()._element_size()) return cls(wrap...
_LegacyStorage
python
joke2k__faker
tests/providers/test_automotive.py
{ "start": 12161, "end": 12767 }
class ____(_SimpleAutomotiveTestMixin): """Test tr_TR automotive provider methods""" license_plate_pattern: Pattern = re.compile( r"\d{2} [A-Z] \d{4}|" r"\d{2} [A-Z] \d{5}|" r"\d{2} [A-Z]{2} \d{3}|" r"\d{2} [A-Z]{2} \d{4}|" r"\d{2} [A-Z]{3} \d{2}|" r"\d{2} [A-Z]{...
TestTrTr
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 33180, "end": 33491 }
class ____(Operator): __slots__ = () _description = "modulus" _pretty = "%" def _op(self, left, right): if not right: raise ZeroDivisionException("Modulo by zero") value = abs(left) % abs(right) if left < 0: value = -value return value
Mod
python
google__flatbuffers
tests/py_test.py
{ "start": 4044, "end": 5193 }
class ____(unittest.TestCase): def test_wire_format(self): # Verify that using the generated Python code builds a buffer without # returning errors, and is interpreted correctly, for size prefixed # representation and regular: for sizePrefix in [True, False]: for file_identifier in [None, b'MON...
TestWireFormat
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 57384, "end": 57925 }
class ____(PrefectFilterBaseModel): """Filter by `BlockSchema.block_type_id`.""" any_: Optional[list[UUID]] = Field( default=None, description="A list of block type ids to include" ) def _get_filter_list( self, db: "PrefectDBInterface" ) -> Iterable[sa.ColumnExpressionArgument[bool...
BlockSchemaFilterBlockTypeId
python
getsentry__sentry
tests/sentry/tasks/test_post_process.py
{ "start": 87948, "end": 89734 }
class ____(BasePostProgressGroupMixin): def assert_organization_key(self, organization: Organization, exists: bool) -> None: key = get_organization_bucket_key(organization) cluster = get_cluster() assert exists == cluster.sismember(key, str(organization.id)) def test_uptime_detection_fe...
DetectBaseUrlsForUptimeTestMixin
python
django__django
django/contrib/postgres/fields/hstore.py
{ "start": 2529, "end": 2875 }
class ____(Transform): output_field = TextField() def __init__(self, key_name, *args, **kwargs): super().__init__(*args, **kwargs) self.key_name = key_name def as_sql(self, compiler, connection): lhs, params = compiler.compile(self.lhs) return "(%s -> %%s)" % lhs, (*params,...
KeyTransform
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_escapes03.py
{ "start": 315, "end": 1059 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("escapes03.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.Check encoding of rich strings.""" w...
TestCompareXLSXFiles
python
encode__starlette
starlette/endpoints.py
{ "start": 506, "end": 2153 }
class ____: def __init__(self, scope: Scope, receive: Receive, send: Send) -> None: assert scope["type"] == "http" self.scope = scope self.receive = receive self.send = send self._allowed_methods = [ method for method in ("GET", "HEAD", "POST", "PUT", ...
HTTPEndpoint
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 9573, "end": 9782 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("DISMISSED", "UNVIEWED", "VIEWED") Float = sgqlc.types.Float
FileViewedState
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_selection.py
{ "start": 47326, "end": 48046 }
class ____(AssetSelection): selected_key_prefixes: Sequence[Sequence[str]] include_sources: bool def resolve_inner( self, asset_graph: BaseAssetGraph, allow_missing: bool ) -> AbstractSet[AssetKey]: base_set = ( asset_graph.get_all_asset_keys() if self.include_so...
KeyPrefixesAssetSelection
python
google__jax
jax/experimental/jax2tf/call_tf.py
{ "start": 16180, "end": 16517 }
class ____(effects.Effect): __str__ = lambda _: "CallTfEffect" call_tf_effect = CallTfEffect() effects.lowerable_effects.add_type(CallTfEffect) effects.control_flow_allowed_effects.add_type(CallTfEffect) effects.remat_allowed_effects.add_type(CallTfEffect) effects.custom_derivatives_allowed_effects.add_type(CallTfE...
CallTfEffect
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 154885, "end": 155469 }
class ____(sgqlc.types.Input): """Images attached to the check run output displayed in the GitHub pull request UI. """ __schema__ = github_schema __field_names__ = ("alt", "image_url", "caption") alt = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="alt") """The alternative te...
CheckRunOutputImage
python
dagster-io__dagster
python_modules/dagster/dagster_tests/utils_tests/test_dataloader.py
{ "start": 388, "end": 1025 }
class ____: key: str batch_keys: list[str] @staticmethod async def gen(context: Context, key: str) -> "Thing": return await context.loader.load(key) async def gen_other_thing(self, context: Context): return await context.loader.load(f"{self.key}_other") async def gen_other_oth...
Thing
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 82924, "end": 86529 }
class ____(TypedDict, total=False): type: Required[Literal['function-plain']] function: Required[ValidationFunction] ref: str json_schema_input_schema: CoreSchema metadata: dict[str, Any] serialization: SerSchema def no_info_plain_validator_function( function: NoInfoValidatorFunction, ...
PlainValidatorFunctionSchema
python
getsentry__sentry
tests/sentry/core/endpoints/test_organization_member_details.py
{ "start": 1497, "end": 6939 }
class ____(OrganizationMemberTestBase): def test_me(self) -> None: response = self.get_success_response(self.organization.slug, "me") assert response.data["role"] == "owner" assert response.data["orgRole"] == "owner" assert response.data["user"]["id"] == str(self.user.id) as...
GetOrganizationMemberTest
python
getsentry__sentry
src/sentry/snuba/metrics/mqb_query_transformer.py
{ "start": 878, "end": 18459 }
class ____(Exception): pass def _get_derived_op_metric_field_from_snuba_function(function: Function): if len(function.parameters) == 0 or not isinstance(function.parameters[0], Column): raise MQBQueryTransformationException( "The first parameter of a function should be a column of the metr...
MQBQueryTransformationException
python
bottlepy__bottle
bottle.py
{ "start": 151989, "end": 155611 }
class ____: """ Base class and minimal API for template adapters """ extensions = ['tpl', 'html', 'thtml', 'stpl'] settings = {} # used in prepare() defaults = {} # used in render() def __init__(self, source=None, name=None, lookup=None, ...
BaseTemplate
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_dms.py
{ "start": 24175, "end": 33802 }
class ____: TASK_DATA = { "ReplicationConfigIdentifier": "test-config", "ReplicationConfigArn": "arn:xxxxxx", "SourceEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:RZZK4EZW5UANC7Y3P4E776WHBE", "TargetEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:GVBUJQXJZASXW...
TestDmsDeleteReplicationConfigOperator
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingTypeIs1.py
{ "start": 2095, "end": 2294 }
class ____(str): @classmethod def method1(cls, v: str): if type(v) is cls: reveal_type(v, expected_text="G*") else: reveal_type(v, expected_text="str")
G
python
xlwings__xlwings
xlwings/constants.py
{ "start": 118191, "end": 118309 }
class ____: xlSummaryAbove = 0 # from enum XlSummaryRow xlSummaryBelow = 1 # from enum XlSummaryRow
SummaryRow
python
doocs__leetcode
lcof2/剑指 Offer II 062. 实现前缀树/Solution.py
{ "start": 0, "end": 1041 }
class ____: def __init__(self): self.children = [None] * 26 self.is_end = False def insert(self, word: str) -> None: node = self for c in word: idx = ord(c) - ord('a') if node.children[idx] is None: node.children[idx] = Trie() ...
Trie
python
giampaolo__psutil
scripts/internal/print_dist.py
{ "start": 2064, "end": 3756 }
class ____(Wheel): def platform(self): return "source" def arch(self): return "-" def pyver(self): return "-" def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( 'dir', nargs="?", default="dist", help='dir...
Tarball
python
ray-project__ray
python/ray/_private/thirdparty/pathspec/util.py
{ "start": 15299, "end": 17929 }
class ____(object): """ The :class:`.TreeEntry` class contains information about a file-system entry. """ #: Make the class dict-less. __slots__ = ('_lstat', 'name', 'path', '_stat') def __init__(self, name, path, lstat, stat): """ Initialize the :class:`.TreeEntry` instance. *name* (:class:`str`) is th...
TreeEntry
python
hynek__structlog
src/structlog/stdlib.py
{ "start": 4389, "end": 16284 }
class ____(BoundLoggerBase): """ Python Standard Library version of `structlog.BoundLogger`. Works exactly like the generic one except that it takes advantage of knowing the logging methods in advance. Use it like:: structlog.configure( wrapper_class=structlog.stdlib.BoundLogg...
BoundLogger
python
airbytehq__airbyte
airbyte-integrations/connectors/source-commcare/source_commcare/source.py
{ "start": 3057, "end": 4609 }
class ____(CommcareStream, IncrementalMixin): cursor_field = "indexed_on" _cursor_value = None @property def state(self) -> Mapping[str, Any]: if self._cursor_value: return {self.cursor_field: self._cursor_value} @state.setter def state(self, value: Mapping[str, Any]): ...
IncrementalStream
python
oauthlib__oauthlib
oauthlib/oauth2/rfc6749/clients/mobile_application.py
{ "start": 280, "end": 8874 }
class ____(Client): """A public client utilizing the implicit code grant workflow. A user-agent-based application is a public client in which the client code is downloaded from a web server and executes within a user-agent (e.g. web browser) on the device used by the resource owner. Protocol data...
MobileApplicationClient
python
jazzband__django-simple-history
simple_history/tests/tests/test_models.py
{ "start": 62390, "end": 63320 }
class ____(TestCase): def setUp(self): self.manager1 = Employee.objects.create() self.manager2 = Employee.objects.create() self.employee = Employee.objects.create(manager=self.manager1) self.employee.manager = self.manager2 self.employee.save() self.manager1_id = self...
TestMissingOneToOne
python
PrefectHQ__prefect
src/prefect/server/orchestration/core_policy.py
{ "start": 34907, "end": 38450 }
class ____(FlowRunOrchestrationRule): """ Rejects failed states and schedules a retry if the retry limit has not been reached. This rule rejects transitions into a failed state if `retries` has been set and the run count has not reached the specified limit. The client will be instructed to transiti...
RetryFailedFlows
python
dask__distributed
distributed/scheduler.py
{ "start": 335969, "end": 336882 }
class ____(Exception): def __init__(self, task: Key, last_worker: WorkerState, allowed_failures: int): super().__init__(task, last_worker, allowed_failures) @property def task(self) -> Key: return self.args[0] @property def last_worker(self) -> WorkerState: return self.args...
KilledWorker
python
langchain-ai__langchain
libs/langchain/langchain_classic/evaluation/string_distance/base.py
{ "start": 1668, "end": 4816 }
class ____(Chain): """Shared methods for the rapidfuzz string distance evaluators.""" distance: StringDistance = Field(default=StringDistance.JARO_WINKLER) normalize_score: bool = Field(default=True) """Whether to normalize the score to a value between `0` and `1`. Applies only to the Levenshtein a...
_RapidFuzzChainMixin
python
plotly__plotly.py
plotly/graph_objs/_contourcarpet.py
{ "start": 215, "end": 60525 }
class ____(_BaseTraceType): _parent_path_str = "" _path_str = "contourcarpet" _valid_props = { "a", "a0", "asrc", "atype", "autocolorscale", "autocontour", "b", "b0", "bsrc", "btype", "carpet", "coloraxis", ...
Contourcarpet
python
ray-project__ray
python/ray/_common/tests/test_utils.py
{ "start": 661, "end": 2265 }
class ____: """Tests for the get_or_create_event_loop utility function.""" def test_existing_event_loop(self): # With running event loop expect_loop = asyncio.new_event_loop() expect_loop.set_debug(True) asyncio.set_event_loop(expect_loop) with warnings.catch_warnings():...
TestGetOrCreateEventLoop
python
walkccc__LeetCode
solutions/309. Best Time to Buy and Sell Stock with Cooldown/309.py
{ "start": 0, "end": 267 }
class ____: def maxProfit(self, prices: list[int]) -> int: sell = 0 hold = -math.inf prev = 0 for price in prices: cache = sell sell = max(sell, hold + price) hold = max(hold, prev - price) prev = cache return sell
Solution
python
numpy__numpy
benchmarks/benchmarks/bench_ma.py
{ "start": 52, "end": 394 }
class ____(Benchmark): def setup(self): self.l100 = range(100) self.t100 = ([True] * 100) def time_masked_array(self): np.ma.masked_array() def time_masked_array_l100(self): np.ma.masked_array(self.l100) def time_masked_array_l100_t100(self): np.ma.masked_array...
MA
python
astropy__astropy
astropy/config/paths.py
{ "start": 8122, "end": 10004 }
class ____(_SetTempPath): """ Context manager to set a temporary path for the Astropy config, primarily for use with testing. If the path set by this context manager does not already exist it will be created, if possible. This may also be used as a decorator on a function to set the config pat...
set_temp_config
python
scikit-learn__scikit-learn
sklearn/tests/metadata_routing_common.py
{ "start": 8103, "end": 11019 }
class ____(ClassifierMixin, BaseEstimator): """A classifier consuming metadata. Parameters ---------- registry : list, default=None If a list, the estimator will append itself to the list in order to have a reference to the estimator later on. Since that reference is not require...
ConsumingClassifier
python
allegroai__clearml
clearml/backend_api/services/v2_9/queues.py
{ "start": 45997, "end": 49217 }
class ____(Response): """ Response of queues.get_queue_metrics endpoint. :param queues: List of the requested queues with their metrics. If no queue ids were requested then 'all' queue is returned with the metrics averaged accross all the company queues. :type queues: Sequence[QueueMetr...
GetQueueMetricsResponse
python
boto__boto3
tests/unit/docs/test_attr.py
{ "start": 700, "end": 3335 }
class ____(BaseDocsTest): def setUp(self): super().setUp() self.add_shape( { 'NestedStruct': { 'type': 'structure', 'members': { 'NestedStrAttr': { 'shape': 'String', ...
TestDocumentAttribute
python
pytorch__pytorch
torch/distributed/fsdp/_fully_shard/_fsdp_common.py
{ "start": 2328, "end": 2512 }
class ____(FSDPMeshInfo, DDPMeshInfo): def __post_init__(self): # Calls `FSDPMeshInfo` -> `DDPMeshInfo` -> `DataParallelMeshInfo` super().__post_init__()
HSDPMeshInfo
python
walkccc__LeetCode
solutions/223. Rectangle Area/223.py
{ "start": 0, "end": 329 }
class ____: def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int: x = min(C, G) - max(A, E) if max(A, E) < min(C, G) else 0 y = min(D, H) - max(B, F) if max(B, F) < min(D, H) else 0 return (C - A) * (D - B) + (G - E) * (H - F) - x...
Solution
python
numba__numba
numba/core/types/misc.py
{ "start": 5372, "end": 6863 }
class ____(Type): """ Type class for optional types, i.e. union { some type, None } """ def __init__(self, typ): assert not isinstance(typ, (Optional, NoneType)) typ = unliteral(typ) self.type = typ name = "OptionalType(%s)" % self.type super(Optional, self).__in...
Optional
python
numpy__numpy
tools/swig/test/testVector.py
{ "start": 12482, "end": 12747 }
class ____(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "ulong" self.typeCode = "L" ######################################################################
ulongTestCase
python
Textualize__textual
src/textual/demo/game.py
{ "start": 5995, "end": 7910 }
class ____(containers.Vertical): """An individual tile in the puzzle. A Tile is a container with a static inside it. The static contains the code (as a Rich Syntax object), scrolled so the relevant portion is visible. """ DEFAULT_CSS = """ Tile { position: absolute; Static ...
Tile
python
getsentry__sentry
src/sentry/integrations/vercel/client.py
{ "start": 266, "end": 348 }
class ____(TypedDict): limit: int until: NotRequired[str | None]
_ParamsDict
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 21002, "end": 21470 }
class ____(DagsterError): """Indicates an error while attempting to launch a backfill.""" def __init__(self, *args, **kwargs): from dagster._utils.error import SerializableErrorInfo self.serializable_error_info = check.opt_inst_param( kwargs.pop("serializable_error_info", None), ...
DagsterBackfillFailedError
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/assignment8.py
{ "start": 144, "end": 619 }
class ____: @overload def bar(self, obj: None) -> object: ... @overload def bar(self, obj: object) -> Any: ... def bar(self, obj: object | None) -> Any: pass @staticmethod def baz(): return 3 _T = TypeVar("_T") my_obj: object my_obj = None my_obj = os my_obj = Foo my_o...
Foo
python
facebookresearch__faiss
tests/test_clone.py
{ "start": 297, "end": 2745 }
class ____(unittest.TestCase): """ Test clone_index for various index combinations. """ def do_test_clone(self, factory, with_ids=False): """ Verify that cloning works for a given index type """ d = 32 ds = datasets.SyntheticDataset(d, 1000, 2000, 10) ind...
TestClone
python
eventlet__eventlet
tests/db_pool_test.py
{ "start": 15151, "end": 15648 }
class ____(MysqlConnectionPool, RawConnectionPool, tests.LimitedTestCase): __test__ = True def postgres_requirement(_f): if psycopg2 is None: print("Skipping postgres tests, psycopg2 not importable") return False try: auth = tests.get_database_auth()['psycopg2'].copy() psy...
Test02MysqlRaw
python
kamyu104__LeetCode-Solutions
Python/best-time-to-buy-and-sell-stock-iv.py
{ "start": 3208, "end": 4123 }
class ____(object): def maxProfit(self, k, prices): """ :type k: int :type prices: List[int] :rtype: int """ def maxAtMostNPairsProfit(sprices): profit = 0 for i in xrange(len(prices) - 1): profit += max(0, prices[i + 1] - price...
Solution2
python
scrapy__scrapy
tests/test_engine.py
{ "start": 3431, "end": 6802 }
class ____: """A class to run the crawler and keep track of events occurred""" def __init__(self, spider_class): self.respplug = [] self.reqplug = [] self.reqdropped = [] self.reqreached = [] self.itemerror = [] self.itemresp = [] self.headers = {} ...
CrawlerRun
python
openai__gym
gym/spaces/discrete.py
{ "start": 163, "end": 4476 }
class ____(Space[int]): r"""A space consisting of finitely many elements. This class represents a finite subset of integers, more specifically a set of the form :math:`\{ a, a+1, \dots, a+n-1 \}`. Example:: >>> Discrete(2) # {0, 1} >>> Discrete(3, start=-1) # {-1, 0, 1} ""...
Discrete
python
PyCQA__pylint
tests/functional/r/regression_02/regression_enum_1734.py
{ "start": 241, "end": 653 }
class ____(Enum): LOADED = "loaded", True SETUP_ERROR = "setup_error", True _recoverable: bool def __new__(cls, value: str, recoverable: bool): obj = object.__new__(cls) obj._value_ = value obj._recoverable = recoverable return obj @property def recoverable(sel...
Test
python
dagster-io__dagster
python_modules/libraries/dagster-k8s/dagster_k8s/client.py
{ "start": 2494, "end": 2856 }
class ____(Exception): pass WHITELISTED_TRANSIENT_K8S_STATUS_CODES = [ 503, # Service unavailable 504, # Gateway timeout 500, # Internal server error # typically not transient, but some k8s clusters raise it transiently: https://github.com/aws/containers-roadmap/issues/1810 401, # Authoriz...
DagsterK8sJobStatusException
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/CurvePoint.py
{ "start": 4034, "end": 4689 }
class ____(CurvePoint): """Provides an arrow that points to any specific sample on a PlotCurveItem. Provides properties that can be animated.""" def __init__(self, curve, index=0, pos=None, **opts): CurvePoint.__init__(self, curve, index=index, pos=pos) if opts.get('pxMode', True): ...
CurveArrow
python
pdm-project__pdm
src/pdm/cli/commands/python.py
{ "start": 3568, "end": 8216 }
class ____(BaseCommand): """Install a Python interpreter with PDM""" arguments = (verbose_option,) def add_arguments(self, parser: ArgumentParser) -> None: parser.add_argument( "version", help="The Python version to install (e.g. cpython@3.10.3). If left empty, " ...
InstallCommand
python
walkccc__LeetCode
solutions/3545. Minimum Deletions for At Most K Distinct Characters/3545.py
{ "start": 0, "end": 212 }
class ____: def minDeletion(self, s: str, k: int) -> int: count = collections.Counter(s) if len(count) <= k: return 0 freqs = sorted(count.values()) return sum(freqs[:len(freqs) - k])
Solution
python
pypa__hatch
tests/config/test_model.py
{ "start": 9562, "end": 17154 }
class ____: def test_default(self, default_cache_dir, default_data_dir): config = RootConfig({}) default_cache_directory = str(default_cache_dir) default_data_directory = str(default_data_dir) assert config.dirs.project == config.dirs.project == [] assert config.dirs.env == ...
TestDirs
python
pytorch__pytorch
test/fx/test_fx_split.py
{ "start": 8144, "end": 10675 }
class ____(TestCase): class TestModule(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv = torch.nn.Conv2d(3, 16, 3, stride=1, bias=True) self.relu = torch.nn.ReLU() def forward(self, x): conv = self.conv(x) conv =...
TestSplitOutputType
python
walkccc__LeetCode
solutions/677. Map Sum Pairs/677.py
{ "start": 101, "end": 623 }
class ____: def __init__(self): self.root = TrieNode() self.keyToVal = {} def insert(self, key: str, val: int) -> None: diff = val - self.keyToVal.get(key, 0) node: TrieNode = self.root for c in key: node = node.children.setdefault(c, TrieNode()) node.sum += diff self.keyToVal[k...
MapSum
python
pytorch__pytorch
torch/nn/utils/_expanded_weights/instance_norm_expanded_weights.py
{ "start": 365, "end": 3772 }
class ____(torch.autograd.Function): @staticmethod # pyrefly: ignore [bad-override] def forward(ctx, kwarg_names, _, *expanded_args_and_kwargs): instance_norm = partial(torch.instance_norm, cudnn_enabled=True) expanded_args, expanded_kwargs = standard_kwargs( kwarg_names, expande...
InstanceNormPerSampleGrad
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/connections.py
{ "start": 2529, "end": 3146 }
class ____(BaseModel): """A class to store the behavior of each standard field of a Hook.""" hidden: Annotated[ bool, Field(description="Flag if the form field should be hidden."), ] = False title: Annotated[ str | None, Field( description="Label / title for ...
ConnectionHookFieldBehavior
python
google__jax
jax/_src/dispatch.py
{ "start": 3807, "end": 6140 }
class ____(threading.local): """See docstring for effects.py module for the calling convention for tokens.""" # For each ordered effect, the token returned by the last dispatched # computation, sharded over the devices in that computation. current_tokens: dict[core.Effect, core.Token] # For each device, the...
RuntimeTokenSet
python
fsspec__filesystem_spec
fsspec/caching.py
{ "start": 8215, "end": 9816 }
class ____(BaseCache): """Cache which reads only when we get beyond a block of data This is a much simpler version of BytesCache, and does not attempt to fill holes in the cache or keep fragments alive. It is best suited to many small reads in a sequential order (e.g., reading lines from a file). "...
ReadAheadCache
python
getsentry__sentry
src/sentry/testutils/cases.py
{ "start": 80034, "end": 85107 }
class ____( TestCase, BaseTestCase, # forcing this to explicitly inherit BaseTestCase addresses some type hint issues ): def store_functions( self, functions, project, transaction=None, extras=None, timestamp=None, ): if transaction is None: ...
ProfilesSnubaTestCase
python
PyCQA__pycodestyle
pycodestyle.py
{ "start": 86617, "end": 102084 }
class ____: """Initialize a PEP-8 instance with few options.""" def __init__(self, *args, **kwargs): # build options from the command line self.checker_class = kwargs.pop('checker_class', Checker) parse_argv = kwargs.pop('parse_argv', False) config_file = kwargs.pop('config_file...
StyleGuide
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_bedrock.py
{ "start": 8884, "end": 14124 }
class ____: KNOWLEDGE_BASE_ID = "knowledge_base_id" @pytest.fixture def mock_conn(self) -> Generator[BaseAwsConnection, None, None]: with mock.patch.object(BedrockAgentHook, "conn") as _conn: _conn.create_knowledge_base.return_value = { "knowledgeBase": {"knowledgeBaseId...
TestBedrockCreateKnowledgeBaseOperator
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_button02.py
{ "start": 315, "end": 877 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("button02.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_file...
TestCompareXLSXFiles