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
huggingface__transformers
src/transformers/models/git/modeling_git.py
{ "start": 33652, "end": 35601 }
class ____(GitPreTrainedModel): config: GitVisionConfig main_input_name = "pixel_values" input_modalities = ("image",) # Copied from transformers.models.clip.modeling_clip.CLIPVisionModel.__init__ with CLIP->Git def __init__(self, config: GitVisionConfig): super().__init__(config) s...
GitVisionModel
python
openai__openai-python
src/openai/lib/streaming/chat/_events.py
{ "start": 437, "end": 665 }
class ____(BaseModel): """This event is yielded for every chunk with `choice.delta.content` data.""" type: Literal["content.delta"] delta: str snapshot: str parsed: Optional[object] = None
ContentDeltaEvent
python
django__django
tests/select_related_onetoone/models.py
{ "start": 1581, "end": 1817 }
class ____(models.Model): name = models.CharField(max_length=50) previous_item = models.OneToOneField( "self", models.CASCADE, related_name="next_item", blank=True, null=True, )
LinkedList
python
realpython__materials
fastapi-url-shortener/source_code_final/shortener_app/config.py
{ "start": 69, "end": 408 }
class ____(BaseSettings): env_name: str = "Local" base_url: str = "http://localhost:8000" db_url: str = "sqlite:///./shortener.db" class Config: env_file = ".env" @lru_cache def get_settings() -> Settings: settings = Settings() print(f"Loading settings for: {settings.env_name}") r...
Settings
python
aio-libs__aiohttp
aiohttp/abc.py
{ "start": 2628, "end": 3012 }
class ____(ABC): """Abstract class based view.""" def __init__(self, request: Request) -> None: self._request = request @property def request(self) -> Request: """Request instance.""" return self._request @abstractmethod def __await__(self) -> Generator[None, None, Str...
AbstractView
python
scrapy__scrapy
scrapy/spidermiddlewares/base.py
{ "start": 396, "end": 3994 }
class ____: """Optional base class for spider middlewares. .. versionadded:: 2.13 This class provides helper methods for asynchronous ``process_spider_output()`` and ``process_start()`` methods. Middlewares that don't have either of these methods don't need to use this class. You can override...
BaseSpiderMiddleware
python
numba__numba
numba/cuda/tests/cudapy/test_record_dtype.py
{ "start": 8725, "end": 9106 }
class ____(TestRecordDtype): ''' Same as TestRecordDtype, but using structured arrays instead of recarrays. ''' def _createSampleArrays(self): self.sample1d = np.zeros(3, dtype=recordtype) self.samplerec1darr = np.zeros(1, dtype=recordwitharray)[0] self.samplerec2darr = np.zeros...
TestRecordDtypeWithStructArrays
python
numba__numba
numba/core/types/containers.py
{ "start": 14594, "end": 14754 }
class ____(BaseContainerPayload): """ Internal type class for the dynamically-allocated payload of a list. """ container_class = List
ListPayload
python
realpython__materials
duck-typing-python/shapes.py
{ "start": 50, "end": 147 }
class ____(Protocol): def area(self) -> float: ... def perimeter(self) -> float: ...
Shape
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDict19.py
{ "start": 317, "end": 832 }
class ____(TypedDict): x: Required[str] def func1(td: TD1 | TD2): # This should generate an error because "x" is not required in TD1. v1 = td["x"] def func2(td: TD1 | TD2): td["x"] = "hi" v1 = td["x"] def func3(td: TD1 | TD2, opt: bool): if opt: td["x"] = "hi" # This should ge...
TD2
python
getsentry__sentry
src/sentry/sentry_metrics/use_case_id_registry.py
{ "start": 305, "end": 2559 }
class ____(Enum): SPANS = "spans" TRANSACTIONS = "transactions" SESSIONS = "sessions" ESCALATING_ISSUES = "escalating_issues" PROFILES = "profiles" METRIC_STATS = "metric_stats" USE_CASE_ID_API_ACCESSES: Mapping[UseCaseID, UseCaseIDAPIAccess] = { UseCaseID.SPANS: UseCaseIDAPIAccess.PUBLIC,...
UseCaseID
python
getsentry__sentry
src/sentry/api/serializers/models/event.py
{ "start": 1773, "end": 4933 }
class ____(EventTagOptional): key: str value: str def get_crash_files(events): event_ids = [x.event_id for x in events if x.platform == "native"] if event_ids: return [ ea for ea in EventAttachment.objects.filter(event_id__in=event_ids) if ea.type in CRASH_F...
EventTag
python
donnemartin__system-design-primer
solutions/system_design/query_cache/query_cache_snippets.py
{ "start": 26, "end": 704 }
class ____(object): def __init__(self, memory_cache, reverse_index_cluster): self.memory_cache = memory_cache self.reverse_index_cluster = reverse_index_cluster def parse_query(self, query): """Remove markup, break text into terms, deal with typos, normalize capitalization, con...
QueryApi
python
agronholm__apscheduler
src/apscheduler/_enums.py
{ "start": 475, "end": 921 }
class ____(Enum): """ Used to track the running state of schedulers. .. attribute:: starting not running yet, but in the process of starting .. attribute:: started running .. attribute:: stopping still running but in the process of shutting down .. attribute:: stop...
RunState
python
pypa__warehouse
warehouse/manage/forms.py
{ "start": 1220, "end": 1626 }
class ____: username = wtforms.StringField( validators=[wtforms.validators.InputRequired(message="Specify username")] ) def validate_username(self, field): userid = self.user_service.find_userid(field.data) if userid is None: raise wtforms.validators.ValidationError( ...
UsernameMixin
python
zarr-developers__zarr-python
src/zarr/testing/buffer.py
{ "start": 544, "end": 658 }
class ____(cpu.Buffer): """Example of a custom Buffer that handles ArrayLike""" __test__ = False
TestBuffer
python
walkccc__LeetCode
solutions/1986. Minimum Number of Work Sessions to Finish the Tasks/1986.py
{ "start": 0, "end": 967 }
class ____: def minSessions(self, tasks: list[int], sessionTime: int) -> int: # Returns True if we can assign tasks[s..n) to `sessions`. Note that `sessions` # may be occupied by some tasks. def dfs(s: int, sessions: list[int]) -> bool: if s == len(tasks): return True for i, session i...
Solution
python
pytorch__pytorch
torch/utils/benchmark/utils/compare.py
{ "start": 417, "end": 584 }
class ____(enum.Enum): NONE = "none" COLUMNWISE = "columnwise" ROWWISE = "rowwise" # Classes to separate internal bookkeeping from what is rendered.
Colorize
python
tensorflow__tensorflow
tensorflow/python/ops/math_grad_test.py
{ "start": 1462, "end": 2477 }
class ____(test.TestCase, parameterized.TestCase): @parameterized.parameters( (None, None, None, None), (None, [], None, None), ([], [], [], []), ([], [None], [0], []), ([None], [None], None, None), ([None, 1], [None], [1], [0]), ([None, 1], [1, None], [1], [0]), ([Non...
InferGradientReductionAxes
python
pytorch__pytorch
test/distributed/test_multi_threaded_pg.py
{ "start": 4865, "end": 12674 }
class ____(MultiThreadedTestCase): @property def world_size(self): return 4 def setUp(self): os.environ["TORCH_DIST_INIT_BARRIER"] = "1" super().setUp() self._spawn_threads() def tearDown(self): super().tearDown() os.environ["TORCH_DIST_INIT_BARRIER"] = ...
TestCollectivesWithBaseClass
python
coleifer__peewee
tests/base_models.py
{ "start": 1278, "end": 1402 }
class ____(TestModel): sample = ForeignKeyField(Sample, backref='metadata') value = FloatField(default=0.0)
SampleMeta
python
realpython__materials
tic-tac-toe-ai-python/source_code_step_2/tic-tac-toe/library/src/tic_tac_toe/game/players.py
{ "start": 1268, "end": 1507 }
class ____(ComputerPlayer): def get_computer_move(self, game_state: GameState) -> Move | None: try: return random.choice(game_state.possible_moves) except IndexError: return None
RandomComputerPlayer
python
google__jax
jax/_src/core.py
{ "start": 106459, "end": 108081 }
class ____: __slots__ = () def __repr__(self): return "[dynamic]" def replace_tracer_for_error_message(obj): # TODO(mattjj): Many ideas for improving this. Crawl the stack and see if # there are user variables whose value is == to this object? Or search # parameters of functions being transformed, at least...
SomeTracer
python
numba__numba
numba/cpython/builtins.py
{ "start": 16546, "end": 36165 }
class ____(AbstractTemplate): def generic(self, args, kws): assert not kws assert len(args) == 1 if isinstance(args[0], (types.DType, types.NumberClass)): return signature(args[0].dtype, *args) @lower_builtin(get_type_min_value, types.NumberClass) @lower_builtin(get_type_min_val...
MinValInfer
python
docker__docker-py
tests/integration/models_resources_test.py
{ "start": 73, "end": 614 }
class ____(BaseIntegrationTest): def test_reload(self): client = docker.from_env(version=TEST_API_VERSION) container = client.containers.run("alpine", "sleep 300", detach=True) self.tmp_containers.append(container.id) first_started_at = container.attrs['State']['StartedAt'] ...
ModelTest
python
pandas-dev__pandas
pandas/tests/scalar/timestamp/test_timestamp.py
{ "start": 14032, "end": 16305 }
class ____: def test_nanosecond_string_parsing(self): ts = Timestamp("2013-05-01 07:15:45.123456789") # GH 7878 expected_repr = "2013-05-01 07:15:45.123456789" expected_value = 1_367_392_545_123_456_789 assert ts._value == expected_value assert expected_repr in repr(t...
TestTimestampNsOperations
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/ir.py
{ "start": 75507, "end": 90110 }
class ____(IR): """A join of two dataframes.""" __slots__ = ("left_on", "options", "right_on") _non_child = ("schema", "left_on", "right_on", "options") left_on: tuple[expr.NamedExpr, ...] """List of expressions used as keys in the left frame.""" right_on: tuple[expr.NamedExpr, ...] """List...
Join
python
langchain-ai__langchain
libs/partners/anthropic/langchain_anthropic/middleware/bash.py
{ "start": 425, "end": 3203 }
class ____(ShellToolMiddleware): """Middleware that exposes Anthropic's native bash tool to models.""" def __init__( self, workspace_root: str | None = None, *, startup_commands: tuple[str, ...] | list[str] | str | None = None, shutdown_commands: tuple[str, ...] | list[s...
ClaudeBashToolMiddleware
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_axis22.py
{ "start": 315, "end": 1399 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_axis22.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
numba__numba
numba/tests/npyufunc/test_ufuncbuilding.py
{ "start": 15493, "end": 16521 }
class ____(unittest.TestCase): """Test that numba ufuncs are compatible with dask collections and wrappers around dask (e.g. xarray or pint) and that they can be serialized, sent over the network, deserialized on a different host and applied remotely. """ def test_dask_array(self): a = Fake...
TestDask
python
kamyu104__LeetCode-Solutions
Python/count-numbers-with-unique-digits.py
{ "start": 365, "end": 743 }
class ____(object): def countNumbersWithUniqueDigits(self, n): """ :type n: int :rtype: int """ fact = [1]*2 def nPr(n, k): while len(fact) <= n: # lazy initialization fact.append(fact[-1]*len(fact)) return fact[n]//fact[n-k] ...
Solution2
python
py-pdf__pypdf
pypdf/errors.py
{ "start": 1470, "end": 1569 }
class ____(PdfReadError): """Raised when a PDF file is empty or has no content."""
EmptyFileError
python
matplotlib__matplotlib
lib/matplotlib/sphinxext/plot_directive.py
{ "start": 18169, "end": 35592 }
class ____(RuntimeError): pass def _run_code(code, code_path, ns=None, function_name=None): """ Import a Python module from a path, and run the function given by name, if function_name is not None. """ # Change the working directory to the directory of the example, so # it can get at its ...
PlotError
python
airbytehq__airbyte
airbyte-integrations/connectors/source-amazon-seller-partner/unit_tests/test_migrations.py
{ "start": 3336, "end": 7067 }
class ____: test_unmigrated_config_path = MIGRATIONS_TEST_DIRECTORY / "unmigrated_config.json" test_migrated_config_path = MIGRATIONS_TEST_DIRECTORY / "migrated_config.json" def test_migrate_config(self, components_module): try: config_copy = dict(UNMIGRATED_CONFIG) assert "...
TestMigrations
python
jmcnamara__XlsxWriter
xlsxwriter/test/chartsheet/test_chartsheet01.py
{ "start": 347, "end": 1479 }
class ____(unittest.TestCase): """ Test assembling a complete Chartsheet file. """ def test_assemble_xml_file(self): """Test writing a chartsheet with no cell data.""" self.maxDiff = None fh = StringIO() chartsheet = Chartsheet() chartsheet._set_filehandle(fh) ...
TestAssembleChartsheet
python
great-expectations__great_expectations
great_expectations/profile/base.py
{ "start": 346, "end": 974 }
class ____(Enum): def __ge__(self, other): if self.__class__ is other.__class__: return self.value >= other.value return NotImplemented def __gt__(self, other): if self.__class__ is other.__class__: return self.value > other.value return NotImplemented ...
OrderedEnum
python
kubernetes-client__python
kubernetes/client/models/v1beta1_resource_claim_consumer_reference.py
{ "start": 383, "end": 6991 }
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...
V1beta1ResourceClaimConsumerReference
python
google__pytype
pytype/tools/traces/traces_test.py
{ "start": 2760, "end": 3829 }
class ____(unittest.TestCase): """Base class for testing traces.MatchAstVisitor.""" def _parse(self, text, options=None): text = textwrap.dedent(text).lstrip() return ast.parse(text), traces.trace(text, options) def _get_traces(self, text, node_type, options=None): module, src = self._parse(text, op...
MatchAstTestCase
python
facebook__pyre-check
tools/generate_taint_models/tests/get_annotated_free_functions_with_decorator_test.py
{ "start": 635, "end": 21207 }
class ____(unittest.TestCase): def assert_expected_annotations( self, source: str, annotation_specifications: List[DecoratorAnnotationSpecification], expected: Set[str], ) -> None: cleaned_source = textwrap.dedent(source) with patch("builtins.open", mock_open(read...
AnnotatedFreeFunctionWithDecoratorGeneratorTest
python
getsentry__sentry
src/sentry/middleware/sudo.py
{ "start": 112, "end": 630 }
class ____(BaseSudoMiddleware): def has_sudo_privileges(self, request: HttpRequest) -> bool: # Right now, only password reauthentication (django-sudo) is supported, # so if a user doesn't have a password (for example, only has github auth) # then we shouldn't prompt them for the password the...
SudoMiddleware
python
openai__openai-python
src/openai/types/realtime/response_audio_transcript_delta_event.py
{ "start": 210, "end": 786 }
class ____(BaseModel): content_index: int """The index of the content part in the item's content array.""" delta: str """The transcript delta.""" event_id: str """The unique ID of the server event.""" item_id: str """The ID of the item.""" output_index: int """The index of th...
ResponseAudioTranscriptDeltaEvent
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 68134, "end": 68454 }
class ____(_PrintableStructure): _fields_ = [ ('timeStamp', c_ulonglong), ('pid', c_uint), ('smUtil', c_uint), ('memUtil', c_uint), ('encUtil', c_uint), ('decUtil', c_uint), ('jpgUtil', c_uint), ('ofaUtil', c_uint), ]
c_nvmlProcessUtilizationInfo_v1_t
python
numba__llvmlite
llvmlite/ir/types.py
{ "start": 242, "end": 2565 }
class ____(_StrCaching): """ The base class for all LLVM types. """ is_pointer = False null = 'zeroinitializer' def __repr__(self): return "<%s %s>" % (type(self), str(self)) def _to_string(self): raise NotImplementedError def as_pointer(self, addrspace=0): ret...
Type
python
getsentry__sentry
src/sentry/grouping/enhancer/matchers.py
{ "start": 12395, "end": 12454 }
class ____(FrameFieldMatch): field = "module"
ModuleMatch
python
getsentry__sentry
tests/sentry/issues/test_occurrence_consumer.py
{ "start": 3144, "end": 13222 }
class ____(IssueOccurrenceTestBase): @django_db_all def test_occurrence_consumer_with_event(self) -> None: message = get_test_message(self.project.id) with self.feature("organizations:profile-file-io-main-thread-ingest"): result = _process_message(message) assert result is no...
IssueOccurrenceProcessMessageTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 339497, "end": 340116 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("EnvironmentEdge"), graphql_name="edges" ) nodes = sgqlc.t...
EnvironmentConnection
python
pytorch__pytorch
torch/fx/experimental/recording.py
{ "start": 19361, "end": 19950 }
class ____(Exception): def __init__( self, msg: str, mismatched: list[tuple[str, str, str]], ) -> None: details = "\n".join( [ "\n".join( [ f"==> {inner_msg}", f" > Left: {str1}", ...
NotEqualError
python
python-pillow__Pillow
src/PIL/ImageFile.py
{ "start": 25976, "end": 27727 }
class ____(PyCodec): """ Python implementation of a format decoder. Override this class and add the decoding logic in the :meth:`decode` method. See :ref:`Writing Your Own File Codec in Python<file-codecs-py>` """ _pulls_fd = False @property def pulls_fd(self) -> bool: return ...
PyDecoder
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_generators.py
{ "start": 16876, "end": 19107 }
class ____(__TestCase): def test_close_no_return_value(self): def f(): yield gen = f() gen.send(None) self.assertIsNone(gen.close()) def test_close_return_value(self): def f(): try: yield # close() raises Generato...
GeneratorCloseTest
python
astropy__astropy
astropy/config/configuration.py
{ "start": 1315, "end": 1635 }
class ____(AstropyWarning): """A Warning that is issued when the configuration value specified in the astropy configuration file does not match the type expected for that configuration value. """ # these are not in __all__ because it's not intended that a user ever see them
InvalidConfigurationItemWarning
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/validators/test_base_workflow.py
{ "start": 3919, "end": 13755 }
class ____(TestCase): def setUp(self) -> None: self.context = { "organization": self.organization, "request": self.make_request(user=self.user), } self.integration, self.org_integration = self.create_provider_integration_for( provider="slack", organizatio...
TestWorkflowValidatorCreate
python
pikepdf__pikepdf
tests/test_filters.py
{ "start": 711, "end": 2015 }
class ____(TokenFilter): def __init__(self): super().__init__() self.names = [] self.rawnames = [] def handle_token(self, token): if token.type_ == TokenType.name_: self.names.append(token.value) self.rawnames.append(token.raw_value) return None ...
FilterCollectNames
python
Delgan__loguru
loguru/_file_sink.py
{ "start": 5093, "end": 14951 }
class ____: def __init__( self, path, *, rotation=None, retention=None, compression=None, delay=False, watch=False, mode="a", buffering=1, encoding="utf8", **kwargs ): self.encoding = encoding self._...
FileSink
python
etianen__django-reversion
tests/test_app/tests/test_models.py
{ "start": 9847, "end": 10586 }
class ____(TestModelMixin, TestBase): def testFieldDict(self): with reversion.create_revision(): obj = TestModel.objects.create() self.assertEqual(Version.objects.get_for_object(obj).get().field_dict, { "id": obj.pk, "name": "v1", "related": [], ...
FieldDictTest
python
great-expectations__great_expectations
contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_profile_numeric_columns_percent_diff_greater_than_threshold.py
{ "start": 955, "end": 7685 }
class ____( DataProfilerProfileMetricProvider ): metric_name = "data_profiler.profile_numeric_columns_percent_diff_greater_than_threshold" value_keys = ( "profile_path", "limit_check_report_keys", "numerical_diff_statistics", ) @metric_value(engine=PandasExecutionEngine) ...
DataProfilerProfileNumericColumnsPercentDiffGreaterThanThreshold
python
pytorch__pytorch
torch/testing/_internal/distributed/rpc/faulty_rpc_agent_test_fixture.py
{ "start": 790, "end": 2142 }
class ____(RpcAgentTestFixture): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.messages_to_fail = retryable_message_types self.messages_to_delay = default_messages_to_delay @property def rpc_backend(self): return rpc.backend_registry.BackendType...
FaultyRpcAgentTestFixture
python
aimacode__aima-python
utils4e.py
{ "start": 20635, "end": 21711 }
class ____: """Given 'P |'==>'| Q, first form PartialExpr('==>', P), then combine with Q.""" def __init__(self, op, lhs): self.op, self.lhs = op, lhs def __or__(self, rhs): return Expr(self.op, self.lhs, rhs) def __repr__(self): return "PartialExpr('{}', {})".format(self.op, s...
PartialExpr
python
kamyu104__LeetCode-Solutions
Python/find-and-replace-pattern.py
{ "start": 52, "end": 530 }
class ____(object): def findAndReplacePattern(self, words, pattern): """ :type words: List[str] :type pattern: str :rtype: List[str] """ def match(word): lookup = {} for x, y in itertools.izip(pattern, word): if lookup.setdefaul...
Solution
python
wandb__wandb
wandb/sdk/artifacts/_generated/fetch_registries.py
{ "start": 833, "end": 1196 }
class ____(GQLResult): node: Optional[RegistryFragment] FetchRegistries.model_rebuild() FetchRegistriesOrganization.model_rebuild() FetchRegistriesOrganizationOrgEntity.model_rebuild() FetchRegistriesOrganizationOrgEntityProjects.model_rebuild() FetchRegistriesOrganizationOrgEntityProjectsEdges.model_rebuild()
FetchRegistriesOrganizationOrgEntityProjectsEdges
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1597099, "end": 1600448 }
class ____(Transform): """ WindowTransform schema wrapper. Parameters ---------- window : Sequence[dict, :class:`WindowFieldDef`] The definition of the fields in the window, and what calculations to use. frame : Sequence[float, None] A frame specification as a two-element array ...
WindowTransform
python
getsentry__sentry
src/sentry/core/endpoints/project_index.py
{ "start": 928, "end": 4182 }
class ____(Endpoint): publish_status = { "GET": ApiPublishStatus.PRIVATE, } permission_classes = (ProjectPermission,) def get(self, request: Request) -> Response: """ List your Projects `````````````````` Return a list of projects available to the authenticated ...
ProjectIndexEndpoint
python
ray-project__ray
rllib/utils/schedules/constant_schedule.py
{ "start": 292, "end": 1002 }
class ____(Schedule): """A Schedule where the value remains constant over time.""" def __init__(self, value: float, framework: Optional[str] = None): """Initializes a ConstantSchedule instance. Args: value: The constant value to return, independently of time. framework:...
ConstantSchedule
python
getsentry__sentry
src/sentry/api/endpoints/organization_sampling_project_rates.py
{ "start": 993, "end": 1700 }
class ____(Serializer): """Serializer for OrganizationSamplingProjectRatesEndpoint.get""" def get_attrs(self, item_list, user, **kwargs) -> MutableMapping[Any, Any]: options = ProjectOption.objects.get_value_bulk(item_list, OPTION_KEY) # NOTE: `get_value_bulk` does not resolve defaults. The def...
GetSerializer
python
gevent__gevent
src/gevent/events.py
{ "start": 11020, "end": 11178 }
class ____(IGeventPatchEvent): """ An event emitted *after* gevent has patched something. """ @implementer(IGeventDidPatchEvent)
IGeventDidPatchEvent
python
ray-project__ray
python/ray/serve/tests/test_metrics_2.py
{ "start": 846, "end": 996 }
class ____: async def __call__(self): signal = ray.get_actor("signal123") await signal.wait.remote() @serve.deployment
WaitForSignal
python
dagster-io__dagster
python_modules/libraries/dagster-dbt/dagster_dbt/errors.py
{ "start": 772, "end": 914 }
class ____(DagsterDbtError): """Error when we expect manifest.json to generated already but it is absent."""
DagsterDbtManifestNotFoundError
python
dagster-io__dagster
python_modules/libraries/dagster-celery-docker/dagster_celery_docker/executor.py
{ "start": 6169, "end": 13106 }
class ____(Executor): def __init__( self, retries, docker_config, broker=None, backend=None, include=None, config_source=None, ): self._retries = check.inst_param(retries, "retries", RetryMode) self.broker = check.opt_str_param(broker, "bro...
CeleryDockerExecutor
python
apache__airflow
providers/papermill/tests/unit/papermill/hooks/test_kernel.py
{ "start": 894, "end": 1581 }
class ____: """ Tests for Kernel connection """ def test_kernel_connection(self): """ Test that fetches kernelConnection with configured host and ports """ from airflow.providers.papermill.hooks.kernel import KernelHook conn = Connection( conn_type="...
TestKernelHook
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_emr_base.py
{ "start": 2237, "end": 4033 }
class ____: def test_poke_returns_true_when_state_is_in_target_states(self): operator = EmrBaseSensorSubclass( task_id="test_task", poke_interval=2, ) operator.response = { "SomeKey": {"State": TARGET_STATE}, "ResponseMetadata": {"HTTPStatusCod...
TestEmrBaseSensor
python
numba__numba
numba/cuda/cudadecl.py
{ "start": 3574, "end": 3877 }
class ____(ConcreteTemplate): key = cuda.match_any_sync cases = [ signature(types.i4, types.i4, types.i4), signature(types.i4, types.i4, types.i8), signature(types.i4, types.i4, types.f4), signature(types.i4, types.i4, types.f8), ] @register
Cuda_match_any_sync
python
pytorch__pytorch
test/distributed/_composable/test_replicate_training.py
{ "start": 2952, "end": 7196 }
class ____(FSDPTestMultiThread): @property def world_size(self) -> int: return 4 @skip_if_lt_x_gpu(1) def test_param_registration_after_forward(self): """Tests the parameter registration after forward.""" device = torch.device(device_type.type, 0) # Single Replicate grou...
TestReplicateRegisteredParams
python
sqlalchemy__sqlalchemy
test/orm/declarative/test_basic.py
{ "start": 2673, "end": 34455 }
class ____(fixtures.TestBase): def test_unbound_declarative_base(self): Base = declarative_base() class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True) s = Session() with testing.expect_raises(exc.UnboundExecutionError): ...
DeclarativeBaseSetupsTest
python
tensorflow__tensorflow
third_party/xla/xla/codegen/testlib/kernel_runner_test.py
{ "start": 924, "end": 1728 }
class ____(absltest.TestCase): def test_from_instruction(self): shape = xla_extension.Shape.array_shape(np.dtype(np.int32), (4,)) hlo_parameter = _extension.HloInstruction.create_parameter( 0, shape, "input" ) hlo_op = _extension.HloInstruction.create_variadic( shape, _extension.HloOp...
HloModuleParse
python
dagster-io__dagster
python_modules/dagster/dagster/_core/snap/job_snapshot.py
{ "start": 3333, "end": 15926 }
class ____(IHaveNew): name: str description: Optional[str] tags: Mapping[str, Any] # It is important that run_tags is nullable to distinguish in host code between # snapshots from older code servers where run_tags does not exist as a field (and is # therefore None) vs snapshots from newer code s...
JobSnap
python
django__django
django/contrib/gis/db/backends/oracle/operations.py
{ "start": 1322, "end": 2047 }
class ____(SpatialOperator): sql_template = "SDO_RELATE(%(lhs)s, %(rhs)s, 'mask=%(mask)s') = 'TRUE'" def check_relate_argument(self, arg): masks = ( "TOUCH|OVERLAPBDYDISJOINT|OVERLAPBDYINTERSECT|EQUAL|INSIDE|COVEREDBY|" "CONTAINS|COVERS|ANYINTERACT|ON" ) mask_reg...
SDORelate
python
pallets__flask
src/flask/config.py
{ "start": 1094, "end": 13219 }
class ____(dict): # type: ignore[type-arg] """Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config. Either you can fill the config from a config file:: app.config.from_pyfile('yourconfig.cfg') Or ...
Config
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/stackdriver.py
{ "start": 1536, "end": 25875 }
class ____(GoogleBaseHook): """Stackdriver Hook for connecting with Google Cloud Stackdriver.""" def __init__( self, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__( ...
StackdriverHook
python
PrefectHQ__prefect
tests/server/orchestration/test_rules.py
{ "start": 2074, "end": 2847 }
class ____: @pytest.mark.parametrize( ["response_type", "response_details"], [ (StateWaitDetails, StateWaitDetails(delay_seconds=20, reason="No!")), (StateRejectDetails, StateRejectDetails(reason="I don't want to change!")), (StateAbortDetails, StateAbortDetails(r...
TestOrchestrationResult
python
ipython__ipython
tests/tclass.py
{ "start": 316, "end": 920 }
class ____(object): def __init__(self, name): self.name = name self.p = print self.flush_stdout = sys.stdout.flush def __del__(self): self.p("tclass.py: deleting object:", self.name) self.flush_stdout() try: name = sys.argv[1] except IndexError: pass else: ...
C
python
encode__django-rest-framework
tests/test_negotiation.py
{ "start": 408, "end": 530 }
class ____(BaseRenderer): media_type = 'application/openapi+json;version=2.0' format = 'swagger'
MockOpenAPIRenderer
python
optuna__optuna
optuna/storages/_rdb/alembic/versions/v1.3.0.a.py
{ "start": 694, "end": 844 }
class ____(BaseModel): __tablename__ = "trials" trial_id = sa.Column(sa.Integer, primary_key=True) number = sa.Column(sa.Integer)
TrialModel
python
PrefectHQ__prefect
src/prefect/server/utilities/database.py
{ "start": 12268, "end": 12789 }
class ____(functions.GenericFunction[datetime.timedelta]): """Platform-independent difference of two timestamps. Computes d1 - d2.""" type: sa.Interval = sa.Interval() inherit_cache: bool = True def __init__( self, d1: _SQLExpressionOrLiteral[datetime.datetime], d2: _SQLExpress...
date_diff
python
pennersr__django-allauth
allauth/socialaccount/providers/quickbooks/provider.py
{ "start": 346, "end": 1784 }
class ____(OAuth2Provider): id = "quickbooks" # Name is displayed to ordinary users -- don't include protocol name = "QuickBooks" account_class = QuickBooksAccount oauth2_adapter_class = QuickBooksOAuth2Adapter def extract_uid(self, data): if "sub" not in data: raise Provide...
QuickBooksOAuth2Provider
python
plotly__plotly.py
plotly/graph_objs/scatterternary/_stream.py
{ "start": 233, "end": 3546 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterternary" _path_str = "scatterternary.stream" _valid_props = {"maxpoints", "token"} @property def maxpoints(self): """ Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints...
Stream
python
SmileyChris__easy-thumbnails
demoproject/mainapp/models.py
{ "start": 88, "end": 268 }
class ____(models.Model): title = models.CharField(max_length=100) image = ThumbnailerImageField(upload_to="images") def __str__(self): return self.title
TestImage
python
pandas-dev__pandas
pandas/tests/series/indexing/test_indexing.py
{ "start": 13042, "end": 15459 }
class ____: # This is adapted from pandas/tests/arrays/masked/test_indexing.py def _check_setitem_invalid(self, ser, invalid, indexer): orig_ser = ser.copy() with pytest.raises(TypeError, match="Invalid value"): ser[indexer] = invalid ser = orig_ser.copy() with ...
TestSetitemValidation
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_template.py
{ "start": 3928, "end": 5247 }
class ____(GraphicsContextBase): """ The graphics context provides the color, line styles, etc. See the cairo and postscript backends for examples of mapping the graphics context attributes (cap styles, join styles, line widths, colors) to a particular backend. In cairo this is done by wrapping a ...
GraphicsContextTemplate
python
aio-libs__aiohttp
tests/test_multipart.py
{ "start": 4274, "end": 23900 }
class ____: async def test_next(self) -> None: with Stream(b"Hello, world!\r\n--:") as stream: d = CIMultiDictProxy[str](CIMultiDict()) obj = aiohttp.BodyPartReader(BOUNDARY, d, stream) result = await obj.next() assert b"Hello, world!" == result as...
TestPartReader
python
google__pytype
pytype/tests/test_typevar2.py
{ "start": 18270, "end": 28505 }
class ____(test_base.BaseTest): """Tests for generic type aliases ("type macros").""" def test_homogeneous_tuple(self): ty = self.Infer(""" from typing import Tuple, TypeVar T = TypeVar('T') X = Tuple[T, ...] def f(x: X[int]): pass f((0, 1, 2)) # should not raise an err...
GenericTypeAliasTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solver18.py
{ "start": 1237, "end": 1659 }
class ____(Generic[_P]): def method1(self, val: str, *args: _P.args, **kwargs: _P.kwargs) -> None: pass def decorator2() -> Callable[[Callable[_P, None]], ClassB[_P]]: ... @decorator2() def func7(y: int) -> None: pass reveal_type(func7, expected_text="ClassB[(y: int)]") reveal_type(func7.method1, ...
ClassB
python
pytorch__pytorch
torch/_higher_order_ops/while_loop.py
{ "start": 27804, "end": 36521 }
class ____(torch.autograd.Function): @staticmethod # pyrefly: ignore [bad-override] def forward( ctx, cond_fn, body_fn, num_carried_inputs, num_additional_inputs, *carries_and_inputs, ): from torch._higher_order_ops.scan import split_into_chunks ...
WhileLoopAutogradOp
python
getsentry__sentry
tests/sentry/issues/test_ignored.py
{ "start": 687, "end": 2596 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.group = self.create_group() self.group_list = [self.group] self.group_ids = [self.group] add_group_to_inbox(self.group, GroupInboxReason.NEW) def test_ignored_forever(self) -> None: status_detail...
HandleIgnoredTest
python
plotly__plotly.py
plotly/graph_objs/layout/smith/_imaginaryaxis.py
{ "start": 235, "end": 28488 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.smith" _path_str = "layout.smith.imaginaryaxis" _valid_props = { "color", "gridcolor", "griddash", "gridwidth", "hoverformat", "labelalias", "layer", "linecolor", "linewid...
Imaginaryaxis
python
pennersr__django-allauth
allauth/socialaccount/providers/telegram/provider.py
{ "start": 246, "end": 2101 }
class ____(Provider): id = "telegram" name = "Telegram" account_class = TelegramAccount supports_redirect = True def get_login_url(self, request, **kwargs): url = reverse("telegram_login") if kwargs: url = url + "?" + urlencode(kwargs) return url def extract...
TelegramProvider
python
django__django
tests/gis_tests/geo3d/models.py
{ "start": 1397, "end": 1545 }
class ____(SimpleModel): mpoint = models.MultiPointField(dim=3) class Meta: required_db_features = {"supports_3d_storage"}
MultiPoint3D
python
Pylons__pyramid
tests/test_exceptions.py
{ "start": 827, "end": 1165 }
class ____(unittest.TestCase): def test_response_equivalence(self): from pyramid.exceptions import BadCSRFToken from pyramid.httpexceptions import HTTPBadRequest self.assertTrue(isinstance(BadCSRFToken(), HTTPBadRequest)) self.assertEqual(BadCSRFToken().status, HTTPBadRequest().stat...
TestBadCSRFToken
python
crytic__slither
slither/core/declarations/solidity_variables.py
{ "start": 7232, "end": 7964 }
class ____(SolidityFunction): def __init__(self, custom_error: CustomError) -> None: # pylint: disable=super-init-not-called self._name = "revert " + custom_error.solidity_signature self._custom_error = custom_error self._return_type: List[Union[TypeInformation, ElementaryType]] = [] @...
SolidityCustomRevert
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_scatter01.py
{ "start": 315, "end": 1406 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_scatter01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.g...
TestCompareXLSXFiles
python
django-crispy-forms__django-crispy-forms
tests/forms.py
{ "start": 2497, "end": 2682 }
class ____(BaseForm): select = forms.ChoiceField( choices=((1, "Option one"), (2, "Option two"), (3, "Option three")), initial=(1,), widget=forms.Select )
SelectSampleForm
python
fastapi__sqlmodel
tests/test_tutorial/test_code_structure/test_tutorial001.py
{ "start": 549, "end": 1465 }
class ____: app: ModuleType database: ModuleType @pytest.fixture( name="modules", params=[ "tutorial001", pytest.param("tutorial001_py39", marks=needs_py39), pytest.param("tutorial001_py310", marks=needs_py310), ], ) def get_modules(request: pytest.FixtureRequest) -> Module...
Modules