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
pallets__werkzeug
src/werkzeug/exceptions.py
{ "start": 18229, "end": 18662 }
class ____(HTTPException): """*424* `Failed Dependency` Used if the method could not be performed on the resource because the requested action depended on another action and that action failed. """ code = 424 description = ( "The method could not be performed on the resource because th...
FailedDependency
python
python-openxml__python-docx
src/docx/oxml/text/run.py
{ "start": 8825, "end": 9432 }
class ____(BaseOxmlElement): """`<w:t>` element, containing a sequence of characters within a run.""" def __str__(self) -> str: """Text contained in this element, the empty string if it has no content. This property allows this run inner-content element to be queried for its text the s...
CT_Text
python
doocs__leetcode
solution/2000-2099/2019.The Score of Students Solving Math Expression/Solution.py
{ "start": 0, "end": 1210 }
class ____: def scoreOfStudents(self, s: str, answers: List[int]) -> int: def cal(s: str) -> int: res, pre = 0, int(s[0]) for i in range(1, n, 2): if s[i] == "*": pre *= int(s[i + 1]) else: res += pre ...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 848000, "end": 848392 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("ProjectV2Field", graphql_...
ProjectV2FieldEdge
python
plotly__plotly.py
plotly/graph_objs/icicle/marker/_colorbar.py
{ "start": 233, "end": 61611 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "icicle.marker" _path_str = "icicle.marker.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "labelalias", "len", "lenmode", "minexpone...
ColorBar
python
facebook__pyre-check
client/tests/error_test.py
{ "start": 385, "end": 7310 }
class ____(unittest.TestCase): fake_error = { "line": 4, "column": 11, "stop_line": 4, "stop_column": 21, "path": "c.py", "code": -1, "name": "Revealed type", "description": "Fake error", "define": "c.$toplevel", } def test_json_parsin...
ErrorTest
python
huggingface__transformers
src/transformers/models/blt/modeling_blt.py
{ "start": 19426, "end": 20109 }
class ____(PreTrainedModel): config: BltConfig base_model_prefix = "model" input_modalities = ("image", "text") supports_gradient_checkpointing = True _no_split_modules = ["BltTransformerLayer"] _can_compile_fullgraph = False # static cache cannot have different shapes for each layer _suppo...
BltPreTrainedModel
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 109133, "end": 109231 }
class ____(BaseModel, extra="forbid"): sample: "Sample" = Field(..., description="")
SampleQuery
python
django__django
tests/template_tests/test_response.py
{ "start": 13242, "end": 13769 }
class ____(SimpleTestCase): def test_custom_urlconf(self): response = self.client.get("/template_response_view/") self.assertContains(response, "This is where you can find the snark: /snark/") @modify_settings( MIDDLEWARE={ "append": [ "django.middleware.cache.FetchFromCach...
CustomURLConfTest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py
{ "start": 28992, "end": 30425 }
class ____(graphene.Mutation): """Reports runless events for an asset or a subset of its partitions.""" Output = graphene.NonNull(GrapheneReportRunlessAssetEventsResult) class Arguments: eventParams = graphene.Argument(graphene.NonNull(GrapheneReportRunlessAssetEventsParams)) class Meta: ...
GrapheneReportRunlessAssetEventsMutation
python
facebook__pyre-check
client/commands/profile.py
{ "start": 1124, "end": 1273 }
class ____: name: str worker_id: int pid: int timestamp: int tags: Dict[str, str] @dataclasses.dataclass(frozen=True)
EventMetadata
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_magazine.py
{ "start": 592, "end": 11734 }
class ____(fixtures.MappedTest): @classmethod def setup_classes(cls): Base = cls.Comparable class Publication(Base): pass class Issue(Base): pass class Location(Base): pass class LocationName(Base): pass class P...
MagazineTest
python
encode__django-rest-framework
tests/test_generics.py
{ "start": 5483, "end": 11309 }
class ____(TestCase): def setUp(self): """ Create 3 BasicModel instances. """ items = ['foo', 'bar', 'baz', 'filtered out'] for item in items: BasicModel(text=item).save() self.objects = BasicModel.objects.exclude(text='filtered out') self.data = [...
TestInstanceView
python
walkccc__LeetCode
solutions/3290. Maximum Multiplication Score/3290-2.py
{ "start": 0, "end": 329 }
class ____: def maxScore(self, a: list[int], b: list[int]) -> int: # dp[i] := the maximum score of a[0..i] dp = [-math.inf] * 4 for num in b: for i in reversed(range(4)): # Skip `num` or pair a[i] with `num`. dp[i] = max(dp[i], (dp[i - 1] if i > 0 else 0) + a[i] * num) return d...
Solution
python
kamyu104__LeetCode-Solutions
Python/rectangle-area.py
{ "start": 29, "end": 501 }
class ____(object): # @param {integer} A # @param {integer} B # @param {integer} C # @param {integer} D # @param {integer} E # @param {integer} F # @param {integer} G # @param {integer} H # @return {integer} def computeArea(self, A, B, C, D, E, F, G, H): return (D - B) * ...
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/perflint/PERF402.py
{ "start": 436, "end": 800 }
class ____: def append(self, x): pass def f(): items = [1, 2, 3, 4] result = Foo() for i in items: result.append(i) # OK def f(): import sys for path in ("foo", "bar"): sys.path.append(path) # OK def f(): items = [1, 2, 3, 4] result = [] async for i i...
Foo
python
kamyu104__LeetCode-Solutions
Python/spiral-matrix-iv.py
{ "start": 70, "end": 172 }
class ____(object): def __init__(self, val=0, next=None): pass # linked list, array
ListNode
python
pandas-dev__pandas
pandas/io/json/_json.py
{ "start": 5773, "end": 7213 }
class ____(ABC): _default_orient: str def __init__( self, obj: NDFrame, orient: str | None, date_format: str, double_precision: int, ensure_ascii: bool, date_unit: str, index: bool, default_handler: Callable[[Any], JSONSerializable] | None...
Writer
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail_baseConfig.py
{ "start": 5745, "end": 6033 }
class ____(BaseModel): x: str = Field(..., alias=x_alias) z: int class Config: validate_by_name = True DynamicAliasModel2(y='y', z=1) # MYPY: error: Unexpected keyword argument "y" for "DynamicAliasModel2" [call-arg] DynamicAliasModel2(x='y', z=1)
DynamicAliasModel2
python
pytest-dev__pytest
testing/test_assertrewrite.py
{ "start": 63236, "end": 70563 }
class ____: def test_option_default(self, pytester: Pytester) -> None: config = pytester.parseconfig() assert config.getini("enable_assertion_pass_hook") is False @pytest.fixture def flag_on(self, pytester: Pytester): pytester.makeini("[pytest]\nenable_assertion_pass_hook = True\n")...
TestAssertionPass
python
plotly__plotly.py
plotly/graph_objs/icicle/marker/_line.py
{ "start": 233, "end": 4730 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "icicle.marker" _path_str = "icicle.marker.line" _valid_props = {"color", "colorsrc", "width", "widthsrc"} @property def color(self): """ Sets the color of the line enclosing each sector. Defaults to the `paper_bgcolor`...
Line
python
networkx__networkx
networkx/generators/tests/test_random_clustered.py
{ "start": 39, "end": 1297 }
class ____: def test_custom_joint_degree_sequence(self): node = [1, 1, 1, 2, 1, 2, 0, 0] tri = [0, 0, 0, 0, 0, 1, 1, 1] joint_degree_sequence = zip(node, tri) G = nx.random_clustered_graph(joint_degree_sequence) assert G.number_of_nodes() == 8 assert G.number_of_edges...
TestRandomClusteredGraph
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_format02.py
{ "start": 315, "end": 1554 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_format02.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = ...
TestCompareXLSXFiles
python
ethereum__web3.py
web3/beacon/beacon.py
{ "start": 1235, "end": 8650 }
class ____: def __init__( self, base_url: str, request_timeout: float = 10.0, ) -> None: self.base_url = base_url self.request_timeout = request_timeout self._request_session_manager = HTTPSessionManager() def _make_get_request( self, endpoint_url: st...
Beacon
python
Lightning-AI__lightning
src/lightning/pytorch/trainer/connectors/logger_connector/result.py
{ "start": 3429, "end": 5907 }
class ____: fx: str name: str prog_bar: bool = False logger: bool = True on_step: bool = False on_epoch: bool = True # https://github.com/pytorch/pytorch/issues/96197 reduce_fx: Callable = torch.mean enable_graph: bool = False add_dataloader_idx: bool = True dataloader_idx: O...
_Metadata
python
ray-project__ray
python/ray/serve/schema.py
{ "start": 41364, "end": 42002 }
class ____(BaseModel): """Represents the dependency graph of deployments in an application. The topology shows which deployments call which other deployments, with the ingress deployment as the entry point. """ app_name: str = Field( description="The name of the application this topology b...
DeploymentTopology
python
numpy__numpy
numpy/_core/tests/test_unicode.py
{ "start": 8726, "end": 8892 }
class ____(AssignValues): """Check the assignment of valued arrays (size 1009, UCS2 values)""" ulen = 1009 ucs_value = ucs2_value
TestAssignValues_1009_UCS2
python
joke2k__faker
tests/providers/test_python.py
{ "start": 5556, "end": 11129 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker() Faker.seed(0) def test_pyfloat(self): result = self.fake.pyfloat() self.assertIsInstance(result, float) def test_left_digits(self): expected_left_digits = 10 result = self.fake.pyfloat(lef...
TestPyfloat
python
boto__boto3
boto3/resources/model.py
{ "start": 3108, "end": 4267 }
class ____: """ An auto-filled parameter which has a source and target. For example, the ``QueueUrl`` may be auto-filled from a resource's ``url`` identifier when making calls to ``queue.receive_messages``. :type target: string :param target: The destination parameter name, e.g. ``QueueUrl`` ...
Parameter
python
celery__celery
celery/utils/functional.py
{ "start": 857, "end": 5142 }
class ____(lazy): """Memoized lazy evaluation. The function is only evaluated once, every subsequent access will return the same value. """ #: Set to :const:`True` after the object has been evaluated. evaluated = False _value = None def evaluate(self): if not self.evaluated: ...
mlazy
python
cython__cython
Cython/Compiler/PyrexTypes.py
{ "start": 183727, "end": 184105 }
class ____(BuiltinObjectType, PythonTypeConstructorMixin): """ builtin types like list, dict etc which can be subscripted in annotations """ def __init__(self, name, cname, objstruct_cname=None): super().__init__( name, cname, objstruct_cname=objstruct_cname) self.set_python_...
BuiltinTypeConstructorObjectType
python
eventlet__eventlet
tests/isolated/wsgi_connection_timeout.py
{ "start": 1149, "end": 1941 }
class ____: # server's socket.accept(); patches resulting connection sockets def __init__(self, sock): self.sock = sock self.sock._really_accept = self.sock.accept self.sock.accept = self self.conn_reg = [] def unwrap(self): self.sock.accept = self.sock._really_acce...
NaughtySocketAcceptWrap
python
huggingface__transformers
src/transformers/models/zoedepth/modeling_zoedepth.py
{ "start": 15304, "end": 17313 }
class ____(nn.Module): def __init__(self, n_classes=256, act=torch.softmax): """Compute log binomial distribution for n_classes Args: n_classes (`int`, *optional*, defaults to 256): Number of output classes. act (`torch.nn.Module`, *optional*, defaults to `to...
LogBinomialSoftmax
python
django__django
tests/constraints/tests.py
{ "start": 960, "end": 3946 }
class ____(SimpleTestCase): def test_constraint_sql(self): c = BaseConstraint(name="name") msg = "This method must be implemented by a subclass." with self.assertRaisesMessage(NotImplementedError, msg): c.constraint_sql(None, None) def test_contains_expressions(self): ...
BaseConstraintTests
python
realpython__materials
python-guitar-synthesizer/source_code_final/src/digitar/instrument.py
{ "start": 798, "end": 1739 }
class ____: tuning: StringTuning vibration: Time damping: float = 0.5 def __post_init__(self) -> None: if not (0 < self.damping <= 0.5): raise ValueError("string damping must be in the range of (0, 0.5]") @cached_property def num_strings(self) -> int: return len(sel...
PluckedStringInstrument
python
pallets__werkzeug
examples/shorty/utils.py
{ "start": 1788, "end": 2959 }
class ____: def __init__(self, query, per_page, page, endpoint): self.query = query self.per_page = per_page self.page = page self.endpoint = endpoint @cached_property def count(self): return self.query.count() @cached_property def entries(self): ret...
Pagination
python
getsentry__sentry
src/sentry/core/endpoints/organization_teams.py
{ "start": 3088, "end": 9267 }
class ____(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } permission_classes = (OrganizationTeamsPermission,) def team_serializer_for_post(self): # allow child routes to supply own serializer, used in SCIM teams route...
OrganizationTeamsEndpoint
python
nedbat__coveragepy
tests/test_files.py
{ "start": 17246, "end": 27841 }
class ____(CoverageTest): """Tests for coverage/files.py:PathAliases""" run_in_temp_dir = False def assert_mapped(self, aliases: PathAliases, inp: str, out: str) -> None: """Assert that `inp` mapped through `aliases` produces `out`. If the aliases are not relative, then `out` is canonical...
PathAliasesTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/external_data.py
{ "start": 56385, "end": 58023 }
class ____: # expect a compact repr for containers & defs components to be added for tree UI leaf_instances: Sequence[ComponentInstanceSnap] @staticmethod def from_tree(tree: ComponentTree) -> "ComponentTreeSnap": leaves = [] for comp_path, comp_inst in check.inst( tree.loa...
ComponentTreeSnap
python
getsentry__sentry
src/sentry/workflow_engine/handlers/condition/event_frequency_query_handlers.py
{ "start": 1246, "end": 1840 }
class ____(Protocol): def __call__( self, model: TSDBModel, keys: list[TSDBKey], start: datetime, end: datetime, rollup: int | None = None, environment_id: int | None = None, use_cache: bool = False, jitter_value: int | None = None, ten...
TSDBFunction
python
apache__airflow
providers/slack/tests/unit/slack/utils/test_utils.py
{ "start": 918, "end": 4145 }
class ____: @pytest.mark.parametrize("conn_type", ["slack", "slack_incoming_webhook"]) def test_get_extra_field(self, conn_type): """Test get arguments from connection extra: prefixed and not.""" extra_config = ConnectionExtraConfig( conn_type=conn_type, conn_id="test-con...
TestConnectionExtra
python
mlflow__mlflow
dev/tests/test_update_ml_package_versions.py
{ "start": 230, "end": 6161 }
class ____: def __init__(self, body): self.body = json.dumps(body).encode("utf-8") def read(self): return self.body def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass @classmethod def from_versions(cls, versions): ...
MockResponse
python
getsentry__sentry
src/sentry/feedback/usecases/ingest/userreport.py
{ "start": 1055, "end": 10038 }
class ____(Exception): pass def save_userreport( project: Project, report: UserReportDict, source: FeedbackCreationSource, start_time: datetime | None = None, ) -> UserReport | None: with metrics.timer("userreport.create_user_report", tags={"referrer": source.value}): if start_time is ...
Conflict
python
pytorch__pytorch
torch/_inductor/select_algorithm.py
{ "start": 60046, "end": 63747 }
class ____: """ Cache for generated code. The cache key is a string representation of the input nodes, number of stages, number of warps, and call sizes. The cache value is a tuple of the generated code, extra code, and events. """ def __init__(self, *args, **kwargs): self._cache: dict[...
GeneratedCodeCache
python
numpy__numpy
numpy/matrixlib/tests/test_matrix_linalg.py
{ "start": 1883, "end": 1945 }
class ____(_TestNorm2D): array = np.matrix
_TestNorm2DMatrix
python
joblib__joblib
benchmarks/bench_compression.py
{ "start": 1236, "end": 2359 }
class ____: """Protect the underlying fileobj against numerous calls to write This is achieved by internally keeping a list of small chunks and only flushing to the backing fileobj if passed a large chunk or after a threshold on the number of small chunks. """ def __init__(self, fileobj, max_bu...
PickleBufferedWriter
python
ansible__ansible
test/units/module_utils/facts/test_collectors.py
{ "start": 7310, "end": 7647 }
class ____(BaseFactsTest): __test__ = True gather_subset = ['!all', 'env'] valid_subsets = ['env'] fact_namespace = 'ansible_env' collector_class = EnvFactCollector def test_collect(self): facts_dict = super(TestEnvFacts, self)._test_collect() self.assertIn('HOME', facts_dict['...
TestEnvFacts
python
weaviate__weaviate-python-client
weaviate/connect/base.py
{ "start": 665, "end": 1137 }
class ____(BaseModel): host: str port: int secure: bool @field_validator("host") def _check_host(cls, v: str) -> str: if v == "": raise ValueError("host must not be empty") return v @field_validator("port") def _check_port(cls, v: int) -> int: if v < 0 o...
ProtocolParams
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/overloadImpl2.py
{ "start": 2392, "end": 2637 }
class ____(Generic[T_contra]): def method(self, x: T_contra) -> int: assert False @overload def func7(x: None) -> int: ... @overload def func7(x: ClassD[T]) -> int: ... def func7(x: ClassD[T] | None) -> int: assert False
ClassD
python
openai__openai-python
src/openai/resources/fine_tuning/jobs/jobs.py
{ "start": 35213, "end": 36093 }
class ____: def __init__(self, jobs: Jobs) -> None: self._jobs = jobs self.create = to_streamed_response_wrapper( jobs.create, ) self.retrieve = to_streamed_response_wrapper( jobs.retrieve, ) self.list = to_streamed_response_wrapper( ...
JobsWithStreamingResponse
python
explosion__spaCy
spacy/schemas.py
{ "start": 2364, "end": 2445 }
class ____: extra = "forbid" arbitrary_types_allowed = True
ArgSchemaConfig
python
huggingface__transformers
examples/pytorch/instance-segmentation/run_instance_segmentation.py
{ "start": 5872, "end": 6333 }
class ____: class_queries_logits: torch.Tensor masks_queries_logits: torch.Tensor def nested_cpu(tensors): if isinstance(tensors, (list, tuple)): return type(tensors)(nested_cpu(t) for t in tensors) elif isinstance(tensors, Mapping): return type(tensors)({k: nested_cpu(t) for k, t in t...
ModelOutput
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/optimizer/torch_optimizer.py
{ "start": 743, "end": 9461 }
class ____(Optimizer): def __init__(self, policy: TorchPolicy, trainer_settings: TrainerSettings): super().__init__() self.policy = policy self.trainer_settings = trainer_settings self.update_dict: Dict[str, torch.Tensor] = {} self.value_heads: Dict[str, torch.Tensor] = {} ...
TorchOptimizer
python
getsentry__sentry
tests/sentry/sentry_apps/api/serializers/test_sentry_app.py
{ "start": 457, "end": 3783 }
class ____(TestCase): def test_published_app(self) -> None: user = self.create_user() organization = self.create_organization(owner=user) sentry_app = self.create_sentry_app( name="Tesla App", organization=organization, published=True, scopes=(...
SentryAppSerializerTest
python
walkccc__LeetCode
solutions/542. 01 Matrix/542-2.py
{ "start": 0, "end": 644 }
class ____: def updateMatrix(self, mat: list[list[int]]) -> list[list[int]]: DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(mat) n = len(mat[0]) q = collections.deque() for i in range(m): for j in range(n): if mat[i][j] == 0: q.append((i, j)) else: mat...
Solution
python
pytorch__pytorch
torch/_higher_order_ops/strict_mode.py
{ "start": 1868, "end": 3831 }
class ____(HigherOrderOperator): def __init__(self): super().__init__("strict_mode") def __call__(self, callable, operands): return super().__call__(callable, operands) strict_mode_op = StrictMode() @strict_mode_op.py_impl(DispatchKey.CompositeExplicitAutograd) def strict_mode_op_dense(call...
StrictMode
python
matplotlib__matplotlib
lib/matplotlib/_mathtext.py
{ "start": 35546, "end": 37082 }
class ____(FontConstantsBase): pass # Maps font family names to the FontConstantBase subclass to use _font_constant_mapping = { 'DejaVu Sans': DejaVuSansFontConstants, 'DejaVu Sans Mono': DejaVuSansFontConstants, 'DejaVu Serif': DejaVuSerifFontConstants, 'cmb10': ComputerModernFontConstants, '...
DejaVuSansFontConstants
python
apache__airflow
providers/databricks/src/airflow/providers/databricks/sensors/databricks_sql.py
{ "start": 1357, "end": 5633 }
class ____(BaseSensorOperator): """ Sensor that runs a SQL query on Databricks. :param databricks_conn_id: Reference to :ref:`Databricks connection id<howto/connection:databricks>` (templated), defaults to DatabricksSqlHook.default_conn_name. :param sql_warehouse_name: Optional name of ...
DatabricksSqlSensor
python
run-llama__llama_index
llama-index-core/llama_index/core/indices/query/query_transform/base.py
{ "start": 2390, "end": 2848 }
class ____(BaseQueryTransform): """ Identity query transform. Do nothing to the query. """ def _get_prompts(self) -> PromptDictType: """Get prompts.""" return {} def _update_prompts(self, prompts: PromptDictType) -> None: """Update prompts.""" def _run(self, quer...
IdentityQueryTransform
python
eriklindernoren__ML-From-Scratch
mlfromscratch/deep_learning/neural_network.py
{ "start": 222, "end": 4750 }
class ____(): """Neural Network. Deep Learning base model. Parameters: ----------- optimizer: class The weight optimizer that will be used to tune the weights in order of minimizing the loss. loss: class Loss function used to measure the model's performance. SquareLoss or Cr...
NeuralNetwork
python
modin-project__modin
modin/pandas/window.py
{ "start": 3267, "end": 8574 }
class ____(ClassLogger): def __init__( self, dataframe, window=None, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None, step=None, method="single", ): if step is not None: raise ...
Rolling
python
PyCQA__pylint
doc/data/messages/t/too-many-ancestors/good.py
{ "start": 241, "end": 294 }
class ____(Animal): has_vertebrae = True
Vertebrate
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/io_test.py
{ "start": 6573, "end": 8351 }
class ____(IOTest, checkpoint_test_base.CheckpointTestBase): @combinations.generate(test_base.eager_only_combinations()) def testSaveCheckpointingAPI(self): dataset = dataset_ops.Dataset.range(40) checkpoint_args = {"directory": self._checkpoint_prefix, "max_to_keep": 50} dataset.save(self._save_dir, c...
SaveCheckpointTest
python
celery__celery
t/integration/test_canvas.py
{ "start": 4791, "end": 6949 }
class ____: @flaky def test_link_error_eager(self): exception = ExpectedException("Task expected to fail", "test") result = fail.apply(args=("test",), link_error=return_exception.s()) actual = result.get(timeout=TIMEOUT, propagate=False) assert actual == exception @flaky ...
test_link_error
python
django__django
django/db/models/fields/__init__.py
{ "start": 77167, "end": 77314 }
class ____(IntegerField): description = _("Small integer") def get_internal_type(self): return "SmallIntegerField"
SmallIntegerField
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 105992, "end": 110606 }
class ____(fixtures.DeclarativeMappedTest, AssertsCompiledSQL): __dialect__ = "default" run_create_tables = None @classmethod def setup_classes(cls): from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm.interfaces import PropComparator Base = cls.DeclarativeBa...
ProxyHybridTest
python
falconry__falcon
examples/recipes/msgspec_main.py
{ "start": 357, "end": 613 }
class ____(msgspec.Struct): text: Annotated[str, msgspec.Meta(max_length=256)] noteid: uuid.UUID = msgspec.field(default_factory=uuid.uuid4) created: datetime = msgspec.field( default_factory=partial(datetime.now, timezone.utc) )
Note
python
huggingface__transformers
src/transformers/models/maskformer/modeling_maskformer_swin.py
{ "start": 2564, "end": 4877 }
class ____(ModelOutput): r""" hidden_states_spatial_dimensions (`tuple(tuple(int, int))`, *optional*): A tuple containing the spatial dimension of each `hidden_state` needed to reshape the `hidden_states` to `batch, channels, height, width`. Due to padding, their spatial size cannot inferred bef...
MaskFormerSwinBaseModelOutput
python
keras-team__keras
keras/src/ops/nn_test.py
{ "start": 111863, "end": 121880 }
class ____(testing.TestCase): def test_logit_recovery_binary_crossentropy(self): layer = layers.Dense( 4, activation="sigmoid", use_bias=False, kernel_initializer="ones" ) loss = losses.BinaryCrossentropy() x = np.array([[1.4, 1.6, 0.8]]) y = np.array([[0.2, 0.6, ...
NNOpsBehaviorTest
python
python-visualization__folium
folium/plugins/encoded.py
{ "start": 1558, "end": 2652 }
class ____(_BaseFromEncoded): """Create PolyLines directly from the encoded string. Parameters ---------- encoded: str The raw encoded string from the Polyline Encoding Algorithm. See: https://developers.google.com/maps/documentation/utilities/polylinealgorithm **kwargs: Pol...
PolyLineFromEncoded
python
huggingface__transformers
tests/trainer/test_data_collator.py
{ "start": 48273, "end": 72352 }
class ____(unittest.TestCase): def setUp(self): self.tmpdirname = tempfile.mkdtemp() vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: ...
NumpyDataCollatorIntegrationTest
python
numba__numba
numba/parfors/parfor.py
{ "start": 70200, "end": 81710 }
class ____: """Parfor subpass to convert setitem on Arrays """ def __init__(self, pass_states): """ Parameters ---------- pass_states : ParforPassStates """ self.pass_states = pass_states self.rewritten = [] def run(self, blocks): pass_sta...
ConvertSetItemPass
python
optuna__optuna
optuna/study/_study_summary.py
{ "start": 306, "end": 4210 }
class ____: """Basic attributes and aggregated results of a :class:`~optuna.study.Study`. See also :func:`optuna.study.get_all_study_summaries`. Attributes: study_name: Name of the :class:`~optuna.study.Study`. direction: :class:`~optuna.study.StudyDirection` of the...
StudySummary
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/literals3.py
{ "start": 97, "end": 202 }
class ____(Enum): SOME_ENUM_VALUE1 = "1" SOME_ENUM_VALUE2 = "2" SOME_ENUM_VALUE3 = "3"
SomeEnum
python
pypa__pipenv
pipenv/utils/markers.py
{ "start": 567, "end": 23940 }
class ____: os_name: Optional[str] = None sys_platform: Optional[str] = None platform_machine: Optional[str] = None platform_python_implementation: Optional[str] = None platform_release: Optional[str] = None platform_system: Optional[str] = None platform_version: Optional[str] = None pyt...
PipenvMarkers
python
getsentry__sentry
src/sentry/workflow_engine/utils/dictpath.py
{ "start": 1957, "end": 3729 }
class ____[T]: def __init__(self, path: list[str], v: T) -> None: self._path = path self._v = v def failed(self) -> bool: return False def get(self, fallback: T | None = None) -> T: return self._v def get_or_none(self) -> T | None: return self._v def is_ty...
_SuccessResultImpl
python
fastai__fastai
fastai/data/transforms.py
{ "start": 16169, "end": 17081 }
class ____(DisplayedTransform): "Normalize/denorm batch of `TensorImage`" parameters,order = L('mean', 'std'),99 def __init__(self, mean=None, std=None, axes=(0,2,3)): store_attr() @classmethod def from_stats(cls, mean, std, dim=1, ndim=4, cuda=True): return cls(*broadcast_vec(dim, ndim, mean, std,...
Normalize
python
pandas-dev__pandas
asv_bench/benchmarks/reindex.py
{ "start": 1731, "end": 2162 }
class ____: params = [["pad", "backfill"], [date_range, period_range]] param_names = ["method", "constructor"] def setup(self, method, constructor): N = 100000 self.idx = constructor("1/1/2000", periods=N, freq="1min") self.ts = Series(np.random.randn(N), index=self.idx)[::2] d...
ReindexMethod
python
gevent__gevent
src/gevent/testing/flaky.py
{ "start": 1795, "end": 1931 }
class ____(FlakyTest): """ Use this when the flaky test is definitely caused by an unexpected timeout. """
FlakyTestTimeout
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/PlotItem/plotConfigTemplate_generic.py
{ "start": 356, "end": 11658 }
class ____(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(481, 840) self.averageGroup = QtWidgets.QGroupBox(Form) self.averageGroup.setGeometry(QtCore.QRect(0, 640, 242, 182)) self.averageGroup.setCheckable(True) self.averageGroup.setChecked(...
Ui_Form
python
django__django
django/contrib/gis/db/models/sql/conversion.py
{ "start": 204, "end": 1366 }
class ____(models.FloatField): "Wrapper for Area values." def __init__(self, geo_field): super().__init__() self.geo_field = geo_field def get_prep_value(self, value): if not isinstance(value, Area): raise ValueError("AreaField only accepts Area measurement objects.") ...
AreaField
python
huggingface__transformers
tests/models/gemma3n/test_modeling_gemma3n.py
{ "start": 2034, "end": 4510 }
class ____: def __init__( self, parent, batch_size=2, num_channels=32, # feature_size / input_feat_size sampling_rate=16_000, raw_audio_length=8_000, is_training=True, ): self.parent = parent self.batch_size = batch_size self.num_c...
Gemma3nAudioModelTester
python
ZoranPandovski__al-go-rithms
data_structures/Graphs/graph/Python/topological_sort.py
{ "start": 104, "end": 1633 }
class ____: def __init__(self,vertices): self.graph = defaultdict(list) #dictionary containing adjacency List self.V = vertices #No. of vertices # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A recursive function used by topologicalSort ...
Graph
python
pytest-dev__pluggy
src/pluggy/_hooks.py
{ "start": 22481, "end": 24611 }
class ____: """A hook implementation in a :class:`HookCaller`.""" __slots__ = ( "function", "argnames", "kwargnames", "plugin", "opts", "plugin_name", "wrapper", "hookwrapper", "optionalhook", "tryfirst", "trylast", ) ...
HookImpl
python
sympy__sympy
sympy/polys/puiseux.py
{ "start": 8041, "end": 27500 }
class ____(Generic[Er]): """Puiseux polynomial. Represents a truncated Puiseux series. See the :class:`PuiseuxRing` class for more information. >>> from sympy import QQ >>> from sympy.polys.puiseux import puiseux_ring >>> R, x, y = puiseux_ring('x, y', QQ) >>> p = 5*x**2 + 7*y**3 >>> p ...
PuiseuxPoly
python
huggingface__transformers
src/transformers/models/vitpose/modeling_vitpose.py
{ "start": 6288, "end": 7734 }
class ____(nn.Module): """ Classic decoding head consisting of a 2 deconvolutional blocks, followed by a 1x1 convolution layer, turning the feature maps into heatmaps. """ def __init__(self, config: VitPoseConfig): super().__init__() self.deconv1 = nn.ConvTranspose2d( c...
VitPoseClassicDecoder
python
django__django
tests/model_forms/models.py
{ "start": 14533, "end": 14699 }
class ____(models.Model): number = models.ForeignKey("Number", on_delete=models.CASCADE) die = models.ForeignKey("Dice", on_delete=models.CASCADE)
NumbersToDice
python
google__flatbuffers
tests/monster_test_generated.py
{ "start": 217, "end": 383 }
class ____(object): Red = 1 # \brief color Green # Green is bit_flag with value (1u << 1) Green = 2 # \brief color Blue (1u << 3) Blue = 8
Color
python
dateutil__dateutil
src/dateutil/parser/_parser.py
{ "start": 49747, "end": 58000 }
class ____(object): class _result(_resultbase): __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", "start", "end"] class _attr(_resultbase): __slots__ = ["month", "week", "weekday", "yday", "jyday", "day", "time"] def __...
_tzparser
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/vtk_m/package.py
{ "start": 220, "end": 1072 }
class ____(CMakePackage): """This is a fake vtk-m package used to demonstrate virtual package providers with dependencies.""" homepage = "http://www.spack-fake-vtk-m.org" url = "http://www.spack-fake-vtk-m.org/downloads/vtk-m-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") ...
VtkM
python
kubernetes-client__python
kubernetes/client/models/v1_group_version_for_discovery.py
{ "start": 383, "end": 5076 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1GroupVersionForDiscovery
python
pytorch__pytorch
test/distributed/test_symmetric_memory.py
{ "start": 43593, "end": 45962 }
class ____(MultiProcContinuousTest): def _init_process(self) -> None: torch.cuda.set_device(self.device) enable_symm_mem_for_group(dist.group.WORLD.group_name) torch.manual_seed(42 + self.rank) torch._inductor.config._collective.auto_select = True @property def device(self) ...
LoweringTest
python
sqlalchemy__sqlalchemy
test/orm/test_naturalpks.py
{ "start": 41986, "end": 50349 }
class ____(fixtures.MappedTest): """Test cascades of pk->pk/fk on joined table inh.""" # mssql doesn't allow ON UPDATE on self-referential keys __unsupported_on__ = ("mssql",) __requires__ = ("skip_mysql_on_windows",) __sparse_driver_backend__ = True @classmethod def define_tables(cls, me...
JoinedInheritanceTest
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_cloud_storage_transfer_service.py
{ "start": 11030, "end": 16377 }
class ____: @mock.patch( "airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook" ) def test_job_create_gcs(self, mock_hook): mock_hook.return_value.create_transfer_job.return_value = VALID_TRANSFER_JOB_GCS body = deepcopy(VALID_TRANSFER_...
TestGcpStorageTransferJobCreateOperator
python
pyca__cryptography
tests/hazmat/primitives/test_ciphers.py
{ "start": 1876, "end": 2548 }
class ____: @pytest.mark.parametrize("mode", (modes.CBC, modes.CTR, CFB, CFB8, OFB)) def test_invalid_key_size_with_mode(self, mode, backend): with pytest.raises(ValueError): ciphers.Cipher(AES(b"0" * 64), mode(b"0" * 16), backend) def test_xts_tweak_not_bytes(self): with pytest...
TestAESXTS
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 27655, "end": 28057 }
class ____(HTTPClientError): """ subclass of :class:`~HTTPClientError` This indicates that the precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. code: 412, title: Precondition Failed """ code = 412 title = 'Precondi...
HTTPPreconditionFailed
python
kubernetes-client__python
kubernetes/client/models/v1_service_port.py
{ "start": 383, "end": 11951 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1ServicePort
python
kamyu104__LeetCode-Solutions
Python/dungeon-game.py
{ "start": 37, "end": 636 }
class ____(object): # @param dungeon, a list of lists of integers # @return a integer def calculateMinimumHP(self, dungeon): DP = [float("inf") for _ in dungeon[0]] DP[-1] = 1 for i in reversed(xrange(len(dungeon))): DP[-1] = max(DP[-1] - dungeon[i][-1], 1) f...
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_types.py
{ "start": 14927, "end": 17913 }
class ____(_LiteralRoundTripFixture, fixtures.TestBase): __requires__ = ("datetime_interval",) __backend__ = True datatype = Interval data = datetime.timedelta(days=1, seconds=4) def test_literal(self, literal_round_trip): literal_round_trip(self.datatype, [self.data], [self.data]) de...
IntervalTest
python
streamlit__streamlit
lib/tests/streamlit/runtime/caching/cache_resource_api_test.py
{ "start": 1761, "end": 7899 }
class ____(unittest.TestCase): def setUp(self) -> None: # Caching functions rely on an active script run ctx add_script_run_ctx(threading.current_thread(), create_mock_script_run_ctx()) def tearDown(self): st.cache_resource.clear() # Some of these tests reach directly into _cach...
CacheResourceTest