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
cython__cython
Cython/Compiler/Builtin.py
{ "start": 1463, "end": 2634 }
class ____: def __init__(self, py_name, args, ret_type, cname, py_equiv="*", utility_code=None, sig=None, func_type=None, is_strict_signature=False, builtin_return_type=None, nogil=None, specialiser=None): self.py_name, self.cname, self.py_equiv = py_name, ...
_BuiltinOverride
python
vyperlang__vyper
vyper/venom/passes/fix_calloca.py
{ "start": 324, "end": 2136 }
class ____(IRGlobalPass): """ Fix callocas after ir_node_to_venom but before function inlining point to abstract memory locations and fixup ids so that they can be reified with the callee function """ def run_pass(self): for fn in self.ctx.get_functions(): self.fcg = self.an...
FixCalloca
python
kubernetes-client__python
kubernetes/client/models/v1beta2_device_capacity.py
{ "start": 383, "end": 4878 }
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...
V1beta2DeviceCapacity
python
gevent__gevent
src/greentest/3.10/test_smtpd.py
{ "start": 1100, "end": 2208 }
class ____(unittest.TestCase): def setUp(self): smtpd.socket = asyncore.socket = mock_socket def test_process_message_unimplemented(self): server = smtpd.SMTPServer((socket_helper.HOST, 0), ('b', 0), decode_data=True) conn, addr = server.accept() ...
SMTPDServerTest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py
{ "start": 27109, "end": 28402 }
class ____(graphene.Mutation): """Deletes asset history from storage.""" Output = graphene.NonNull(GrapheneAssetWipeMutationResult) class Arguments: assetPartitionRanges = graphene.Argument(non_null_list(GraphenePartitionsByAssetSelector)) class Meta: name = "AssetWipeMutation" @...
GrapheneAssetWipeMutation
python
anthropics__anthropic-sdk-python
src/anthropic/_types.py
{ "start": 4106, "end": 4873 }
class ____: """ To explicitly omit something from being sent in a request, use `omit`. ```py # as the default `Content-Type` header is `application/json` that will be sent client.post("/upload/files", files={"file": b"my raw file content"}) # you can't explicitly override the header as it has ...
Omit
python
walkccc__LeetCode
solutions/3504. Longest Palindrome After Substring Concatenation II/3504.py
{ "start": 0, "end": 1293 }
class ____: # 3503. Longest Palindrome After Substring Concatenation I def longestPalindrome(self, s: str, t: str) -> int: m = len(s) n = len(t) suffix = self._getPalindromeLengths(s, True) prefix = self._getPalindromeLengths(t, False) ans = max(max(suffix), max(prefix)) # dp[i][j] := the lo...
Solution
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/router/embedding_router.py
{ "start": 489, "end": 3150 }
class ____(RouterChain): """Chain that uses embeddings to route between options.""" vectorstore: VectorStore routing_keys: list[str] = ["query"] model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", ) @property def input_keys(self) -> list[str]: ...
EmbeddingRouterChain
python
ansible__ansible
test/lib/ansible_test/_internal/host_profiles.py
{ "start": 58849, "end": 62934 }
class ____(RemoteProfile[NetworkRemoteConfig]): """Host profile for a network remote instance.""" def wait(self) -> None: """Wait for the instance to be ready. Executed before delegation for the controller and after delegation for targets.""" self.wait_until_ready() def get_inventory_varia...
NetworkRemoteProfile
python
bokeh__bokeh
src/bokeh/core/has_props.py
{ "start": 27589, "end": 27682 }
class ____(TypedDict): name: str kind: KindRef default: NotRequired[Any]
PropertyDef
python
astropy__astropy
astropy/time/formats.py
{ "start": 74394, "end": 75554 }
class ____(TimeEpochDate): """Besselian Epoch year as decimal value(s) like 1950.0. For information about this epoch format, see: `<https://en.wikipedia.org/wiki/Epoch_(astronomy)#Besselian_years>`_. The astropy Time class uses the ERFA functions ``epb2jd`` and ``epb`` to convert between Besselian...
TimeBesselianEpoch
python
keras-team__keras
keras/src/layers/attention/multi_head_attention_test.py
{ "start": 595, "end": 27693 }
class ____(testing.TestCase): def setUp(self): super().setUp() # Flash attention is a newly introduced feature. We need to disable it # for testing purposes. disable_flash_attention() def tearDown(self): enable_flash_attention() return super().tearDown() def...
MultiHeadAttentionTest
python
great-expectations__great_expectations
great_expectations/data_context/_version_checker.py
{ "start": 336, "end": 3147 }
class ____: _LATEST_GX_VERSION_CACHE: ClassVar[version.Version | None] = None _BASE_PYPI_URL: ClassVar[str] = "https://pypi.org/pypi" _PYPI_GX_ENDPOINT: ClassVar[str] = f"{_BASE_PYPI_URL}/great_expectations/json" def __init__(self, user_version: str) -> None: self._user_version = version.Versi...
_VersionChecker
python
pypa__warehouse
warehouse/organizations/models.py
{ "start": 1316, "end": 1467 }
class ____(str, enum.Enum): Owner = "Owner" BillingManager = "Billing Manager" Manager = "Manager" Member = "Member"
OrganizationRoleType
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py
{ "start": 4634, "end": 4811 }
class ____(BaseConfig): name: str bypass_reason: Optional[str] = Field(default=None, description="Reason why this field is considered ignored.")
IgnoredFieldsConfiguration
python
Farama-Foundation__Gymnasium
gymnasium/vector/sync_vector_env.py
{ "start": 652, "end": 15782 }
class ____(VectorEnv): """Vectorized environment that serially runs multiple environments. Example: >>> import gymnasium as gym >>> envs = gym.make_vec("Pendulum-v1", num_envs=2, vectorization_mode="sync") >>> envs SyncVectorEnv(Pendulum-v1, num_envs=2) >>> envs = gym.ve...
SyncVectorEnv
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/common.py
{ "start": 1671, "end": 1928 }
class ____(BaseModel): """Base Node serializer for responses.""" id: str label: str children: list[GridNodeResponse] | None = None is_mapped: bool | None setup_teardown_type: Literal["setup", "teardown"] | None = None
GridNodeResponse
python
google__pytype
pytype/overlays/typing_overlay.py
{ "start": 21075, "end": 21358 }
class ____(abstract.AnnotationClass): """Implementation of typing.Concatenate[...].""" def _build_value(self, node, inner, ellipses): self.ctx.errorlog.invalid_ellipses(self.ctx.vm.frames, ellipses, self.name) return abstract.Concatenate(list(inner), self.ctx)
Concatenate
python
PyCQA__pylint
doc/data/messages/o/overridden-final-method/bad.py
{ "start": 27, "end": 101 }
class ____: @final def can_breathe(self): return True
Animal
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/engine/base.py
{ "start": 96563, "end": 100571 }
class ____(Transaction): """Represent the "root" transaction on a :class:`_engine.Connection`. This corresponds to the current "BEGIN/COMMIT/ROLLBACK" that's occurring for the :class:`_engine.Connection`. The :class:`_engine.RootTransaction` is created by calling upon the :meth:`_engine.Connection.begi...
RootTransaction
python
FactoryBoy__factory_boy
tests/test_django.py
{ "start": 7714, "end": 8443 }
class ____(django_test.TestCase): def setUp(self): super().setUp() StandardFactoryWithPKField.reset_sequence() def test_no_pk(self): std = StandardFactoryWithPKField() self.assertIsNotNone(std.pk) self.assertEqual('foo0', std.foo) def test_force_pk(self): st...
DjangoPkForceTestCase
python
gwtw__py-sorting
test/comb_sort_test.py
{ "start": 404, "end": 723 }
class ____(unittest.TestCase, BaseCustomComparisonSortTest, BasePositiveIntegerSortTest, BaseNegativeIntegerSortTest, BaseStringSortTest): def setUp(self): self.sort = comb_sort.sort if __name__ == '__main__': unittest.main()
CombSortTest
python
walkccc__LeetCode
solutions/715. Range Module/715-3.py
{ "start": 0, "end": 597 }
class ____: def __init__(self): self.A = [] def addRange(self, left: int, right: int) -> None: i = bisect_left(self.A, left) j = bisect_right(self.A, right) self.A[i:j] = [left] * (i % 2 == 0) + [right] * (j % 2 == 0) def queryRange(self, left: int, right: int) -> bool: i = bisect_right(self...
RangeModule
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/types.py
{ "start": 2159, "end": 2281 }
class ____(_NetworkAddressTypeMixin, sqltypes.TypeEngine[str]): __visit_name__ = "MACADDR" PGMacAddr = MACADDR
MACADDR
python
pytorch__pytorch
torch/_inductor/kernel/mm.py
{ "start": 7794, "end": 37037 }
class ____(SubgraphTemplate): def __init__(self, name: str, description: str, fn: Any): self.name = name self.description = description self.fn = fn super().__init__( name=name, ) def generate( # type: ignore[override] self, input_nodes: list...
ContiguousTemplate
python
tensorflow__tensorflow
tensorflow/python/saved_model/registration/registration_saving_test.py
{ "start": 1886, "end": 2345 }
class ____(resource_variable_ops.ResourceVariable): def __init__(self, value): self._init_from_args(value) @classmethod def _deserialize_from_proto(cls, **kwargs): return cls([0, 0]) def _export_to_saved_model_graph(self, object_map, tensor_map, **kwargs): p = Part(array_ops.zeros(self.shape, sel...
Part
python
google__flatbuffers
tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.py
{ "start": 1340, "end": 2090 }
class ____(object): # TableInNestedNST def __init__(self): self.foo = 0 # type: int @classmethod def InitFromBuf(cls, buf, pos): tableInNestedNS = TableInNestedNS() tableInNestedNS.Init(buf, pos) return cls.InitFromObj(tableInNestedNS) @classmethod def InitFromObj(cls, tableInNestedNS): ...
TableInNestedNST
python
apache__airflow
devel-common/src/tests_common/test_utils/logging_command_executor.py
{ "start": 962, "end": 1063 }
class ____(Exception): """Raise in case of error during command execution."""
CommandExecutionError
python
ansible__ansible
test/units/plugins/connection/test_winrm.py
{ "start": 597, "end": 7096 }
class ____(object): OPTIONS_DATA: tuple[tuple[dict[str, t.Any], dict[str, t.Any], dict[str, t.Any], bool], ...] = ( # default options ( {'_extras': {}}, {}, { '_kerb_managed': False, '_kinit_cmd': 'kinit', '_winrm_c...
TestConnectionWinRM
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructorCallable1.py
{ "start": 1550, "end": 2188 }
class ____(Generic[T1]): @overload def __init__(self: "D[None]", x: int, y: Literal[True]) -> None: ... @overload def __init__(self, x: T1, y: bool = ...) -> None: ... def __init__(self, x: Any, y: bool = False) -> None: ... d1 = func1(D[int], 3) reveal_type(d1, expected_text="D[int]") # This s...
D
python
PyCQA__pylint
tests/functional/u/unnecessary/unnecessary_ellipsis.py
{ "start": 1491, "end": 1836 }
class ____: '''Whoops! Mark this one as bad too. ''' ... # [unnecessary-ellipsis] # Function overloading @overload def summarize(data: int) -> float: ... @overload def summarize(data: str) -> str: ... def summarize(data): if isinstance(data, str): ... return float(data) # Method ove...
DocstringAndEllipsis
python
pandas-dev__pandas
asv_bench/benchmarks/inference.py
{ "start": 5814, "end": 6002 }
class ____: def setup(self): self.s = Series(["2Q2005", "2Q05", "2005Q1", "05Q1"] * 10000) def time_infer_quarter(self): to_datetime(self.s)
ToDatetimeFormatQuarters
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/automap.py
{ "start": 29587, "end": 30703 }
class ____(Protocol): def __call__( self, base: Type[Any], local_cls: Type[Any], referred_cls: Type[Any], constraint: ForeignKeyConstraint, ) -> str: ... def name_for_scalar_relationship( base: Type[Any], local_cls: Type[Any], referred_cls: Type[Any], co...
NameForScalarRelationshipType
python
walkccc__LeetCode
solutions/310. Minimum Height Trees/310.py
{ "start": 0, "end": 609 }
class ____: def findMinHeightTrees(self, n: int, edges: list[list[int]]) -> list[int]: if n == 1 or not edges: return [0] ans = [] graph = collections.defaultdict(set) for u, v in edges: graph[u].add(v) graph[v].add(u) for label, children in graph.items(): if len(childre...
Solution
python
django__django
tests/admin_inlines/admin.py
{ "start": 5242, "end": 5339 }
class ____(admin.ModelAdmin): inlines = [Inner5StackedInline, Inner5TabularInline]
Holder5Admin
python
huggingface__transformers
tests/models/got_ocr2/test_processing_got_ocr2.py
{ "start": 798, "end": 3954 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = GotOcr2Processor @classmethod def _setup_tokenizer(cls): tokenizer_class = cls._get_component_class_from_processor("tokenizer") tokenizer = tokenizer_class.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf") return toke...
GotOcr2ProcessorTest
python
coleifer__peewee
playhouse/pool.py
{ "start": 10939, "end": 12397 }
class ____(_PooledPostgresqlDatabase, PostgresqlDatabase): pass try: from playhouse.postgres_ext import PostgresqlExtDatabase class PooledPostgresqlExtDatabase(_PooledPostgresqlDatabase, PostgresqlExtDatabase): pass except ImportError: PooledPostgresqlExtDatabase = None try: from playhou...
PooledPostgresqlDatabase
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/psycopg2.py
{ "start": 21135, "end": 21948 }
class ____(_PGExecutionContext_common_psycopg): _psycopg2_fetched_rows = None def post_exec(self): self._log_notices(self.cursor) def _log_notices(self, cursor): # check also that notices is an iterable, after it's already # established that we will be iterating through it. This i...
PGExecutionContext_psycopg2
python
dagster-io__dagster
python_modules/libraries/dagster-wandb/dagster_wandb/types.py
{ "start": 36, "end": 239 }
class ____(TypedDict, total=False): """W&B Artifacts IO Manager configuration of the serialization module. Useful for type checking.""" name: str parameters: dict[str, Any]
SerializationModule
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/extra/django/_impl.py
{ "start": 1565, "end": 1647 }
class ____(HypothesisTestCase, dt.TransactionTestCase): pass
TransactionTestCase
python
ray-project__ray
rllib/examples/gpus/float16_training_and_inference.py
{ "start": 5105, "end": 7564 }
class ____: """Custom grad scaler for `TorchLearner`. This class is utilizing the experimental support for the `TorchLearner`'s support for loss/gradient scaling (analogous to how a `torch.amp.GradScaler` would work). TorchLearner performs the following steps using this class (`scaler`): - loss_pe...
Float16GradScaler
python
PrefectHQ__prefect
tests/test_cache_policies.py
{ "start": 683, "end": 1191 }
class ____: def test_initializes(self): policy = _None() assert isinstance(policy, CachePolicy) def test_doesnt_compute_a_key(self): policy = _None() key = policy.compute_key(task_ctx=None, inputs=None, flow_parameters=None) assert key is None @pytest.mark.parametri...
TestNonePolicy
python
ray-project__ray
rllib/models/tf/attention_net.py
{ "start": 15156, "end": 23011 }
class ____(TFModelV2): """GTrXL wrapper serving as interface for ModelV2s that set use_attention.""" def __init__( self, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, num_outputs: int, model_config: ModelConfigDict, name: str, ): if log...
AttentionWrapper
python
fastapi__sqlmodel
docs_src/tutorial/relationship_attributes/back_populates/tutorial003_py310.py
{ "start": 708, "end": 1522 }
class ____(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: int | None = Field(default=None, index=True) team_id: int | None = Field(default=None, foreign_key="team.id") team: Team | None = Relationship(back_popula...
Hero
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py
{ "start": 37614, "end": 42549 }
class ____(GoogleCloudBaseOperator): """ Create a Redis instance and import a Redis RDB snapshot file from Cloud Storage into this instance. By default, the instance is accessible from the project's `default network <https://cloud.google.com/compute/docs/networks-and-firewalls#networks>`__. .. see...
CloudMemorystoreCreateInstanceAndImportOperator
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_image_anchor01.py
{ "start": 315, "end": 1246 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("image_anchor01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Wo...
TestCompareXLSXFiles
python
openai__openai-python
tests/api_resources/evals/test_runs.py
{ "start": 10883, "end": 21988 }
class ____: parametrize = pytest.mark.parametrize( "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] ) @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: run = await async_client.evals.runs.creat...
TestAsyncRuns
python
PrefectHQ__prefect
src/prefect/server/orchestration/rules.py
{ "start": 39685, "end": 39797 }
class ____( BaseOrchestrationRule[orm_models.TaskRun, core.TaskRunPolicy] ): pass
TaskRunOrchestrationRule
python
plotly__plotly.py
plotly/graph_objs/treemap/_textfont.py
{ "start": 233, "end": 17119 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "treemap" _path_str = "treemap.textfont" _valid_props = { "color", "colorsrc", "family", "familysrc", "lineposition", "linepositionsrc", "shadow", "shadowsrc", "size", "siz...
Textfont
python
walkccc__LeetCode
solutions/287. Find the Duplicate Number/287.py
{ "start": 0, "end": 312 }
class ____: def findDuplicate(self, nums: list[int]) -> int: slow = nums[nums[0]] fast = nums[nums[nums[0]]] while slow != fast: slow = nums[slow] fast = nums[nums[fast]] slow = nums[0] while slow != fast: slow = nums[slow] fast = nums[fast] return slow
Solution
python
pytorch__pytorch
test/distributed/checkpoint/_experimental/test_checkpoint_process.py
{ "start": 5888, "end": 17278 }
class ____(TestCase): def setUp(self) -> None: super().setUp() """Set up common test fixtures.""" self.rank_info = RankInfo( global_world_size=1, global_rank=0, ) self.writer_config = CheckpointWriterConfig() self.test_state_dict = { ...
TestCheckpointProcess
python
django__django
tests/admin_views/admin.py
{ "start": 28004, "end": 28500 }
class ____(forms.ModelForm): nolabel_form_field = forms.BooleanField(required=False) class Meta: model = State fields = "__all__" labels = {"name": "State name (from form’s Meta.labels)"} @property def changed_data(self): data = super().changed_data if data: ...
StateAdminForm
python
sqlalchemy__sqlalchemy
test/engine/test_deprecations.py
{ "start": 8615, "end": 9443 }
class ____(fixtures.TestBase): def test_connection_rec_connection(self): dbapi = MockDBAPI() p1 = pool.Pool(creator=lambda: dbapi.connect("foo.db")) rec = pool._ConnectionRecord(p1) with expect_deprecated( "The _ConnectionRecord.connection attribute is deprecated; " ...
PoolTest
python
kamyu104__LeetCode-Solutions
Python/finding-3-digit-even-numbers.py
{ "start": 1446, "end": 1600 }
class ____(object): def __init__(self, val=None, left=None, right=None): self.val = val self.left = left self.right = right
Node
python
pandas-dev__pandas
pandas/io/formats/info.py
{ "start": 20279, "end": 21958 }
class ____(ABC): """ Abstract builder for info table. """ _lines: list[str] info: _BaseInfo @abstractmethod def get_lines(self) -> list[str]: """Product in a form of list of lines (strings).""" @property def data(self) -> DataFrame | Series: return self.info.data ...
_TableBuilderAbstract
python
openai__gym
tests/wrappers/test_pixel_observation.py
{ "start": 1247, "end": 4188 }
class ____(FakeEnvironment): def __init__(self, *args, **kwargs): self.observation_space = spaces.Dict( { "state": spaces.Box(shape=(2,), low=-1, high=1, dtype=np.float32), } ) super().__init__(*args, **kwargs) @pytest.mark.parametrize("pixels_only",...
FakeDictObservationEnvironment
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py
{ "start": 11238, "end": 11576 }
class ____(type(Protocol)): def __new__( cls, name: str, bases: tuple[type[Any], ...], attrs: dict[str, Any], **kwargs: Any ) -> MetaclassInWhichSelfCannotBeUsed5: new_class = super().__new__(cls, name, bases, attrs, **kwargs) return new_class import django.db.models.base
MetaclassInWhichSelfCannotBeUsed5
python
nedbat__coveragepy
coverage/exceptions.py
{ "start": 260, "end": 701 }
class ____(Exception): """The base class of all exceptions raised by Coverage.py.""" def __init__( self, *args: Any, slug: str | None = None, ) -> None: """Create an exception. Args: slug: A short string identifying the exception, will be used for ...
CoverageException
python
python-openxml__python-docx
tests/image/test_helpers.py
{ "start": 207, "end": 1569 }
class ____: def it_can_read_a_string_of_specified_len_at_offset(self, read_str_fixture): stream_rdr, expected_string = read_str_fixture s = stream_rdr.read_str(6, 2) assert s == "foobar" def it_raises_on_unexpected_EOF(self, read_str_fixture): stream_rdr = read_str_fixture[0] ...
DescribeStreamReader
python
getsentry__sentry
tests/sentry/integrations/github/test_client.py
{ "start": 36702, "end": 38098 }
class ____(TestCase): @mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1") def setUp(self, get_jwt): ten_days = timezone.now() + timedelta(days=10) self.integration = self.create_integration( organization=self.organization, provider="github...
GitHubClientFileBlameIntegrationDisableTest
python
ray-project__ray
python/ray/dag/tests/experimental/test_compiled_graphs.py
{ "start": 10849, "end": 16401 }
class ____: regex = r"Found \d+ DAGNodes from the arg .*? in .*?\.\s*" r"Please ensure that the argument is a single DAGNode and that a " r"DAGNode is not allowed to be placed inside any type of container\." def test_dag_node_in_list(self, ray_start_regular): actor = Actor.remote(0) wit...
TestDAGNodeInsideContainer
python
streamlit__streamlit
lib/streamlit/runtime/caching/hashing.py
{ "start": 2160, "end": 5197 }
class ____(StreamlitAPIException): def __init__( self, orig_exc: BaseException, object_to_hash: Any, hash_func: Callable[[Any], Any], cache_type: CacheType | None = None, ) -> None: self.alternate_name = type(orig_exc).__name__ self.hash_func = hash_func ...
UserHashError
python
tensorflow__tensorflow
tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/cyclic_object_graph.py
{ "start": 1222, "end": 1411 }
class ____(tf.Module): def __init__(self): super(TestModule, self).__init__() self.child = ReferencesParent(self) if __name__ == '__main__': common.do_test(TestModule)
TestModule
python
wandb__wandb
wandb/automations/events.py
{ "start": 9506, "end": 10304 }
class ____(_BaseMutationEventInput): """A new artifact is created. Examples: Define an event that triggers when a new artifact is created in the collection "my-collection": ```python from wandb import Api from wandb.automations import OnCreateArtifact api = Api...
OnCreateArtifact
python
realpython__materials
dwitter-part-3/source_code_final/dwitter/admin.py
{ "start": 186, "end": 417 }
class ____(admin.ModelAdmin): model = User fields = ["username"] inlines = [ProfileInline] admin.site.unregister(User) admin.site.register(User, UserAdmin) admin.site.unregister(Group) admin.site.register(Dweet)
UserAdmin
python
google__pytype
pytype/directors/directors_test.py
{ "start": 23958, "end": 24729 }
class ____(DirectorTestCase): """Test global directives.""" def test_skip_file(self): self.assertRaises( directors.SkipFileError, self._create, """ # pytype: skip-file """, ) def test_features(self): self._create(""" # pytype: features=no-return-any ...
GlobalDirectivesTest
python
django-extensions__django-extensions
tests/testapp/models.py
{ "start": 9583, "end": 9752 }
class ____(models.Model): a = models.IntegerField() uuid_field = ShortUUIDField() class Meta: app_label = "django_extensions"
ShortUUIDTestModel_field
python
pypa__pip
src/pip/_vendor/msgpack/ext.py
{ "start": 513, "end": 5726 }
class ____: """Timestamp represents the Timestamp extension type in msgpack. When built with Cython, msgpack uses C methods to pack and unpack `Timestamp`. When using pure-Python msgpack, :func:`to_bytes` and :func:`from_bytes` are used to pack and unpack `Timestamp`. This class is immutable: Do n...
Timestamp
python
pytorch__pytorch
test/distributed/elastic/test_control_plane.py
{ "start": 862, "end": 1449 }
class ____(HTTPConnectionPool): def __init__(self, socket_path: str) -> None: super().__init__("localhost") self.socket_path = socket_path def _new_conn(self): return UnixHTTPConnection(self.socket_path) @contextmanager def local_worker_server() -> None: with tempfile.TemporaryDi...
UnixHTTPConnectionPool
python
pytorch__pytorch
test/dynamo/test_guard_serialization.py
{ "start": 6880, "end": 8878 }
class ____(torch.Tensor): @staticmethod def __new__(cls, a, extra, outer_size=None, outer_stride=None): if outer_size is None: outer_size = a.size() if outer_stride is None: outer_stride = a.stride() shape = outer_size kwargs = {} kwargs["strides"...
SubclassWithSubclassInnerTensor
python
walkccc__LeetCode
solutions/1624. Largest Substring Between Two Equal Characters/1624.py
{ "start": 0, "end": 262 }
class ____: def maxLengthBetweenEqualCharacters(self, s: str) -> int: ans = -1 lastSeen = {} for i, c in enumerate(s): if c not in lastSeen: lastSeen[c] = i else: ans = max(ans, i - lastSeen[c] - 1) return ans
Solution
python
sympy__sympy
sympy/stats/crv_types.py
{ "start": 7256, "end": 10005 }
class ____(SingleContinuousDistribution): _argnames = ('alpha', 'beta', 'sigma') @staticmethod def check(alpha, beta, sigma): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") _value_check(sigma > 0, "...
BeniniDistribution
python
django__django
tests/urlpatterns_reverse/tests.py
{ "start": 20926, "end": 28085 }
class ____(SimpleTestCase): def test_resolver_repr(self): """ Test repr of URLResolver, especially when urlconf_name is a list (#17892). """ # Pick a resolver from a namespaced URLconf resolver = get_resolver("urlpatterns_reverse.namespace_urls") sub_resolver ...
ResolverTests
python
PyCQA__pyflakes
pyflakes/test/test_other.py
{ "start": 51990, "end": 53379 }
class ____(TestCase): """ Tests for warning about invalid use of print function. """ def test_valid_print(self): self.flakes(''' print("Hello") ''') def test_invalid_print_when_imported_from_future(self): exc = self.flakes(''' from __future__ import print_fu...
TestIncompatiblePrintOperator
python
apache__airflow
providers/edge3/src/airflow/providers/edge3/models/edge_job.py
{ "start": 1304, "end": 3621 }
class ____(Base, LoggingMixin): """ A job which is queued, waiting or running on a Edge Worker. Each tuple in the database represents and describes the state of one job. """ __tablename__ = "edge_job" dag_id: Mapped[str] = mapped_column(StringID(), primary_key=True, nullable=False) task_id...
EdgeJobModel
python
tensorflow__tensorflow
tensorflow/python/framework/op_allowlist_namespace_test.py
{ "start": 879, "end": 1169 }
class ____(googletest.TestCase): def testOpAllowListNamespace(self): """Test that the building of the python wrapper worked.""" op = test_namespace_ops.namespace_test_string_output self.assertIsNotNone(op) if __name__ == "__main__": googletest.main()
OpAllowlistNamespaceTest
python
getsentry__sentry
src/sentry/dynamic_sampling/models/base.py
{ "start": 276, "end": 400 }
class ____(Exception): pass Input = TypeVar("Input", bound=ModelInput) Output = TypeVar("Output")
InvalidModelInputError
python
Textualize__textual
src/textual/widgets/_markdown.py
{ "start": 13170, "end": 13422 }
class ____(MarkdownBlock): """A horizontal rule.""" DEFAULT_CSS = """ MarkdownHorizontalRule { border-bottom: solid $secondary; height: 1; padding-top: 1; margin-bottom: 1; } """
MarkdownHorizontalRule
python
doocs__leetcode
solution/1500-1599/1586.Binary Search Tree Iterator II/Solution.py
{ "start": 192, "end": 981 }
class ____: def __init__(self, root: Optional[TreeNode]): self.nums = [] def dfs(root): if root is None: return dfs(root.left) self.nums.append(root.val) dfs(root.right) dfs(root) self.i = -1 def hasNext(self) -> ...
BSTIterator
python
dagster-io__dagster
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/headers/auth.py
{ "start": 247, "end": 376 }
class ____(Enum): ORGANIZATION = "organization" DEPLOYMENT = "deployment" UNSCOPED = "unscoped"
DagsterCloudInstanceScope
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_bic.py
{ "start": 760, "end": 1433 }
class ____(ColumnMapMetricProvider): condition_metric_name = "column_values.valid_bic" @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): return column.apply(is_valid_bic) # @column_condition_partial(engine=SparkDFExecutionEngine) # def _spark(cls, ...
ColumnValuesToBeValidBic
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/datetime.py
{ "start": 14079, "end": 20146 }
class ____(SearchStrategy): def __init__(self, min_value, max_value): super().__init__() assert isinstance(min_value, dt.timedelta) assert isinstance(max_value, dt.timedelta) assert min_value < max_value self.min_value = min_value self.max_value = max_value def d...
TimedeltaStrategy
python
xlwings__xlwings
xlwings/main.py
{ "start": 97826, "end": 98185 }
class ____(Collection): """ A collection of all :meth:`shape <Shape>` objects on the specified sheet: >>> import xlwings as xw >>> xw.books['Book1'].sheets[0].shapes Shapes([<Shape 'Oval 1' in <Sheet [Book1]Sheet1>>, <Shape 'Rectangle 1' in <Sheet [Book1]Sheet1>>]) .. versionadded:...
Shapes
python
Netflix__metaflow
test/core/tests/merge_artifacts.py
{ "start": 67, "end": 3072 }
class ____(MetaflowTest): PRIORITY = 1 SKIP_GRAPHS = [ "simple_switch", "nested_switch", "branch_in_switch", "foreach_in_switch", "switch_in_branch", "switch_in_foreach", "recursive_switch", "recursive_switch_inside_foreach", ] @steps(0, [...
MergeArtifactsTest
python
getsentry__sentry
src/sentry/integrations/discord/views/link_identity.py
{ "start": 848, "end": 1736 }
class ____(DiscordIdentityLinkageView, LinkIdentityView): def get_success_template_and_context( self, params: Mapping[str, Any], integration: Integration | None ) -> tuple[str, dict[str, Any]]: if integration is None: raise ValueError( 'integration is required for lin...
DiscordLinkIdentityView
python
huggingface__transformers
src/transformers/models/deit/modeling_deit.py
{ "start": 1490, "end": 5414 }
class ____(nn.Module): """ Construct the CLS token, distillation token, position and patch embeddings. Optionally, also the mask token. """ def __init__(self, config: DeiTConfig, use_mask_token: bool = False) -> None: super().__init__() self.cls_token = nn.Parameter(torch.zeros(1, 1, c...
DeiTEmbeddings
python
networkx__networkx
networkx/classes/tests/test_reportviews.py
{ "start": 6647, "end": 6955 }
class ____(TestNodeViewSetOps): @classmethod def setup_class(cls): cls.G = nx.path_graph(9) cls.G.nodes[3]["foo"] = "bar" cls.nv = cls.G.nodes.data("foo") def n_its(self, nodes): return {(node, "bar" if node == 3 else None) for node in nodes}
TestNodeDataViewSetOps
python
pydantic__pydantic
pydantic-core/tests/serializers/test_union.py
{ "start": 29125, "end": 29225 }
class ____: def __init__(self, type_: Literal['dog']) -> None: self.type_ = 'dog'
ModelDog
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/diamond_link_right/package.py
{ "start": 217, "end": 529 }
class ____(Package): """Part of diamond-link-{top,left,right,bottom} group""" homepage = "http://www.example.com" url = "http://www.example.com/diamond-link-right-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") depends_on("diamond-link-bottom", type="link")
DiamondLinkRight
python
vyperlang__vyper
vyper/semantics/types/subscriptable.py
{ "start": 4794, "end": 6830 }
class ____(_SequenceT): """ Static array type """ typeclass = "static_array" _id = "$SArray" def __init__(self, value_type: VyperType, length: int) -> None: super().__init__(value_type, length) def __repr__(self): return f"{self.value_type}[{self.length}]" @property ...
SArrayT
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/translate.py
{ "start": 74744, "end": 78199 }
class ____(GoogleCloudBaseOperator): """ Delete a Google Cloud Translation Glossary. Deletes a translation glossary, using API V3. For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:TranslateDeleteGlossaryOperator`. :param glossary_id: User-specifi...
TranslateDeleteGlossaryOperator
python
run-llama__llama_index
llama-index-core/llama_index/core/evaluation/correctness.py
{ "start": 2037, "end": 4888 }
class ____(BaseEvaluator): """ Correctness evaluator. Evaluates the correctness of a question answering system. This evaluator depends on `reference` answer to be provided, in addition to the query string and response string. It outputs a score between 1 and 5, where 1 is the worst and 5 is th...
CorrectnessEvaluator
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-duckduckgo/llama_index/tools/duckduckgo/base.py
{ "start": 127, "end": 1732 }
class ____(BaseToolSpec): """DuckDuckGoSearch tool spec.""" spec_functions = ["duckduckgo_instant_search", "duckduckgo_full_search"] def __init__(self) -> None: if not importlib.util.find_spec("duckduckgo_search"): raise ImportError( "DuckDuckGoSearchToolSpec requires t...
DuckDuckGoSearchToolSpec
python
kamyu104__LeetCode-Solutions
Python/painting-a-grid-with-three-different-colors.py
{ "start": 3518, "end": 8626 }
class ____(object): def colorTheGrid(self, m, n): """ :type m: int :type n: int :rtype: int """ MOD = 10**9+7 def find_masks(m, basis): # Time: 3 + 3*2 + 3*2*2 + ... + 3*2^(m-1) = 3 * (2^m - 1) = O(2^m), Space: O(2^m) masks = [0] for c...
Solution2
python
ansible__ansible
test/units/plugins/connection/test_local.py
{ "start": 859, "end": 1239 }
class ____(unittest.TestCase): def test_local_connection_module(self): play_context = PlayContext() play_context.prompt = ( '[sudo via ansible, key=ouzmdnewuhucvuaabtjmweasarviygqq] password: ' ) in_stream = StringIO() self.assertIsInstance(local.Connection(play...
TestLocalConnectionClass
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-ads/unit_tests/test_components.py
{ "start": 6562, "end": 8689 }
class ____: def test_click_view_http_requester_returns_expected_request_body(self, config): requester = ClickViewHttpRequester( name="test_click_view_http_requester", parameters={}, config=config, schema_loader=InlineSchemaLoader( schema={ ...
TestClickViewHttpRequester
python
huggingface__transformers
src/transformers/models/time_series_transformer/modeling_time_series_transformer.py
{ "start": 12864, "end": 18626 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, config: Opti...
TimeSeriesTransformerAttention
python
HypothesisWorks__hypothesis
hypothesis-python/tests/conjecture/test_engine.py
{ "start": 15501, "end": 51193 }
class ____: def __repr__(self): return "stuff" def test_debug_data(capsys): choices = (0, 1, 2) def f(data): for choice in choices: if data.draw(st.integers(0, 100)) != choice: data.mark_invalid() data.start_span(1) data.stop_span() ...
Foo
python
numpy__numpy
numpy/_core/tests/test_deprecations.py
{ "start": 5718, "end": 6693 }
class ____(_DeprecationTestCase): # 2020-03-31 1.19.0 deprecated_types = [np.csingle, np.cdouble, np.clongdouble] not_deprecated_types = [ np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float16, np.float32, np.float64, ] def test_depreca...
BuiltInRoundComplexDType
python
walkccc__LeetCode
solutions/616. Add Bold Tag in String/616.py
{ "start": 0, "end": 695 }
class ____: def addBoldTag(self, s: str, words: list[str]) -> str: n = len(s) ans = [] # bold[i] := True if s[i] should be bolded bold = [0] * n boldEnd = -1 # s[i:boldEnd] should be bolded for i in range(n): for word in words: if s[i:].startswith(word): boldEnd = max...
Solution