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
openai__openai-python
src/openai/resources/audio/translations.py
{ "start": 14237, "end": 14478 }
class ____: def __init__(self, translations: Translations) -> None: self._translations = translations self.create = to_streamed_response_wrapper( translations.create, )
TranslationsWithStreamingResponse
python
pydantic__pydantic
tests/test_plugin_loader.py
{ "start": 149, "end": 339 }
class ____: def __init__(self, name, value, group): self.name = name self.value = value self.group = group def load(self): return self.value
EntryPoint
python
django__django
django/contrib/gis/geos/libgeos.py
{ "start": 3585, "end": 3867 }
class ____(Structure): pass # Pointers to opaque GEOS geometry structures. GEOM_PTR = POINTER(GEOSGeom_t) PREPGEOM_PTR = POINTER(GEOSPrepGeom_t) CS_PTR = POINTER(GEOSCoordSeq_t) CONTEXT_PTR = POINTER(GEOSContextHandle_t) lgeos = SimpleLazyObject(load_geos)
GEOSContextHandle_t
python
realpython__materials
django-diary/source_code_step_6/entries/views.py
{ "start": 653, "end": 918 }
class ____(SuccessMessageMixin, UpdateView): model = Entry fields = ["title", "content"] success_message = "Your entry was updated!" def get_success_url(self): return reverse_lazy("entry-detail", kwargs={"pk": self.object.pk})
EntryUpdateView
python
allegroai__clearml
clearml/backend_api/services/v2_23/models.py
{ "start": 93045, "end": 93913 }
class ____(Request): """ Gets model information :param model: Model id :type model: str """ _service = "models" _action = "get_by_id" _version = "2.23" _schema = { "definitions": {}, "properties": {"model": {"description": "Model id", "type": "string"}}, "re...
GetByIdRequest
python
pytorch__pytorch
torch/_functorch/_aot_autograd/descriptors.py
{ "start": 24220, "end": 24467 }
class ____(AOTOutput): """The final offset from the functionalized RNG calls, backward only""" def expr(self) -> str: return "__philox_updated_backward_offset" @dataclasses.dataclass(frozen=True)
PhiloxUpdatedBackwardOffsetAOTOutput
python
Textualize__textual
src/textual/_animator.py
{ "start": 5296, "end": 7272 }
class ____: def __init__(self, animator: Animator, obj: object) -> None: self._animator = animator self._obj = obj def __call__( self, attribute: str, value: str | float | Animatable, *, final_value: object = ..., duration: float | None = None, ...
BoundAnimator
python
getsentry__sentry
src/sentry/api/bases/organization.py
{ "start": 12097, "end": 12842 }
class ____(TypedDict): start: datetime end: datetime project_id: list[int] project_objects: list[Project] organization_id: int environment: NotRequired[list[str]] environment_objects: NotRequired[list[Environment]] def _validate_fetched_projects( filtered_projects: Sequence[Project], ...
FilterParamsDateNotNull
python
getsentry__sentry
tests/sentry/backup/test_rpc.py
{ "start": 1462, "end": 12559 }
class ____(TestCase): """ Ensure that retries don't duplicate writes. """ def test_good_local_retry_idempotent(self) -> None: # If the response gets lost on the way to the caller, it will try again. Make sure it is # clever enough to not try to write the data twice if its already been c...
RpcImportRetryTests
python
instagram__MonkeyType
demo/models.py
{ "start": 2967, "end": 3224 }
class ____(Generic[T]): type: EventType def __init__(self, repo: RepoInterface) -> None: self.repo = repo def add(self, event: T) -> None: pass def aggregate(self) -> List[AggregatedItem]: return []
AggregatorInterface
python
networkx__networkx
networkx/algorithms/tree/tests/test_mst.py
{ "start": 17454, "end": 28157 }
class ____: """ Uses the same graph as the above class but with an added edge of twice the weight. """ def setup_method(self): # New graph edges = [ (0, 1, 5), (0, 1, 10), (1, 2, 4), (1, 2, 8), (1, 4, 6), (1, 4, 12)...
TestSpanningTreeMultiGraphIterator
python
getsentry__sentry
src/sentry/sentry_metrics/consumers/indexer/slicing_router.py
{ "start": 3063, "end": 5762 }
class ____(MessageRouter): """ Router which works based on the settings defined for slicing. """ def __init__( self, sliceable: Sliceable, ) -> None: self.__sliceable = sliceable self.__slice_to_producer: MutableMapping[int, MessageRoute] = {} _validate_slici...
SlicingRouter
python
scipy__scipy
scipy/signal/tests/test_filter_design.py
{ "start": 15103, "end": 25409 }
class ____: # @pytest.mark.parametrize('dt', 'fdgFDG') # XXX: quietly remove float128 and complex256 @pytest.mark.parametrize('dt', ['float32', 'float64', 'complex64', 'complex128']) @pytest.mark.parametrize('pairing, analog', [('nearest', False), ...
TestZpk2Sos
python
getsentry__sentry
src/sentry/notifications/platform/templates/sample.py
{ "start": 12321, "end": 14267 }
class ____(NotificationTemplate[TeamUpdateData]): category = NotificationCategory.DEBUG example_data = TeamUpdateData( team_name="Engineering", update_type="Weekly Standup Reminder", message="Don't forget about our weekly standup meeting tomorrow at 10 AM. Please prepare your updates on ...
TeamUpdateNotificationTemplate
python
mitmproxy__pdoc
test/testdata/flavors_google.py
{ "start": 6148, "end": 12587 }
class ____(object): """The summary line for a class docstring should fit on one line. If the class has public attributes, they may be documented here in an ``Attributes`` section and follow the same formatting as a function's ``Args`` section. Alternatively, attributes may be documented inline with...
ExampleClass
python
huggingface__transformers
src/transformers/models/minimax/modeling_minimax.py
{ "start": 23895, "end": 24853 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.top_k = config.num_experts_per_tok self.jitter_noise = config.router_jitter_noise self.gate = MiniMaxTopKRouter(config) self.experts = MiniMaxExperts(config) def forward(self, hidden_states: torch...
MiniMaxSparseMoeBlock
python
realpython__materials
python-dict-attribute/config_v1.py
{ "start": 0, "end": 349 }
class ____: def __init__(self, **kwargs): self.__dict__.update(kwargs) update = __init__ def __str__(self): return str(self.__dict__) config = Config(theme="light", font_size=12, language="English") print(config) user = {"theme": "dark", "font_size": 14, "language": "Spanish"} config.up...
Config
python
django-haystack__django-haystack
haystack/inputs.py
{ "start": 1191, "end": 1734 }
class ____(BaseInput): """ An input type for making exact matches. """ input_type_name = "exact" def prepare(self, query_obj): query_string = super().prepare(query_obj) if self.kwargs.get("clean", False): # We need to clean each part of the exact match. exa...
Exact
python
huggingface__transformers
src/transformers/models/prophetnet/modeling_prophetnet.py
{ "start": 43590, "end": 44895 }
class ____(GradientCheckpointingLayer): """ Encoder block for Prophetnet """ def __init__(self, config: ProphetNetConfig): super().__init__() # 1st residual block self.self_attn = ProphetNetAttention(config, config.num_encoder_attention_heads) self.self_attn_layer_norm =...
ProphetNetEncoderLayer
python
astropy__astropy
astropy/coordinates/representation/cylindrical.py
{ "start": 454, "end": 5303 }
class ____(BaseRepresentation): """ Representation of points in 3D cylindrical coordinates. Parameters ---------- rho : `~astropy.units.Quantity` The distance from the z axis to the point(s). phi : `~astropy.units.Quantity` or str The azimuth of the point(s), in angular units, ...
CylindricalRepresentation
python
PrefectHQ__prefect
src/prefect/server/events/actions.py
{ "start": 24450, "end": 26125 }
class ____(Action): """Base class for Actions that operate on Deployments and need to infer them from events""" source: Literal["selected", "inferred"] = Field( "selected", description=( "Whether this Action applies to a specific selected " "deployment (given by `dep...
DeploymentAction
python
tox-dev__tox
src/tox/tox_env/python/package.py
{ "start": 1290, "end": 5183 }
class ____(Python, PackageToxEnv, ABC): def __init__(self, create_args: ToxEnvCreateArgs) -> None: self._wheel_build_envs: dict[str, PythonPackageToxEnv] = {} super().__init__(create_args) def _setup_env(self) -> None: """Setup the tox environment.""" super()._setup_env() ...
PythonPackageToxEnv
python
huggingface__transformers
src/transformers/models/ministral/modeling_ministral.py
{ "start": 22089, "end": 22494 }
class ____(GenericForQuestionAnswering, MinistralPreTrainedModel): base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model` __all__ = [ "MinistralPreTrainedModel", "MinistralModel", "MinistralForCausalLM", "MinistralForSequenceClassification", "MinistralForT...
MinistralForQuestionAnswering
python
lepture__authlib
authlib/integrations/httpx_client/oauth2_client.py
{ "start": 808, "end": 1549 }
class ____(Auth, TokenAuth): """Sign requests for OAuth 2.0, currently only bearer token is supported.""" requires_request_body = True def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: try: url, headers, body = self.prepare( str(request...
OAuth2Auth
python
getsentry__sentry
src/sentry/integrations/discord/types.py
{ "start": 24, "end": 464 }
class ____(Enum): # https://discord.com/developers/docs/topics/permissions#permissions VIEW_CHANNEL = 1 << 10 SEND_MESSAGES = 1 << 11 SEND_TTS_MESSAGES = 1 << 12 EMBED_LINKS = 1 << 14 ATTACH_FILES = 1 << 15 MANAGE_THREADS = 1 << 34 CREATE_PUBLIC_THREADS = 1 << 35 CREATE_PRIVATE_THREA...
DiscordPermissions
python
dagster-io__dagster
python_modules/libraries/dagster-k8s/dagster_k8s/component.py
{ "start": 421, "end": 1999 }
class ____(Component, Resolvable): """Component that creates assets backed by kubernetes pod execution via Dagster Pipes.""" name: str assets: Sequence[ResolvedAssetSpec] image: Optional[str] = None command: Optional[Union[str, Sequence[str]]] = None namespace: Optional[str] = None env: Opt...
PipesK8sComponent
python
pyodide__pyodide
src/py/pyodide/webloop.py
{ "start": 35124, "end": 36631 }
class ____(asyncio.DefaultEventLoopPolicy): """ A simple event loop policy for managing :py:class:`WebLoop`-based event loops. """ def __init__(self): self._default_loop = None def get_event_loop(self): """Get the current event loop""" if self._default_loop: ret...
WebLoopPolicy
python
pytorch__pytorch
test/mobile/model_test/android_api_module.py
{ "start": 69, "end": 3776 }
class ____(torch.jit.ScriptModule): @torch.jit.script_method def forward(self, input): return None @torch.jit.script_method def eqBool(self, input: bool) -> bool: return input @torch.jit.script_method def eqInt(self, input: int) -> int: return input @torch.jit.scri...
AndroidAPIModule
python
huggingface__transformers
src/transformers/models/csm/modeling_csm.py
{ "start": 30020, "end": 30598 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.embed_audio_tokens = nn.Embedding((config.num_codebooks * config.vocab_size), config.hidden_size) self.register_buffer( "audio_tokens_offsets", torch.arange(config.num_codebooks) * config.vocab_size, persi...
CsmBackboneModelEmbeddings
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_privacy_urls.py
{ "start": 9237, "end": 9450 }
class ____(ProjectMixin): def test_private_urls(self): from readthedocs.projects.urls.private import urlpatterns self._test_url(urlpatterns) # ## Public Project Testing ###
PrivateProjectMixin
python
wandb__wandb
wandb/sdk/lib/auth/wbnetrc.py
{ "start": 216, "end": 5408 }
class ____(Exception): """Could not write to the netrc file.""" def read_netrc_auth(*, host: str) -> str | None: """Read a W&B API key from the .netrc file. Args: host: The W&B server URL. Returns: An API key for the host, or None if there's no .netrc file or if it doesn't co...
WriteNetrcError
python
pytorch__pytorch
test/inductor/test_fuzzer.py
{ "start": 1283, "end": 7706 }
class ____(TestCase): def test_sampling_method_toggle(self): toggle = SamplingMethod.dispatch(SamplingMethod.TOGGLE) self.assertEqual(toggle("", bool, False), True) self.assertEqual(toggle("", bool, True), False) self.assertEqual(toggle("", Literal["foo", "bar"], "foo"), "bar") ...
TestConfigFuzzer
python
neetcode-gh__leetcode
python/0076-minimum-window-substring.py
{ "start": 0, "end": 965 }
class ____: def minWindow(self, s: str, t: str) -> str: if len(s) < len(t): return "" countT, window = {}, {} for c in t: countT[c] = 1 + countT.get(c, 0) have, need = 0, len(countT) res, resLen = [-1, -1], float("infinity") l = 0 for...
Solution
python
geekcomputers__Python
BlackJack_game/blackjack_simulate.py
{ "start": 5378, "end": 7678 }
class ____: def __init__(self, name, role, chips_amount=None, color="END"): """ :param name: User name :param role: dealer or player :param chips_amount: Casino tokens equal money """ self.name = name self.prompt = "{role} >> ({name}) : ".format(role=role, nam...
User
python
Netflix__metaflow
test/unit/configs/test_config_plain.py
{ "start": 234, "end": 2040 }
class ____: """Test Config with plain=True option.""" def test_flow_completes(self, config_plain_run): """Test that the flow completes successfully.""" assert config_plain_run.successful assert config_plain_run.finished def test_plain_string_without_parser(self, config_plain_run): ...
TestConfigPlain
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 39097, "end": 39255 }
class ____(AutomationRuleMixin, DeleteViewWithMessage): success_message = _("Automation rule deleted") http_method_names = ["post"]
AutomationRuleDelete
python
readthedocs__readthedocs.org
readthedocs/api/v3/permissions.py
{ "start": 1269, "end": 1553 }
class ____(BasePermission): """Grant permission if user has admin rights on the Project.""" def has_permission(self, request, view): project = view._get_parent_project() if view.has_admin_permission(request.user, project): return True
IsProjectAdmin
python
doocs__leetcode
solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/Solution.py
{ "start": 0, "end": 589 }
class ____: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: def bfs(s: int): q = deque([s]) vis = {s} while q: i = q.popleft() for j in g[i]: if j not in vis: vis.add(j)...
Solution
python
google__pytype
pytype/pytd/slots_test.py
{ "start": 75, "end": 821 }
class ____(unittest.TestCase): """Test the operator mappings in slots.py.""" def test_reverse_name_mapping(self): for operator in ( "add", "and", "div", "divmod", "floordiv", "lshift", "matmul", "mod", "mul", "or", "pow", ...
TestPytd
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py
{ "start": 450, "end": 585 }
class ____: def f(self): print("f") def defined_outside(self): super(MyClass, self).f() # CANNOT use super()
BaseClass
python
celery__celery
t/unit/worker/test_loops.py
{ "start": 925, "end": 4481 }
class ____: def __init__(self, app, heartbeat=None, on_task_message=None, transport_driver_type=None): hub = Hub() ( self.obj, self.connection, self.consumer, self.blueprint, self.hub, self.qos, sel...
X
python
huggingface__transformers
src/transformers/models/fuyu/modeling_fuyu.py
{ "start": 11021, "end": 17485 }
class ____(FuyuPreTrainedModel, GenerationMixin): _checkpoint_conversion_mapping = { "^language_model.model": "model.language_model", "^vision_embed_tokens": "model.vision_embed_tokens", "^language_model.lm_head": "lm_head", } _tied_weights_keys = {"lm_head.weight": "model.language_m...
FuyuForCausalLM
python
astropy__astropy
astropy/cosmology/_src/tests/flrw/test_wpwazpcdm.py
{ "start": 3893, "end": 7890 }
class ____( FLRWTest, ParameterwpTestMixin, ParameterwaTestMixin, ParameterzpTestMixin ): """Test :class:`astropy.cosmology.wpwaCDM`.""" def setup_class(self): """Setup for testing.""" super().setup_class(self) self.cls = wpwaCDM self.cls_kwargs.update(wp=-0.9, wa=0.2, zp=0....
TestwpwaCDM
python
python-excel__xlwt
xlwt/antlr.py
{ "start": 36257, "end": 46976 }
class ____(TokenStream): ## class members NO_CHAR = 0 EOF_CHAR = '' ### EOF shall be the empty string. def __init__(self, *argv, **kwargs): super(CharScanner, self).__init__() self.saveConsumedInput = True self.tokenClass = None self.caseSensitive = True self.ca...
CharScanner
python
doocs__leetcode
solution/2900-2999/2924.Find Champion II/Solution.py
{ "start": 0, "end": 221 }
class ____: def findChampion(self, n: int, edges: List[List[int]]) -> int: indeg = [0] * n for _, v in edges: indeg[v] += 1 return -1 if indeg.count(0) != 1 else indeg.index(0)
Solution
python
spack__spack
lib/spack/spack/version/version_types.py
{ "start": 7111, "end": 7750 }
class ____(VersionType): """Base type for versions that represents a single (non-range or list) version.""" def _stringify_version(versions: VersionTuple, separators: Tuple[str, ...]) -> str: """Create a string representation from version components.""" release, prerelease = versions components = [f"...
ConcreteVersion
python
astropy__astropy
astropy/time/tests/test_ut1.py
{ "start": 1331, "end": 2558 }
class ____: def setup_class(cls): # Need auto_download so that IERS_B won't be loaded and cause tests to # fail. iers_conf.auto_download = True def teardown_class(cls): # This setting is to be consistent with astropy/conftest.py iers_conf.auto_download = False def t...
TestTimeUT1Remote
python
eventlet__eventlet
tests/hub_test.py
{ "start": 6391, "end": 7976 }
class ____(tests.LimitedTestCase): def test_exceptionpreservation(self): # events for controlling execution order gt1event = eventlet.Event() gt2event = eventlet.Event() def test_gt1(): try: raise KeyError() except KeyError: g...
TestExceptionInGreenthread
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py
{ "start": 5898, "end": 6421 }
class ____(BaseModel): class Config: extra = Extra.allow type: Literal["CustomRecordFilter"] class_name: str = Field( ..., description="Fully-qualified name of the class that will be implementing the custom record filter strategy. The format is `source_<name>.<package>.<class_name>`...
CustomRecordFilter
python
google__jax
jax/experimental/jax2tf/tests/flax_models/gnn.py
{ "start": 1678, "end": 4135 }
class ____(nn.Module): """A complete Graph Network model defined with Jraph.""" latent_size: int num_mlp_layers: int message_passing_steps: int output_globals_size: int dropout_rate: float = 0 skip_connections: bool = True use_edge_model: bool = True layer_norm: bool = True deterministic: bool = Tr...
GraphNet
python
openai__openai-python
src/openai/types/beta/realtime/transcription_session_update.py
{ "start": 801, "end": 963 }
class ____(BaseModel): expires_at: Optional[SessionClientSecretExpiresAt] = None """Configuration for the ephemeral token expiration."""
SessionClientSecret
python
pytorch__pytorch
test/dynamo/test_deviceguard.py
{ "start": 1707, "end": 3092 }
class ____(torch._dynamo.test_case.TestCase): """ Unit tests for the DeviceGuard class using a CudaInterface. """ def setUp(self): super().setUp() self.device_interface = CudaInterface @unittest.skipIf(not TEST_MULTIGPU, "need multiple GPU") def test_device_guard(self): ...
TestCUDADeviceGuard
python
sqlalchemy__sqlalchemy
test/sql/test_select.py
{ "start": 1689, "end": 17885 }
class ____(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default" def test_old_bracket_style_fail(self): with expect_raises_message( exc.ArgumentError, r"Column expression, FROM clause, or other columns clause .*" r".*Did you mean to say", ): ...
SelectTest
python
python-poetry__poetry
src/poetry/mixology/incompatibility_cause.py
{ "start": 278, "end": 338 }
class ____(IncompatibilityCauseError): pass
RootCauseError
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/math_ops/segment_reduction_ops_test.py
{ "start": 54453, "end": 56887 }
class ____(test.Benchmark): outer_dim_options = [2**x for x in range(9, 14, 2)] ratio_options = [2**x for x in range(1, 6, 2)] inner_dim_options = [2**x for x in range(9, 14, 2)] # randomly generated sizes with less alignments inner_dim_options += [ 1120, 1215, 1856, 1302, 1329, 1531, 1313, 1672, 1851, ...
SegmentReductionOpBenchmark
python
astropy__astropy
astropy/io/votable/exceptions.py
{ "start": 23458, "end": 23855 }
class ____(VOTableSpecWarning): """ The given element was not supported inside of the given element until the specified VOTable version, however the version declared in the file is for an earlier version. These attributes may not be written out to the file. """ message_template = "'{}' ins...
W26
python
getsentry__sentry
src/sentry/monitors/models.py
{ "start": 21442, "end": 22613 }
class ____(BaseManager["MonitorEnvironment"]): """ A manager that consolidates logic for monitor environment updates """ def ensure_environment( self, project: Project, monitor: Monitor, environment_name: str | None ) -> MonitorEnvironment: from sentry.monitors.rate_limit import upd...
MonitorEnvironmentManager
python
scipy__scipy
scipy/optimize/_shgo.py
{ "start": 61425, "end": 61586 }
class ____: def __init__(self, v): self.v = v self.x_l = None self.lres = None self.f_min = None self.lbounds = []
LMap
python
bokeh__bokeh
src/bokeh/models/sources.py
{ "start": 30381, "end": 31824 }
class ____(ColumnDataSource): ''' Base class for web column data sources that can update from data URLs. .. note:: This base class is typically not useful to instantiate on its own. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> Non...
WebDataSource
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 42949, "end": 44982 }
class ____(UserDefinedObjectVariable): """ Represents a torch._C._ImperativeEngine instance. """ def __init__( self, value, value_type=None, **kwargs, ) -> None: super().__init__(value=value, value_type=value_type, **kwargs) def call_method( self...
AutogradEngineVariable
python
allegroai__clearml
examples/frameworks/jsonargparse/jsonargparse_command.py
{ "start": 56, "end": 347 }
class ____: def __init__(self, prize: int = 100): self.prize = prize def person(self, name: str): return "{} won {}!".format(name, self.prize) if __name__ == "__main__": Task.init(project_name="examples", task_name="jsonargparse command") print(CLI(Main))
Main
python
wandb__wandb
tools/cloud_tool.py
{ "start": 1912, "end": 3978 }
class ____: """A simple CLI for managing GKE clusters. It is assumed that the user has installed the Google Cloud SDK with the required components (gke-gcloud-auth-plugin and kubectl) and has authenticated with the Google Cloud Platform. """ def __init__( self, config: GKEConfi...
GKE
python
falconry__falcon
examples/recipes/msgspec_media_validation.py
{ "start": 73, "end": 397 }
class ____: def process_resource( self, req: Request, resp: Response, resource: object, params: dict ) -> None: if schema := getattr(resource, f'{req.method}_SCHEMA', None): param = schema.__name__.lower() params[param] = msgspec.convert(req.get_media(), schema)
MsgspecMiddleware
python
walkccc__LeetCode
solutions/1233. Remove Sub-Folders from the Filesystem/1233.py
{ "start": 0, "end": 285 }
class ____: def removeSubfolders(self, folder: list[str]) -> list[str]: ans = [] prev = "" folder.sort() for f in folder: if len(prev) > 0 and f.startswith(prev) and f[len(prev)] == '/': continue ans.append(f) prev = f return ans
Solution
python
rapidsai__cudf
python/cudf/cudf/core/groupby/groupby.py
{ "start": 111657, "end": 114906 }
class ____(GroupBy): obj: Series def agg(self, func, *args, engine=None, engine_kwargs=None, **kwargs): result = super().agg( func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs ) # downcast the result to a Series: if result._num_columns: i...
SeriesGroupBy
python
numpy__numpy
numpy/_core/tests/test_multiarray.py
{ "start": 193639, "end": 199983 }
class ____: sizes = [(), (3,), (3, 2), (2, 3), (3, 3), (2, 3, 4), (4, 3, 2), (1, 2, 3, 4), (2, 3, 4, 1), (3, 4, 1, 2), (4, 1, 2, 3), (64,), (128,), (256,)] @pytest.mark.parametrize("size, axis", itertools.chain(*[[(size, axis) for axis in list(range(...
TestArgmaxArgminCommon
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-oci-data-science/tests/test_oci_data_science_utils.py
{ "start": 7943, "end": 9359 }
class ____: """Unit tests for _get_response_token_counts function.""" def test_with_usage(self): """Ensures token counts are extracted correctly when usage is present.""" raw_response = { "usage": { "prompt_tokens": 10, "completion_tokens": 5, ...
TestGetResponseTokenCounts
python
wandb__wandb
wandb/automations/scopes.py
{ "start": 1680, "end": 2290 }
class ____(_BaseScope, ProjectScopeFields): """An automation scope defined by a specific `Project`.""" scope_type: Literal[ScopeType.PROJECT] = ScopeType.PROJECT # for type annotations AutomationScope: TypeAlias = Annotated[ Union[_ArtifactSequenceScope, _ArtifactPortfolioScope, ProjectScope], Before...
ProjectScope
python
huggingface__transformers
tests/models/video_llava/test_modeling_video_llava.py
{ "start": 1478, "end": 6671 }
class ____: def __init__( self, parent, ignore_index=-100, image_token_index=0, video_token_index=1, projector_hidden_act="gelu", seq_length=3, num_frames=2, vision_feature_select_strategy="default", vision_feature_layer=-1, tex...
VideoLlavaVisionText2TextModelTester
python
ansible__ansible
lib/ansible/module_utils/facts/system/distribution.py
{ "start": 1181, "end": 23197 }
class ____: """has-a various distro file parsers (os-release, etc) and logic for finding the right one.""" # every distribution name mentioned here, must have one of # - allowempty == True # - be listed in SEARCH_STRING # - have a function get_distribution_DISTNAME implemented # keep names in...
DistributionFiles
python
huggingface__transformers
src/transformers/models/seed_oss/modeling_seed_oss.py
{ "start": 22412, "end": 22515 }
class ____(GenericForTokenClassification, SeedOssPreTrainedModel): pass
SeedOssForTokenClassification
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/waiters/test_opensearch_serverless.py
{ "start": 1534, "end": 2987 }
class ____(TestOpenSearchServerlessCustomWaitersBase): WAITER_NAME = "collection_available" @pytest.fixture def mock_getter(self): with mock.patch.object(self.client, "batch_get_collection") as getter: yield getter @pytest.mark.parametrize("state", OpenSearchServerlessCollectionAct...
TestCollectionAvailableWaiter
python
pdm-project__pdm
src/pdm/cli/commands/publish/package.py
{ "start": 1040, "end": 8267 }
class ____: """A distribution file for upload. XXX: currently only supports sdist and wheel. """ filename: str metadata: email.message.Message comment: str | None py_version: str | None filetype: str def __post_init__(self) -> None: self.base_filename = os.path.basename(se...
PackageFile
python
PyCQA__pyflakes
pyflakes/test/test_api.py
{ "start": 25234, "end": 25706 }
class ____(IntegrationTests): """ Tests of the pyflakes main function. """ def runPyflakes(self, paths, stdin=None): try: with SysStreamCapturing(stdin) as capture: main(args=paths) except SystemExit as e: self.assertIsInstance(e.code, bool) ...
TestMain
python
huggingface__transformers
src/transformers/models/lfm2/modeling_lfm2.py
{ "start": 19452, "end": 23540 }
class ____(nn.Module): def __init__( self, config: Lfm2Config, layer_idx: int, ): super().__init__() self.config = config self.layer_idx = layer_idx self.L_cache = config.conv_L_cache self.bias = config.conv_bias self.conv = nn.Conv1d( ...
Lfm2ShortConv
python
aimacode__aima-python
probability4e.py
{ "start": 814, "end": 2730 }
class ____: """A discrete probability distribution. You name the random variable in the constructor, then assign and query probability of values. >>> P = ProbDist('Flip'); P['H'], P['T'] = 0.25, 0.75; P['H'] 0.25 >>> P = ProbDist('X', {'lo': 125, 'med': 375, 'hi': 500}) >>> P['lo'], P['med'], P[...
ProbDist
python
tornadoweb__tornado
tornado/test/testing_test.py
{ "start": 3608, "end": 6024 }
class ____(unittest.TestCase): # These tests verify that tests that return non-None values (without being decorated with # @gen_test) raise errors instead of incorrectly succeeding. These tests should be removed or # updated when the _callTestMethod method is removed from AsyncTestCase (the same checks will...
AsyncTestCaseReturnAssertionsTest
python
apache__airflow
helm-tests/tests/helm_tests/security/test_security_context.py
{ "start": 4379, "end": 21613 }
class ____: """Tests security context.""" # Test securityContext setting for Pods and Containers def test_check_default_setting(self): docs = render_chart( values={ "securityContext": {"runAsUser": 6000, "fsGroup": 60}, "webserver": {"defaultUser": {"enab...
TestSecurityContext
python
realpython__materials
python-inherit-list-userlist/custom_list2.py
{ "start": 35, "end": 433 }
class ____(UserList): def join(self, separator=" "): return separator.join(str(item) for item in self) def map(self, action): return type(self)(action(item) for item in self.data) def filter(self, predicate): return type(self)(item for item in self if predicate(item)) def for_...
CustomList
python
openai__gym
gym/error.py
{ "start": 4029, "end": 4136 }
class ____(Error): """Error message when an invalid frame is captured.""" # Wrapper errors
InvalidFrame
python
Pylons__pyramid
src/pyramid/security.py
{ "start": 15732, "end": 16724 }
class ____(ACLPermitsResult, Allowed): """ An instance of ``ACLAllowed`` is a specialization of :class:`pyramid.security.Allowed` that represents that a security check made explicitly against ACL was allowed. It evaluates equal to all boolean true types. It also has the following attributes: ``acl...
ACLAllowed
python
huggingface__transformers
tests/repo_utils/test_check_copies.py
{ "start": 3488, "end": 4017 }
class ____: attr_1 = 1 attr_2 = 2 def __init__(self, a=1, b=2): self.a = a self.b = b # Ignore copy def only_in_roberta_to_be_ignored(self, c): return 3 # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward def forward(self, c): ...
RobertaBertDummyModel
python
realpython__materials
python-textual/vertical_scroll.py
{ "start": 127, "end": 410 }
class ____(App): CSS_PATH = "vertical_layout.tcss" def compose(self): with VerticalScroll(): for i in range(NUM_BOXES): yield Static(f"Static {i + 1}") if __name__ == "__main__": app = VerticalScrollApp() app.run()
VerticalScrollApp
python
mlflow__mlflow
mlflow/utils/file_utils.py
{ "start": 1856, "end": 7526 }
class ____: def __init__(self, desc, total, step, **kwargs) -> None: self.desc = desc self.total = total self.step = step self.pbar = None self.progress = 0 self.kwargs = kwargs def set_pbar(self): if MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR.get(): ...
ArtifactProgressBar
python
sympy__sympy
sympy/functions/special/error_functions.py
{ "start": 14013, "end": 19347 }
class ____(DefinedFunction): r""" Imaginary error function. Explanation =========== The function erfi is defined as: .. math :: \mathrm{erfi}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{t^2} \mathrm{d}t Examples ======== >>> from sympy import I, oo, erfi >>> from sympy.abc...
erfi
python
getsentry__sentry
src/sentry/data_export/base.py
{ "start": 393, "end": 595 }
class ____(str, Enum): Early = "EARLY" # The download is being prepared Valid = "VALID" # The download is ready for the user Expired = "EXPIRED" # The download has been deleted
ExportStatus
python
gevent__gevent
src/greentest/3.10/test_asyncore.py
{ "start": 14746, "end": 14973 }
class ____(BaseTestHandler): def __init__(self, family, address): BaseTestHandler.__init__(self) self.create_socket(family) self.connect(address) def handle_connect(self): pass
BaseClient
python
pytorch__pytorch
torch/_dynamo/variables/ctx_manager.py
{ "start": 27480, "end": 30117 }
class ____(ContextWrappingVariable): """represents whether torch function overrides are enabled or not""" _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.TORCH_FUNCTION_STATE) # type: ignore[arg-type] @staticmethod def create( tx: "InstructionTranslator", **kwargs: Any ) -> "T...
TorchFunctionDisableVariable
python
pydantic__pydantic
pydantic-core/tests/serializers/test_list_tuple.py
{ "start": 8194, "end": 19309 }
class ____(ImplicitContains): __contains__ = None # This might be done to explicitly force the `x in RemovedContains()` check to not be allowed @pytest.mark.parametrize( 'include,exclude,expected', [ ({1, 3}, None, ['b', 'd']), ({1, 3, 5}, {5}, ['b', 'd']), ({2: None, 3: None, 5: ...
RemovedContains
python
jupyterlab__jupyterlab
jupyterlab/browser_check.py
{ "start": 6108, "end": 7639 }
class ____(LabApp): """An app the launches JupyterLab and waits for it to start up, checking for JS console errors, JS errors, and Python logged errors. """ name = __name__ open_browser = False serverapp_config = {"base_url": "/foo/"} default_url = Unicode("/lab?reset", config=True, help="...
BrowserApp
python
kubernetes-client__python
kubernetes/client/models/v1_container_user.py
{ "start": 383, "end": 3363 }
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...
V1ContainerUser
python
huggingface__transformers
tests/models/splinter/test_modeling_splinter.py
{ "start": 1193, "end": 7537 }
class ____: def __init__( self, parent, batch_size=13, num_questions=3, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, question_token_id=1, ...
SplinterModelTester
python
getsentry__sentry
src/sentry/charts/chartcuterie.py
{ "start": 432, "end": 3262 }
class ____(ChartRenderer): """ The Chartcuterie service is responsible for converting series data into a chart of the data as an image. This uses the external Chartcuterie API to produce charts """ @property def service_url(self) -> str | None: return options.get("chart-rendering.c...
Chartcuterie
python
apache__airflow
airflow-core/src/airflow/models/dag.py
{ "start": 11867, "end": 31347 }
class ____(Base): """Table containing DAG properties.""" __tablename__ = "dag" """ These items are stored in the database for state related information. """ dag_id: Mapped[str] = mapped_column(StringID(), primary_key=True) # A DAG can be paused from the UI / DB # Set this default value ...
DagModel
python
pytorch__pytorch
test/distributed/launcher/test_run.py
{ "start": 1693, "end": 26848 }
class ____(TestCase): def setUp(self): self.test_dir = tempfile.mkdtemp() # remove any lingering environment variables for env in os.environ.keys(): # noqa: SIM118 if env.startswith("PET_"): del os.environ[env] # set a sentinel env var on the parent pro...
ElasticLaunchTest
python
tiangolo__fastapi
docs_src/dependencies/tutorial011.py
{ "start": 56, "end": 504 }
class ____: def __init__(self, fixed_content: str): self.fixed_content = fixed_content def __call__(self, q: str = ""): if q: return self.fixed_content in q return False checker = FixedContentQueryChecker("bar") @app.get("/query-checker/") async def read_query_check(fixe...
FixedContentQueryChecker
python
huggingface__transformers
src/transformers/models/auto/configuration_auto.py
{ "start": 40390, "end": 44579 }
class ____(OrderedDict[str, str]): """ A mapping that will load all pairs of key values at the first access (either by indexing, requestions keys, values, etc.) Args: mapping: The mapping to load. """ def __init__(self, mapping): self._mapping = mapping self._initialize...
_LazyLoadAllMappings
python
airbytehq__airbyte
airbyte-integrations/connectors/source-recurly/components.py
{ "start": 204, "end": 503 }
class ____(RecordExtractor): def extract_records(self, response: requests.Response) -> List[Mapping[str, Any]]: try: dates = response.json()["dates"] except requests.exceptions.JSONDecodeError: dates = [] return [{"dates": dates}]
ExportDatesExtractor
python
django__django
django/contrib/sessions/backends/base.py
{ "start": 676, "end": 799 }
class ____(Exception): """ Occurs if Django tries to update a session that was deleted. """ pass
UpdateError
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 39877, "end": 40044 }
class ____(panel_grid_minor_x, panel_grid_minor_y): """ Minor grid lines Parameters ---------- theme_element : element_line """
panel_grid_minor