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
pypa__warehouse
tests/unit/organizations/test_models.py
{ "start": 10803, "end": 11397 }
class ____: def test_traversal_finds(self, db_request): organization = DBOrganizationFactory.create(name="foo") team = DBTeamFactory.create(organization=organization, name="Bar") root = TeamFactory(db_request) assert root["foo"]["bar"] == team def test_traversal_cant_find(self...
TestTeamFactory
python
pytest-dev__pytest
src/_pytest/mark/expression.py
{ "start": 9303, "end": 9831 }
class ____(Mapping[str, MatcherNameAdapter]): """Adapts a matcher function to a locals mapping as required by eval().""" def __init__(self, matcher: ExpressionMatcher) -> None: self.matcher = matcher def __getitem__(self, key: str) -> MatcherNameAdapter: return MatcherNameAdapter(matcher=s...
MatcherAdapter
python
celery__celery
t/unit/worker/test_bootsteps.py
{ "start": 5005, "end": 9415 }
class ____: class Blueprint(bootsteps.Blueprint): name = 'test_Blueprint' def test_steps_added_to_unclaimed(self): class tnA(bootsteps.Step): name = 'test_Blueprint.A' class tnB(bootsteps.Step): name = 'test_Blueprint.B' class xxA(bootsteps.Step): ...
test_Blueprint
python
Lightning-AI__lightning
examples/pytorch/tensor_parallel/train.py
{ "start": 346, "end": 2773 }
class ____(L.LightningModule): def __init__(self): super().__init__() self.model_args = ModelArgs(vocab_size=32000) self.model = Transformer(self.model_args) def configure_model(self): # User-defined function that applies the desired parallelizations specific to the model ...
Llama3
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol30.py
{ "start": 327, "end": 373 }
class ____(Protocol): v1: ClassVar[float]
P2
python
pallets__flask
src/flask/json/tag.py
{ "start": 1625, "end": 2803 }
class ____: """Base class for defining type tags for :class:`TaggedJSONSerializer`.""" __slots__ = ("serializer",) #: The tag to mark the serialized object with. If empty, this tag is #: only used as an intermediate step during tagging. key: str = "" def __init__(self, serializer: TaggedJSONS...
JSONTag
python
pandas-dev__pandas
pandas/tests/plotting/frame/test_frame_subplots.py
{ "start": 577, "end": 28961 }
class ____: @pytest.mark.slow @pytest.mark.parametrize("kind", ["bar", "barh", "line", "area"]) def test_subplots(self, kind): df = DataFrame( np.random.default_rng(2).random((10, 3)), index=list(string.ascii_letters[:10]), ) axes = df.plot(kind=kind, subplot...
TestDataFramePlotsSubplots
python
PrefectHQ__prefect
src/prefect/cli/transfer/_dag.py
{ "start": 837, "end": 1068 }
class ____(Enum): """State of a node during traversal.""" PENDING = "pending" READY = "ready" IN_PROGRESS = "in_progress" COMPLETED = "completed" FAILED = "failed" SKIPPED = "skipped" @dataclass
NodeState
python
google__jax
jax/_src/hijax.py
{ "start": 6954, "end": 7173 }
class ____(type): def __instancecheck__(self, instance): return (super().__instancecheck__(instance) or isinstance(instance, core.Tracer) and isinstance(core.typeof(instance), BoxTy))
_BoxMeta
python
getsentry__sentry
src/sentry/models/debugfile.py
{ "start": 1441, "end": 3964 }
class ____(BaseManager["ProjectDebugFile"]): def find_missing(self, checksums: Iterable[str], project: Project) -> list[str]: if not checksums: return [] checksums = [x.lower() for x in checksums] missing = set(checksums) found = ProjectDebugFile.objects.filter( ...
ProjectDebugFileManager
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeParams7.py
{ "start": 425, "end": 487 }
class ____(str): ... A5 = ClassA[..., StrSubclass]
StrSubclass
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/op_invocation.py
{ "start": 1279, "end": 23494 }
class ____(NamedTuple): input_args: tuple[Any, ...] input_kwargs: dict[str, Any] resources_by_param_name: dict[str, Any] config_arg: Any def _separate_args_and_kwargs( compute_fn: "DecoratedOpFunction", args: tuple[Any, ...], kwargs: dict[str, Any], resource_arg_mapping: dict[str, Any]...
SeparatedArgsKwargs
python
huggingface__transformers
src/transformers/models/speech_to_text/configuration_speech_to_text.py
{ "start": 788, "end": 9825 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Speech2TextModel`]. It is used to instantiate a Speech2Text model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a simil...
Speech2TextConfig
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_function_base.py
{ "start": 3104, "end": 5158 }
class ____(TestCase): def test_basic(self): assert_raises(ValueError, np.rot90, np.ones(4)) assert_raises( (ValueError, RuntimeError), np.rot90, np.ones((2, 2, 2)), axes=(0, 1, 2) ) assert_raises(ValueError, np.rot90, np.ones((2, 2)), axes=(0, 2)) assert_raises(Va...
TestRot90
python
getsentry__sentry
src/sentry/notifications/notifications/activity/assigned.py
{ "start": 1815, "end": 2673 }
class ____(GroupActivityNotification): metrics_key = "assigned_activity" title = "Assigned" def get_assignee(self) -> str: return get_assignee_str(self.activity, self.organization) def get_description(self) -> tuple[str, str | None, Mapping[str, Any]]: return "{author} assigned {an iss...
AssignedActivityNotification
python
rapidsai__cudf
python/cudf/cudf/core/column/timedelta.py
{ "start": 1353, "end": 13792 }
class ____(TemporalBaseColumn): _NP_SCALAR = np.timedelta64 _PD_SCALAR = pd.Timedelta _VALID_BINARY_OPERATIONS = { "__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__", "__add__", "__sub__", "__mul__", "__mod__", "...
TimeDeltaColumn
python
python__mypy
mypyc/irbuild/nonlocalcontrol.py
{ "start": 1525, "end": 1988 }
class ____(NonlocalControl): """Default nonlocal control outside any statements that affect it.""" def gen_break(self, builder: IRBuilder, line: int) -> None: assert False, "break outside of loop" def gen_continue(self, builder: IRBuilder, line: int) -> None: assert False, "continue outsid...
BaseNonlocalControl
python
huggingface__transformers
src/transformers/models/dab_detr/modeling_dab_detr.py
{ "start": 29378, "end": 30636 }
class ____(nn.Module): def __init__(self, config: DabDetrConfig): super().__init__() hidden_size = config.hidden_size self.final_layer_norm = nn.LayerNorm(hidden_size) self.fc1 = nn.Linear(hidden_size, config.decoder_ffn_dim) self.fc2 = nn.Linear(config.decoder_ffn_dim, hidde...
DabDetrDecoderLayerFFN
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/assertsql.py
{ "start": 13850, "end": 14179 }
class ____(AllOf): def process_statement(self, execute_observed): for rule in self.rules: rule.process_statement(execute_observed) if rule.is_consumed: self.is_consumed = True break else: self.errormessage = list(self.rules)[0].erro...
Or
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/models/secrets.py
{ "start": 1088, "end": 2644 }
class ____(SecretStore): def __init__(self, gcp_credentials: Secret) -> None: service_account_info = json.loads(gcp_credentials.value) credentials = service_account.Credentials.from_service_account_info(service_account_info) self.gsm_client = secretmanager_v1.SecretManagerServiceClient.from_...
GSMSecretStore
python
buildout__buildout
src/zc/buildout/buildout.py
{ "start": 8990, "end": 59017 }
class ____(DictMixin): COMMANDS = set() def __init__(self, config_file, cloptions, use_user_defaults=True, command=None, args=()): __doing__ = 'Initializing.' # default options _buildout_default_options_copy = copy.deepcopy( _buildout_def...
Buildout
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/optimiser.py
{ "start": 853, "end": 8856 }
class ____: """A fairly basic optimiser designed to increase the value of scores for targeted property-based testing. This implements a fairly naive hill climbing algorithm based on randomly regenerating parts of the test case to attempt to improve the result. It is not expected to produce amazing ...
Optimiser
python
pyparsing__pyparsing
examples/tiny/tiny_ast.py
{ "start": 17628, "end": 19051 }
class ____(TinyNode): """Statement form of a function call. Holds the function name and argument expressions; on execution the arguments are evaluated and `TinyEngine.call_function` is invoked. The return value (if any) is ignored in statement context. """ statement_type: ClassVar[str] = "call_...
CallStmtNode
python
aio-libs__aiohttp
aiohttp/client_middleware_digest_auth.py
{ "start": 4775, "end": 17017 }
class ____: """ HTTP digest authentication middleware for aiohttp client. This middleware intercepts 401 Unauthorized responses containing a Digest authentication challenge, calculates the appropriate digest credentials, and automatically retries the request with the proper Authorization header. ...
DigestAuthMiddleware
python
facelessuser__soupsieve
tests/test_level3/test_nth_last_child.py
{ "start": 61, "end": 1365 }
class ____(util.TestCase): """Test `nth` last child selectors.""" def test_nth_last_child(self): """Test `nth` last child.""" markup = """ <body> <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> ...
TestNthLastChild
python
ray-project__ray
python/ray/serve/tests/unit/test_application_state.py
{ "start": 99621, "end": 130529 }
class ____: """Test application-level autoscaling policy registration, execution, and lifecycle.""" def _create_app_config( self, app_name="test_app", has_policy=True, deployments=None ): """Helper to create a ServeApplicationSchema with optional autoscaling policy.""" if deployment...
TestApplicationLevelAutoscaling
python
huggingface__transformers
src/transformers/models/vit_msn/modeling_vit_msn.py
{ "start": 1372, "end": 5405 }
class ____(nn.Module): """ Construct the CLS token, position and patch embeddings. Optionally, also the mask token. """ def __init__(self, config: ViTMSNConfig, use_mask_token: bool = False) -> None: super().__init__() self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)...
ViTMSNEmbeddings
python
patrys__httmock
tests.py
{ "start": 11249, "end": 11844 }
class ____(unittest.TestCase): @with_httmock(any_mock) def test_stream_request(self): r = requests.get('http://domain.com/', stream=True) self.assertEqual(r.raw.read(), b'Hello from domain.com') @with_httmock(dict_any_mock) def test_stream_request_with_dict_mock(self): r = reque...
StreamTest
python
scikit-learn__scikit-learn
sklearn/ensemble/_forest.py
{ "start": 89347, "end": 103557 }
class ____(ForestRegressor): """ An extra-trees regressor. This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. This ...
ExtraTreesRegressor
python
getsentry__sentry-python
sentry_sdk/integrations/grpc/aio/client.py
{ "start": 1283, "end": 2292 }
class ____(ClientInterceptor, UnaryUnaryClientInterceptor): # type: ignore async def intercept_unary_unary( self, continuation: Callable[[ClientCallDetails, Message], UnaryUnaryCall], client_call_details: ClientCallDetails, request: Message, ) -> Union[UnaryUnaryCall, Message]: ...
SentryUnaryUnaryClientInterceptor
python
Netflix__metaflow
metaflow/plugins/cards/card_modules/chevron/tokenizer.py
{ "start": 52, "end": 7400 }
class ____(SyntaxError): pass # # Helper functions # def grab_literal(template, l_del): """Parse a literal from the template""" global _CURRENT_LINE try: # Look for the next tag and move the template to it literal, template = template.split(l_del, 1) _CURRENT_LINE += litera...
ChevronError
python
django__django
django/contrib/auth/backends.py
{ "start": 12845, "end": 12965 }
class ____(RemoteUserBackend): def user_can_authenticate(self, user): return True
AllowAllUsersRemoteUserBackend
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 39910, "end": 69805 }
class ____(Loops): reduction_ranges: Sequence[_IntLike] reduction_type: ReductionType # self.dtype represents the dst dtype src_dtype: torch.dtype reduction_hint: ReductionHint def __str__(self) -> str: return self._to_str(("ranges", "reduction_ranges", "reduction_type")) __repr__ ...
Reduction
python
pydantic__pydantic
tests/mypy/outputs/mypy-default_ini/root_models.py
{ "start": 606, "end": 1578 }
class ____(BaseModel, Generic[V]): m1: Maybe[int] m2: Maybe[V] m3: Maybe # MYPY: error: Missing type parameters for generic type "Maybe" [type-arg] Model[str](m1=1, m2='dog', m3=[]) # MYPY: error: Argument "m1" to "Model" has incompatible type "int"; expected "Maybe[int]" [arg-type] # MYPY: error: Argum...
Model
python
great-expectations__great_expectations
great_expectations/render/components.py
{ "start": 7222, "end": 8415 }
class ____(RenderedComponentContent): def __init__( self, header, subheader=None, header_row=None, styling=None, content_block_type="header", ) -> None: super().__init__(content_block_type=content_block_type, styling=styling) self.header = header ...
RenderedHeaderContent
python
getsentry__sentry
src/sentry/api/endpoints/organization_events_meta.py
{ "start": 7270, "end": 13826 }
class ____(OrganizationEventsV2EndpointBase): publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get(self, request: Request, organization: Organization) -> Response: try: snuba_params = self.get_snuba_params(request, organization) except NoProjects: r...
OrganizationSpansSamplesEndpoint
python
python__mypy
mypy/messages.py
{ "start": 114139, "end": 136729 }
class ____(TypeTraverserVisitor): def __init__(self) -> None: self.types: list[Type] = [] def visit_instance(self, t: Instance) -> None: self.types.append(t) super().visit_instance(t) def visit_type_alias_type(self, t: TypeAliasType) -> None: if t.alias and not t.is_recursi...
CollectAllNamedTypesQuery
python
astropy__astropy
astropy/modeling/functional_models.py
{ "start": 79553, "end": 82255 }
class ____(Fittable2DModel): """ Two dimensional Box model. Parameters ---------- amplitude : float Amplitude x_0 : float x position of the center of the box function x_width : float Width in x direction of the box y_0 : float y position of the center of ...
Box2D
python
walkccc__LeetCode
solutions/1499. Max Value of Equation/1499-2.py
{ "start": 0, "end": 533 }
class ____: def findMaxValueOfEquation(self, points: list[list[int]], k: int) -> int: ans = -math.inf maxQ = collections.deque() # (y - x, x) for x, y in points: # Remove the invalid points, xj - xi > k while maxQ and x - maxQ[0][1] > k: maxQ.popleft() if maxQ: ans = ma...
Solution
python
pytorch__pytorch
torch/_inductor/codegen/common.py
{ "start": 7769, "end": 7964 }
class ____: name: str buffer: str dtype: torch.dtype offset: sympy.Expr = sympy.S.Zero # c++ only alias_of: Optional[str] = None # halide only @dataclasses.dataclass
TensorArg
python
google__pytype
pytype/tests/test_functions2.py
{ "start": 10443, "end": 22092 }
class ____(test_base.BaseTest): """Tests for functions.""" def test_make_function(self): src = """ def uses_annotations(x: int) -> int: i, j = 3, 4 return i def uses_pos_defaults(x, y=1): i, j = 3, 4 return __any_object__ def uses_kw_defaults(x, *myargs, y=1)...
TestFunctionsPython3Feature
python
psf__black
src/blib2to3/pytree.py
{ "start": 15319, "end": 18335 }
class ____: """ A pattern is a tree matching pattern. It looks for a specific node type (token or symbol), and optionally for a specific content. This is an abstract base class. There are three concrete subclasses: - LeafPattern matches a single leaf node; - NodePattern matches a sin...
BasePattern
python
plotly__plotly.py
plotly/graph_objs/splom/marker/colorbar/_title.py
{ "start": 233, "end": 4006 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "splom.marker.colorbar" _path_str = "splom.marker.colorbar.title" _valid_props = {"font", "side", "text"} @property def font(self): """ Sets this color bar's title font. The 'font' property is an instance of Font ...
Title
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_P.py
{ "start": 14542, "end": 15627 }
class ____(Benchmark): r""" Powell objective function. This class defines the Powell [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Powell}}(x) = (x_3+10x_1)^2 + 5(x_2-x_4)^2 + (x_1-2x_2)^4 + 10(x_3-x_4)^4 ...
Powell
python
huggingface__transformers
tests/models/altclip/test_modeling_altclip.py
{ "start": 1428, "end": 4514 }
class ____: def __init__( self, parent, batch_size=12, image_size=30, patch_size=2, num_channels=3, is_training=True, hidden_size=32, projection_dim=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, ...
AltCLIPVisionModelTester
python
kamyu104__LeetCode-Solutions
Python/jump-game-vi.py
{ "start": 50, "end": 540 }
class ____(object): def maxResult(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ score = 0 dq = collections.deque() for i, num in enumerate(nums): if dq and dq[0][0] == i-k-1: dq.popleft() ...
Solution
python
getsentry__sentry
src/sentry/notifications/types.py
{ "start": 2390, "end": 6022 }
class ____(Enum): SELF_ACTIVITY = "personalActivityNotifications" SELF_ASSIGN = "selfAssignOnResolve" VALID_VALUES_FOR_KEY = { NotificationSettingEnum.APPROVAL: { NotificationSettingsOptionEnum.ALWAYS, NotificationSettingsOptionEnum.NEVER, }, NotificationSettingEnum.DEPLOY: { ...
UserOptionsSettingsKey
python
pyqtgraph__pyqtgraph
pyqtgraph/parametertree/parameterTypes/font.py
{ "start": 114, "end": 581 }
class ____(WidgetParameterItem): def makeWidget(self): w = QtWidgets.QFontComboBox() w.setMaximumHeight(20) w.sigChanged = w.currentFontChanged w.value = w.currentFont w.setValue = w.setCurrentFont self.hideWidget = False return w def updateDisplayLabel(s...
FontParameterItem
python
python-openxml__python-docx
tests/image/test_png.py
{ "start": 10602, "end": 12643 }
class ____: def it_constructs_the_appropriate_Chunk_subclass(self, call_fixture): chunk_type, stream_rdr_, offset, chunk_cls_ = call_fixture chunk = _ChunkFactory(chunk_type, stream_rdr_, offset) chunk_cls_.from_offset.assert_called_once_with(chunk_type, stream_rdr_, offset) assert i...
Describe_ChunkFactory
python
google__jax
tests/pallas/pallas_test.py
{ "start": 87042, "end": 87118 }
class ____(PallasCheckifyTest): INTERPRET = True
PallasCheckifyInterpretTest
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/nested_auto_heights.py
{ "start": 186, "end": 1362 }
class ____(App[None]): CSS = """ Screen { background: red; } #my-static-container { border: heavy lightgreen; background: green; height: auto; max-height: 10; } #my-static-wrapper { border: heavy lightblue; background: blue; width...
NestedAutoApp
python
realpython__materials
python-docstrings/classes_docstring.py
{ "start": 0, "end": 894 }
class ____: """ Represents a magical potion composed of various ingredients. Attributes ---------- name : str The name of the potion. ingredients : list of str A list of ingredients used in the potion. potency : int The strength level of the potion. Methods ...
Potion
python
charliermarsh__ruff
scripts/check_docs_formatted.py
{ "start": 4163, "end": 12389 }
class ____(ValueError): """Raised when ruff fails to parse file.""" def format_str(code: str, extension: Literal["py", "pyi"]) -> str: """Format a code block with ruff by writing to a temporary file.""" # Run ruff to format the tmp file try: completed_process = subprocess.run( ["ru...
InvalidInput
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/envs/pettingzoo_env_factory.py
{ "start": 585, "end": 1957 }
class ____: def __init__(self, env_id: str) -> None: self.env_id = env_id def env( self, seed: Optional[int] = None, **kwargs: Union[List, int, bool, None] ) -> UnityAECEnv: """ Creates the environment with env_id from unity's default_registry and wraps it in a UnityToPettin...
PettingZooEnvFactory
python
getsentry__sentry
src/sentry/api/serializers/rest_framework/dashboard.py
{ "start": 26560, "end": 47704 }
class ____(CamelSnakeSerializer[Dashboard]): # Is a string because output serializers also make it a string. id = serializers.CharField(required=False, help_text="A dashboard's unique id.") title = serializers.CharField( required=False, max_length=255, help_text="The user-defined dashboard title." ...
DashboardDetailsSerializer
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/ranges.py
{ "start": 31104, "end": 31248 }
class ____(AbstractMultiRange[int]): """Represent the PostgreSQL INT4MULTIRANGE type.""" __visit_name__ = "INT4MULTIRANGE"
INT4MULTIRANGE
python
cython__cython
runtests.py
{ "start": 18791, "end": 19353 }
class ____(_build_ext): def build_extension(self, ext): try: compiler_obj = self.compiler if ext.language == 'c++': compiler_obj.compiler_so.remove('-Wstrict-prototypes') if CCACHE: compiler_obj.compiler_so = CCACHE + compiler_obj.compiler_...
build_ext
python
realpython__materials
python-protocol/contents.py
{ "start": 105, "end": 232 }
class ____(ContentCreator, Protocol): posts: list[str] def add_post(self, title: str, content: str) -> None: ...
Blogger
python
psf__requests
tests/test_structures.py
{ "start": 81, "end": 1572 }
class ____: @pytest.fixture(autouse=True) def setup(self): """CaseInsensitiveDict instance with "Accept" header.""" self.case_insensitive_dict = CaseInsensitiveDict() self.case_insensitive_dict["Accept"] = "application/json" def test_list(self): assert list(self.case_insensi...
TestCaseInsensitiveDict
python
huggingface__transformers
src/transformers/debug_utils.py
{ "start": 774, "end": 12768 }
class ____: """ This debug class helps detect and understand where the model starts getting very large or very small, and more importantly `nan` or `inf` weight and activation elements. There are 2 working modes: 1. Underflow/overflow detection (default) 2. Specific batch absolute min/max trac...
DebugUnderflowOverflow
python
kamyu104__LeetCode-Solutions
Python/check-if-digits-are-equal-in-string-after-operations-i.py
{ "start": 1000, "end": 2153 }
class ____(object): def hasSameDigits(self, s): """ :type s: str :rtype: bool """ def nCr(n, r): if n-r < r: r = n-r if LOOKUP[n][r] == -1: c = 1 for k in xrange(1, r+1): c *= n-k+1 ...
Solution2
python
huggingface__transformers
src/transformers/models/qwen3_vl/modular_qwen3_vl.py
{ "start": 19989, "end": 21010 }
class ____(Qwen3DecoderLayer): def __init__(self, config: Qwen3VLTextConfig, layer_idx: int): super().__init__(config, layer_idx) del self.attention_type def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], atten...
Qwen3VLTextDecoderLayer
python
walkccc__LeetCode
solutions/3453. Separate Squares I/3453.py
{ "start": 0, "end": 532 }
class ____: def separateSquares(self, squares: list[list[int]]) -> float: halfArea = sum((l**2 for _, _, l in squares)) / 2 events = sorted([(y, True, l) for _, y, l in squares] + [(y + l, False, l) for _, y, l in squares]) area = 0 width = 0 prevY = 0 for y, isStart, l in...
Solution
python
django__django
django/core/checks/messages.py
{ "start": 1654, "end": 1773 }
class ____(CheckMessage): def __init__(self, *args, **kwargs): super().__init__(DEBUG, *args, **kwargs)
Debug
python
cython__cython
Demos/benchmarks/bm_chaos.py
{ "start": 1921, "end": 4636 }
class ____(object): """Class for representing B-Splines and NURBS of arbitrary degree""" def __init__(self, points, degree = 3, knots = None): """Creates a Spline. points is a list of GVector, degree is the degree of the Spline.""" if knots is None: self.knots = GetKnots(points, degr...
Spline
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/hitl.py
{ "start": 1112, "end": 1338 }
class ____(BaseModel): """Schema for updating the content of a Human-in-the-loop detail.""" chosen_options: list[str] = Field(min_length=1) params_input: Mapping = Field(default_factory=dict)
UpdateHITLDetailPayload
python
astropy__astropy
astropy/coordinates/polarization.py
{ "start": 4550, "end": 8107 }
class ____(ShapedLikeNDArray): """ A representation of stokes coordinates with helpers for converting to profile names. Parameters ---------- stokes : array-like The numeric values representing stokes coordinates. """ info = StokesCoordInfo() def __init__(self, stokes, copy=Fa...
StokesCoord
python
walkccc__LeetCode
solutions/1669. Merge In Between Linked Lists/1669.py
{ "start": 0, "end": 525 }
class ____: def mergeInBetween( self, list1: ListNode, a: int, b: int, list2: ListNode, ) -> ListNode: nodeBeforeA = list1 for i in range(a - 1): nodeBeforeA = nodeBeforeA.next nodeB = nodeBeforeA.next for i in range(b - a): nodeB = nodeB.next nodeBefo...
Solution
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_pretty.py
{ "start": 3465, "end": 3519 }
class ____: def somemethod(self): pass
MyObj
python
plotly__plotly.py
plotly/graph_objs/parcoords/line/colorbar/_title.py
{ "start": 233, "end": 4021 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "parcoords.line.colorbar" _path_str = "parcoords.line.colorbar.title" _valid_props = {"font", "side", "text"} @property def font(self): """ Sets this color bar's title font. The 'font' property is an instance of Font ...
Title
python
pyca__cryptography
src/cryptography/hazmat/_oid.py
{ "start": 10822, "end": 17240 }
class ____: CHALLENGE_PASSWORD = ObjectIdentifier("1.2.840.113549.1.9.7") UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2") _OID_NAMES = { NameOID.COMMON_NAME: "commonName", NameOID.COUNTRY_NAME: "countryName", NameOID.LOCALITY_NAME: "localityName", NameOID.STATE_OR_PROVINCE_NAME: "...
AttributeOID
python
catalyst-team__catalyst
catalyst/metrics/_functional_metric.py
{ "start": 3582, "end": 6579 }
class ____(ICallbackLoaderMetric): """Class for custom **loader-based** metrics in a functional way. Args: metric_fn: metric function, that get outputs, targets and return score as torch.Tensor metric_key: metric name accumulative_fields: list of keys to accumulate data from...
FunctionalLoaderMetric
python
jazzband__django-oauth-toolkit
tests/test_oidc_views.py
{ "start": 971, "end": 7160 }
class ____(TestCase): def test_get_connect_discovery_info(self): expected_response = { "issuer": "http://localhost/o", "authorization_endpoint": "http://localhost/o/authorize/", "token_endpoint": "http://localhost/o/token/", "userinfo_endpoint": "http://localh...
TestConnectDiscoveryInfoView
python
apache__airflow
providers/google/tests/unit/google/cloud/sensors/test_bigquery.py
{ "start": 5549, "end": 10580 }
class ____: @mock.patch("airflow.providers.google.cloud.sensors.bigquery.BigQueryHook") def test_passing_arguments_to_hook(self, mock_hook): task = BigQueryTablePartitionExistenceSensor( task_id="task-id", project_id=TEST_PROJECT_ID, dataset_id=TEST_DATASET_ID, ...
TestBigqueryTablePartitionExistenceSensor
python
dagster-io__dagster
python_modules/dagster/dagster/components/component/component.py
{ "start": 1339, "end": 2982 }
class ____(IHaveNew): """Specifies the core attributes of a component. Used when defining custom components. Args: description (Optional[str]): Human-readable description of this component. metadata (Optional[Dict[str, Any]]): A dict of static metadata for this component. For exampl...
ComponentTypeSpec
python
donnemartin__interactive-coding-challenges
stacks_queues/n_stacks/test_n_stacks.py
{ "start": 18, "end": 1356 }
class ____(unittest.TestCase): def test_pop_on_empty(self, num_stacks, stack_size): print('Test: Pop on empty stack') stacks = Stacks(num_stacks, stack_size) stacks.pop(0) def test_push_on_full(self, num_stacks, stack_size): print('Test: Push to full stack') stacks = St...
TestStacks
python
ray-project__ray
python/ray/train/tensorflow/tensorflow_checkpoint.py
{ "start": 380, "end": 5524 }
class ____(FrameworkCheckpoint): """A :py:class:`~ray.train.Checkpoint` with TensorFlow-specific functionality.""" MODEL_FILENAME_KEY = "_model_filename" @classmethod def from_model( cls, model: keras.Model, *, preprocessor: Optional["Preprocessor"] = None, ) -> "Te...
TensorflowCheckpoint
python
jmcnamara__XlsxWriter
xlsxwriter/test/workbook/test_custom_sheet.py
{ "start": 404, "end": 447 }
class ____(Chartsheet): pass
MyChartsheet
python
getsentry__sentry
src/sentry/search/events/types.py
{ "start": 9265, "end": 9720 }
class ____: op: str group: str @staticmethod def from_str(s: str) -> Span: parts = s.rsplit(":", 1) if len(parts) != 2: raise ValueError( "span must consist of of a span op and a valid 16 character hex delimited by a colon (:)" ) if not is...
Span
python
ansible__ansible
test/lib/ansible_test/_internal/commands/sanity/__init__.py
{ "start": 24801, "end": 25008 }
class ____(TestSuccess): """Sanity test success.""" def __init__(self, test: str, python_version: t.Optional[str] = None) -> None: super().__init__(COMMAND, test, python_version)
SanitySuccess
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 734454, "end": 735255 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "actor", "created_at", "database_id", "deployment", "pull_request", "ref", ) actor = sgqlc.types.Field(Actor, graphql_na...
DeployedEvent
python
MorvanZhou__Reinforcement-learning-with-tensorflow
contents/5.2_Prioritized_Replay_DQN/RL_brain.py
{ "start": 2873, "end": 4777 }
class ____(object): # stored as ( s, a, r, s_ ) in SumTree """ This Memory class is modified based on the original code from: https://github.com/jaara/AI-blog/blob/master/Seaquest-DDQN-PER.py """ epsilon = 0.01 # small amount to avoid zero priority alpha = 0.6 # [0~1] convert the importance o...
Memory
python
django__django
tests/queries/tests.py
{ "start": 137492, "end": 138475 }
class ____(TestCase): """ Filtering on non-null character fields works as expected. The reason for these tests is that Oracle treats '' as NULL, and this can cause problems in query construction. Refs #17957. """ @classmethod def setUpTestData(cls): cls.nc = NamedCategory.objects.cr...
EmptyStringsAsNullTest
python
huggingface__transformers
src/transformers/models/mobilebert/modeling_mobilebert.py
{ "start": 12241, "end": 13297 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.use_bottleneck = config.use_bottleneck self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size) self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size) if not self...
MobileBertOutput
python
huggingface__transformers
src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py
{ "start": 23887, "end": 28868 }
class ____(GPTBigCodePreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"} def __init__(self, config): super().__init__(config) self.transformer = GPTBigCodeModel(config) self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False...
GPTBigCodeForCausalLM
python
django__django
tests/admin_views/models.py
{ "start": 15307, "end": 15489 }
class ____(models.Model): name = models.CharField(max_length=25) two = models.ForeignKey("CyclicTwo", models.CASCADE) def __str__(self): return self.name
CyclicOne
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py
{ "start": 19008, "end": 30822 }
class ____: """An instance of this class represents a context variant that will be run against *every* method in the test class, defined as a class created by inheriting from make_graphql_context_test_suite. It comes with a number of static methods with prebuilt context variants. e.g. in_memory_in_...
GraphQLContextVariant
python
walkccc__LeetCode
solutions/1057. Campus Bikes/1057.py
{ "start": 0, "end": 706 }
class ____: def assignBikes( self, workers: list[list[int]], bikes: list[list[int]], ) -> list[int]: ans = [-1] * len(workers) usedBikes = [False] * len(bikes) # buckets[k] := (i, j), where k = dist(workers[i], bikes[j]) buckets = [[] for _ in range(2001)] def dist(p1: list[in...
Solution
python
anthropics__anthropic-sdk-python
src/anthropic/types/thinking_config_disabled_param.py
{ "start": 227, "end": 326 }
class ____(TypedDict, total=False): type: Required[Literal["disabled"]]
ThinkingConfigDisabledParam
python
getsentry__sentry
src/sentry/workflow_engine/handlers/condition/latest_adopted_release_handler.py
{ "start": 838, "end": 2918 }
class ____(DataConditionHandler[WorkflowEventData]): group = DataConditionHandler.Group.ACTION_FILTER subgroup = DataConditionHandler.Subgroup.EVENT_ATTRIBUTES comparison_json_schema = { "type": "object", "properties": { "release_age_type": {"type": "string", "enum": [*ModelAgeT...
LatestAdoptedReleaseConditionHandler
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/test_dataloaders.py
{ "start": 2255, "end": 2550 }
class ____(BoringModel): def test_dataloader(self): return [DataLoader(RandomDataset(32, 64)), DataLoader(RandomDataset(32, 64), batch_size=8)] def test_step(self, batch, batch_idx, dataloader_idx): return super().test_step(batch, batch_idx)
MultiTestDataLoaderBoringModel
python
matplotlib__matplotlib
lib/matplotlib/tests/test_cbook.py
{ "start": 2000, "end": 6336 }
class ____: def setup_method(self): np.random.seed(937) self.nrows = 37 self.ncols = 4 self.data = np.random.lognormal(size=(self.nrows, self.ncols), mean=1.5, sigma=1.75) self.known_keys = sorted([ 'mean', 'med', 'q1', 'q3'...
Test_boxplot_stats
python
lxml__lxml
src/lxml/tests/common_imports.py
{ "start": 3048, "end": 3638 }
class ____(unittest.TestCase): def tearDown(self): if DEBUG_PROXY_ISSUES: gc.collect() def parse(self, text, parser=None): f = BytesIO(text) if isinstance(text, bytes) else StringIO(text) return etree.parse(f, parser=parser) def _rootstring(self, tree): return e...
HelperTestCase
python
pytorch__pytorch
test/test_autocast.py
{ "start": 7016, "end": 7910 }
class ____(TorchDispatchMode): def __init__(self, weight): super().__init__() self.dtype_cast_counter = 0 self.weight = weight def __torch_dispatch__(self, func, types, args=(), kwargs=None): if ( func is torch.ops.aten._to_copy.default and args[0] is sel...
WeightDTypeCastCounterMode
python
kamyu104__LeetCode-Solutions
Python/number-of-sets-of-k-non-overlapping-line-segments.py
{ "start": 1176, "end": 2026 }
class ____(object): def numberOfSets(self, n, k): """ :type n: int :type k: int :rtype: int """ MOD = 10**9+7 def nCr(n, r): # Time: O(n), Space: O(1) if n-r < r: return nCr(n, n-r) c = 1 for k in xrange(1, ...
Solution2
python
giampaolo__psutil
tests/test_misc.py
{ "start": 15487, "end": 20451 }
class ____(PsutilTestCase): def test_memoize_when_activated(self): class Foo: @memoize_when_activated def foo(self): calls.append(None) f = Foo() calls = [] f.foo() f.foo() assert len(calls) == 2 # activate cal...
TestCommonModule
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 682369, "end": 682694 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("UserContentEdit", graphql_name="node")
UserContentEditEdge
python
keras-team__keras
integration_tests/dataset_tests/cifar10_test.py
{ "start": 91, "end": 1195 }
class ____(testing.TestCase): def test_x_train_shape(self): (x_train, _), _ = cifar10.load_data() self.assertEqual(x_train.shape, (50000, 32, 32, 3)) def test_y_train_shape(self): (_, y_train), _ = cifar10.load_data() self.assertEqual(y_train.shape, (50000, 1)) def test_x_t...
Cifar10LoadDataTest
python
getsentry__sentry
tests/sentry/preprod/vcs/status_checks/size/test_templates.py
{ "start": 9619, "end": 13684 }
class ____(StatusCheckTestBase): """Tests for formatting artifacts in error/failure states.""" def test_failed_state_formatting(self): """Test formatting for failed state.""" artifact = PreprodArtifact.objects.create( project=self.project, state=PreprodArtifact.ArtifactS...
ErrorStateFormattingTest
python
lazyprogrammer__machine_learning_examples
unsupervised_class3/dcgan_tf.py
{ "start": 2129, "end": 3672 }
class ____: def __init__(self, name, mi, mo, output_shape, apply_batch_norm, filtersz=5, stride=2, f=tf.nn.relu): # mi = input feature map size # mo = output feature map size # NOTE!!! shape is specified in the OPPOSITE way from regular conv # self.W = tf.Variable(0.02*tf.random_normal(shape=(filtersz...
FractionallyStridedConvLayer