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 | facelessuser__pymdown-extensions | pymdownx/critic.py | {
"start": 5275,
"end": 8759
} | class ____(Preprocessor):
"""Handle viewing critic marks in Markdown content."""
def __init__(self, critic_stash):
"""Initialize."""
super().__init__()
self.critic_stash = critic_stash
def _ins(self, text):
"""Handle critic inserts."""
if RE_BLOCK_SEP.match(text):... | CriticViewPreprocessor |
python | django-extensions__django-extensions | tests/management/commands/test_managestate.py | {
"start": 808,
"end": 1520
} | class ____:
"""Tests for managestate management command exceptions."""
def test_bad_action(self):
with pytest.raises(CommandError):
call_command(COMMAND, "bad_action")
def test_no_such_file(self):
with pytest.raises(CommandError):
call_command(COMMAND, "load", "-f",... | TestManageStateExceptions |
python | walkccc__LeetCode | solutions/948. Bag of Tokens/948.py | {
"start": 0,
"end": 461
} | class ____:
def bagOfTokensScore(self, tokens: list[int], power: int) -> int:
ans = 0
score = 0
q = collections.deque(sorted(tokens))
while q and (power >= q[0] or score):
while q and power >= q[0]:
# Play the smallest face up.
power -= q.popleft()
score += 1
ans =... | Solution |
python | tornadoweb__tornado | tornado/test/netutil_test.py | {
"start": 5463,
"end": 6177
} | class ____(unittest.TestCase):
def test_is_valid_ip(self):
self.assertTrue(is_valid_ip("127.0.0.1"))
self.assertTrue(is_valid_ip("4.4.4.4"))
self.assertTrue(is_valid_ip("::1"))
self.assertTrue(is_valid_ip("2620:0:1cfe:face:b00c::3"))
self.assertFalse(is_valid_ip("www.google.c... | IsValidIPTest |
python | walkccc__LeetCode | solutions/50. Pow(x, n)/50.py | {
"start": 0,
"end": 235
} | class ____:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n < 0:
return 1 / self.myPow(x, -n)
if n % 2 == 1:
return x * self.myPow(x, n - 1)
return self.myPow(x * x, n // 2)
| Solution |
python | getlogbook__logbook | tests/conftest.py | {
"start": 1106,
"end": 1401
} | class ____(ActivationStrategy):
def activate(self):
self.handler.push_context()
def deactivate(self):
self.handler.pop_context()
@pytest.fixture(params=[ContextEnteringStrategy, PushingStrategy])
def activation_strategy(request):
return request.param
| PushingStrategy |
python | django__django | tests/prefetch_related/models.py | {
"start": 7791,
"end": 8147
} | class ____(models.Model):
name = models.CharField(max_length=50, unique=True)
first_book = models.ForeignKey(
"Book", models.CASCADE, related_name="first_time_authors+"
)
favorite_books = models.ManyToManyField("Book", related_name="+")
class Meta:
ordering = ["id"]
# Models for m... | Author2 |
python | django-haystack__django-haystack | haystack/generic_views.py | {
"start": 2522,
"end": 3415
} | class ____(SearchMixin):
"""
A mixin that allows adding in a Haystack search functionality with search
faceting.
"""
form_class = FacetedSearchForm
facet_fields = None
date_facet_fields = None
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs.update({... | FacetedSearchMixin |
python | huggingface__transformers | src/transformers/models/focalnet/modeling_focalnet.py | {
"start": 7225,
"end": 10900
} | class ____(nn.Module):
def __init__(
self,
config,
image_size,
patch_size,
num_channels,
embed_dim,
add_norm=False,
use_conv_embed=False,
is_stem=False,
):
super().__init__()
image_size = image_size if isinstance(image_size,... | FocalNetPatchEmbeddings |
python | PrefectHQ__prefect | src/prefect/_versioning.py | {
"start": 880,
"end": 1070
} | class ____(VersionInfo):
type: Literal["vcs:gitlab"] = "vcs:gitlab"
version: str
commit_sha: str
message: str
branch: str
repository: str
url: str
| GitlabVersionInfo |
python | pypa__hatch | tests/backend/metadata/test_spec.py | {
"start": 215,
"end": 7005
} | class ____:
def test_missing_name(self):
core_metadata = f"""\
Metadata-Version: {LATEST_METADATA_VERSION}
"""
with pytest.raises(ValueError, match="^Missing required core metadata: Name$"):
project_metadata_from_core_metadata(core_metadata)
def test_missing_version(self):
c... | TestProjectMetadataFromCoreMetadata |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/strategies/_internal/collections.py | {
"start": 12300,
"end": 13998
} | class ____(SearchStrategy[dict[Any, Any]]):
"""A strategy which produces dicts with a fixed set of keys, given a
strategy for each of their equivalent values.
e.g. {'foo' : some_int_strategy} would generate dicts with the single
key 'foo' mapping to some integer.
"""
def __init__(
self... | FixedDictStrategy |
python | ansible__ansible | lib/ansible/errors/__init__.py | {
"start": 6346,
"end": 6436
} | class ____(AnsibleError, AssertionError):
"""Invalid assertion."""
| AnsibleAssertionError |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/aot_autograd_result.py | {
"start": 1969,
"end": 2375
} | class ____(ABC, Generic[TOut]):
"""
Class representing a single inductor output
"""
@abstractmethod
def pre_save(self) -> None: ...
@abstractmethod
def load(self, example_inputs) -> TOut: ...
@abstractmethod
def post_compile(self, result: TOut, fx_config: _CompileFxKwargs) -> TOut... | InductorOutput |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_0.py | {
"start": 2763,
"end": 2873
} | class ____(Generic[W]): # -> [W = int]
var: W
# nested classes and functions are skipped
| DefaultOnlyTypeVar |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/execution_api/deps.py | {
"start": 1485,
"end": 3625
} | class ____(HTTPBearer):
"""
A FastAPI security dependency that validates JWT tokens using for the Execution API.
This will validate the tokens are signed and that the ``sub`` is a UUID, but nothing deeper than that.
The dependency result will be an `TIToken` object containing the ``id`` UUID (from the... | JWTBearer |
python | huggingface__transformers | src/transformers/models/kyutai_speech_to_text/feature_extraction_kyutai_speech_to_text.py | {
"start": 1495,
"end": 11453
} | class ____(SequenceFeatureExtractor):
r"""
Constructs an KyutaiSpeechToText feature extractor.
This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
most of the main methods. Users should refer to this superclass for more information regardi... | KyutaiSpeechToTextFeatureExtractor |
python | cython__cython | Cython/Shadow.py | {
"start": 11949,
"end": 12273
} | class ____(CythonType):
def __init__(self, type, name=None):
self._basetype = type
self.name = name
def __call__(self, *arg):
value = cast(self._basetype, *arg)
return value
def __repr__(self):
return self.name or str(self._basetype)
__getitem__ = index_type
... | typedef |
python | RaRe-Technologies__gensim | gensim/test/test_poincare.py | {
"start": 873,
"end": 1515
} | class ____(unittest.TestCase):
def test_encoding_handling(self):
"""Tests whether utf8 and non-utf8 data loaded correctly."""
non_utf8_file = datapath('poincare_cp852.tsv')
relations = [relation for relation in PoincareRelations(non_utf8_file, encoding='cp852')]
self.assertEqual(len(... | TestPoincareData |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/declared_attr_two.py | {
"start": 785,
"end": 1104
} | class ____(Base):
__tablename__ = "foo"
id = mapped_column(Integer, primary_key=True)
u1 = User()
if typing.TYPE_CHECKING:
assert_type(User.__tablename__, str)
assert_type(Foo.__tablename__, str)
assert_type(u1.related_data, str)
assert_type(User.related_data, InstrumentedAttribute[str])
| Foo |
python | apache__airflow | providers/cncf/kubernetes/tests/unit/cncf/kubernetes/decorators/test_kubernetes_cmd.py | {
"start": 1271,
"end": 13950
} | class ____(TestKubernetesDecoratorsBase):
@pytest.mark.asyncio
@pytest.mark.parametrize(
"args_only",
[True, False],
)
def test_basic_kubernetes(self, args_only: bool):
"""Test basic proper KubernetesPodOperator creation from @task.kubernetes_cmd decorator"""
expected = [... | TestKubernetesCmdDecorator |
python | PyCQA__bandit | tests/unit/cli/test_main.py | {
"start": 1838,
"end": 12051
} | class ____(testtools.TestCase):
def setUp(self):
super().setUp()
self.current_directory = os.getcwd()
def tearDown(self):
super().tearDown()
os.chdir(self.current_directory)
def test_get_options_from_ini_no_ini_path_no_target(self):
# Test that no config options are... | BanditCLIMainTests |
python | django__django | tests/model_inheritance/tests.py | {
"start": 22190,
"end": 23301
} | class ____(SimpleTestCase):
def test_abstract_fk_related_name(self):
related_name = "%(app_label)s_%(class)s_references"
class Referenced(models.Model):
class Meta:
app_label = "model_inheritance"
class AbstractReferent(models.Model):
reference = mod... | InheritanceSameModelNameTests |
python | zostera__django-bootstrap4 | tests/test_formsets.py | {
"start": 388,
"end": 6481
} | class ____(TestCase):
def test_illegal_form(self):
with self.assertRaises(BootstrapError):
render_form(form="illegal")
def test_field_names(self):
form = TestForm()
res = render_form(form)
for field in form:
# datetime has a multiwidget field widget
... | BootstrapFormTest |
python | huggingface__transformers | src/transformers/models/phi3/modeling_phi3.py | {
"start": 23992,
"end": 24241
} | class ____(GenericForTokenClassification, Phi3PreTrainedModel):
pass
__all__ = [
"Phi3PreTrainedModel",
"Phi3Model",
"Phi3ForCausalLM",
"Phi3ForSequenceClassification",
"Phi3ForTokenClassification",
]
| Phi3ForTokenClassification |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/core/airflow_instance.py | {
"start": 2612,
"end": 23821
} | class ____:
"""A class that represents a running Airflow Instance and provides methods for interacting with its REST API.
Args:
auth_backend (AirflowAuthBackend): The authentication backend to use when making requests to the Airflow instance.
name (str): The name of the Airflow instance. This w... | AirflowInstance |
python | walkccc__LeetCode | solutions/1924. Erect the Fence II/1924.py | {
"start": 60,
"end": 121
} | class ____:
x: float
y: float
@dataclass(frozen=True)
| Point |
python | jd__tenacity | tenacity/__init__.py | {
"start": 4952,
"end": 5265
} | class ____(BaseAction):
REPR_FIELDS = ("sleep",)
NAME = "retry"
def __init__(self, sleep: t.SupportsFloat) -> None:
self.sleep = float(sleep)
_unset = object()
def _first_set(first: t.Union[t.Any, object], second: t.Any) -> t.Any:
return second if first is _unset else first
| RetryAction |
python | pytorch__pytorch | torch/ao/ns/fx/graph_matcher.py | {
"start": 682,
"end": 6892
} | class ____:
"""
Iterates through the graph of gm, starting with the output nodes
and continuing backwards.
1. Returns matchable subgraphs, in order. A subgraph is defined by
(start_node, end_node).
2. Skips over non-matchable subgraphs
"""
def __init__(
self,
gm: Grap... | _NSGraphMatchableSubgraphsIterator |
python | pandas-dev__pandas | pandas/tests/scalar/timedelta/test_timedelta.py | {
"start": 9205,
"end": 10077
} | class ____:
def test_invert(self):
td = Timedelta(10, unit="D")
msg = "bad operand type for unary ~"
with pytest.raises(TypeError, match=msg):
~td
# check this matches pytimedelta and timedelta64
with pytest.raises(TypeError, match=msg):
~(td.to_pyti... | TestTimedeltaUnaryOps |
python | vyperlang__vyper | vyper/codegen/ir_node.py | {
"start": 3783,
"end": 25775
} | class ____:
repr_show_gas = False
_gas: int
valency: int
args: List["IRnode"]
value: Union[str, int]
is_self_call: bool
passthrough_metadata: dict[str, Any]
func_ir: Any
common_ir: Any
# for bytestrings, if we have `is_source_bytes_literal`, we can perform
# certain optimiza... | IRnode |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1260494,
"end": 1261079
} | class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData):
"""Audit log entry for a
org.update_member_repository_invitation_permission event.
"""
__schema__ = github_schema
__field_names__ = ("can_invite_outside_collaborators_to_repositories",)
can_invite_outside_collaborators_... | OrgUpdateMemberRepositoryInvitationPermissionAuditEntry |
python | scipy__scipy | scipy/linalg/tests/test_cython_blas.py | {
"start": 145,
"end": 1396
} | class ____:
def test_transposes(self):
a = np.arange(12, dtype='d').reshape((3, 4))[:2,:2]
b = np.arange(1, 13, dtype='d').reshape((4, 3))[:2,:2]
c = np.empty((2, 4))[:2,:2]
blas._test_dgemm(1., a, b, 0., c)
assert_allclose(c, a.dot(b))
blas._test_dgemm(1., a.... | TestDGEMM |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/connectors/aioodbc.py | {
"start": 1178,
"end": 3045
} | class ____(AsyncAdapt_dbapi_connection):
_cursor_cls = AsyncAdapt_aioodbc_cursor
_ss_cursor_cls = AsyncAdapt_aioodbc_ss_cursor
__slots__ = ()
@property
def autocommit(self):
return self._connection.autocommit
@autocommit.setter
def autocommit(self, value):
# https://github.... | AsyncAdapt_aioodbc_connection |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 220774,
"end": 223371
} | class ____:
# regression tests after precision improvements, ticket:1041, not verified
def test_precision(self):
assert_almost_equal(stats.chi2.pdf(1000, 1000), 8.919133934753128e-003,
decimal=14)
assert_almost_equal(stats.chi2.pdf(100, 100), 0.028162503162596778,
... | TestChi2 |
python | apache__airflow | devel-common/src/tests_common/pytest_plugin.py | {
"start": 64646,
"end": 89557
} | class ____(Protocol):
"""Type stub for create_task_of_operator."""
def __call__(
self,
operator_class: type[Op],
*,
dag_id: str,
session: Session = ...,
**kwargs,
) -> Op: ...
@pytest.fixture
def create_task_of_operator(dag_maker: DagMaker) -> CreateTaskOfO... | CreateTaskOfOperator |
python | doocs__leetcode | solution/0500-0599/0588.Design In-Memory File System/Solution.py | {
"start": 0,
"end": 745
} | class ____:
def __init__(self):
self.name = None
self.isFile = False
self.content = []
self.children = {}
def insert(self, path, isFile):
node = self
ps = path.split('/')
for p in ps[1:]:
if p not in node.children:
node.childre... | Trie |
python | scipy__scipy | scipy/stats/tests/test_morestats.py | {
"start": 66933,
"end": 85744
} | class ____:
def test_wilcoxon_bad_arg(self, xp):
# Raise ValueError when two args of different lengths are given or
# zero_method is unknown.
x = xp.asarray([1, 2])
d = xp.asarray([1]*10)
message = "`zero_method` must be one of..."
with pytest.raises(ValueError, match... | TestWilcoxon |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context_creation_job.py | {
"start": 5727,
"end": 10173
} | class ____(Generic[TContextType], ABC):
def __init__(
self,
event_generator: Iterator[Union[DagsterEvent, TContextType]],
raise_on_error: Optional[bool] = False,
):
self._manager = EventGenerationManager[TContextType](
generator=event_generator, object_cls=self.contex... | ExecutionContextManager |
python | dagster-io__dagster | python_modules/dagster/dagster/_module_alias_map.py | {
"start": 705,
"end": 2821
} | class ____(MetaPathFinder):
def __init__(self, alias_map: Mapping[str, str]):
self.alias_map = alias_map
def find_spec(
self,
fullname: str,
_path: Optional[Sequence[Union[bytes, str]]] = None,
_target: Optional[ModuleType] = None,
) -> Optional[ModuleSpec]:
... | AliasedModuleFinder |
python | walkccc__LeetCode | solutions/686. Repeated String Match/686.py | {
"start": 0,
"end": 203
} | class ____:
def repeatedStringMatch(self, a: str, b: str) -> int:
n = math.ceil(len(b) / len(a))
s = a * n
if b in s:
return n
if b in s + a:
return n + 1
return -1
| Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_20/models.py | {
"start": 40652,
"end": 42344
} | class ____(Request):
"""
Delete a model.
:param model: Model ID
:type model: str
:param force: Force. Required if there are tasks that use the model as an
execution model, or if the model's creating task is published.
:type force: bool
"""
_service = "models"
_action = "del... | DeleteRequest |
python | realpython__materials | python-import/namespace_package/local/serializers/yaml.py | {
"start": 87,
"end": 195
} | class ____(JsonSerializer):
def __str__(self):
return yaml.dump(self._current_object)
| YamlSerializer |
python | numba__numba | numba/tests/test_jitclasses.py | {
"start": 33198,
"end": 59870
} | class ____(MemoryLeakMixin, TestCase):
class PyList:
def __init__(self):
self.x = [0]
def append(self, y):
self.x.append(y)
def clear(self):
self.x.clear()
def __abs__(self):
return len(self.x) * 7
def __bool__(self):
... | TestJitClassOverloads |
python | keon__algorithms | tests/test_maths.py | {
"start": 2516,
"end": 2927
} | class ____(unittest.TestCase):
"""[summary]
Test for the file euler_totient.py
Arguments:
unittest {[type]} -- [description]
"""
def test_euler_totient(self):
self.assertEqual(4, euler_totient(8))
self.assertEqual(12, euler_totient(21))
self.assertEqual(311040, eule... | TestEulerTotient |
python | imageio__imageio | imageio/plugins/freeimage.py | {
"start": 6178,
"end": 9270
} | class ____(FreeimageFormat):
"""A PNG format based on the Freeimage library.
This format supports grayscale, RGB and RGBA images.
The freeimage plugin requires a `freeimage` binary. If this binary
not available on the system, it can be downloaded manually from
<https://github.com/imageio/imageio-b... | FreeimagePngFormat |
python | mlflow__mlflow | mlflow/langchain/api_request_parallel_processor.py | {
"start": 2472,
"end": 13118
} | class ____:
"""
Stores an API request's inputs, outputs, and other metadata. Contains a method to make an API
call.
Args:
index: The request's index in the tasks list
lc_model: The LangChain model to call
request_json: The request's input data
results: The list to append... | APIRequest |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/errors.py | {
"start": 6463,
"end": 6570
} | class ____(HypothesisException, Warning):
"""A generic warning issued by Hypothesis."""
| HypothesisWarning |
python | coleifer__peewee | tests/regressions.py | {
"start": 7490,
"end": 8090
} | class ____(ModelTestCase):
@requires_models(Category2, User2)
def test_get_or_create_self_referential_fk2(self):
huey = User2.create(username='huey')
parent = Category2.create(name='parent', user=huey)
child, created = Category2.get_or_create(parent=parent, name='child',
... | TestGithub1354 |
python | run-llama__llama_index | llama-index-instrumentation/src/llama_index_instrumentation/base/event.py | {
"start": 206,
"end": 1075
} | class ____(BaseModel):
model_config = ConfigDict(
arbitrary_types_allowed=True,
# copy_on_model_validation = "deep" # not supported in Pydantic V2...
)
timestamp: datetime = Field(default_factory=lambda: datetime.now())
id_: str = Field(default_factory=lambda: str(uuid4()))
span_id:... | BaseEvent |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/instance.py | {
"start": 7656,
"end": 8686
} | class ____(graphene.ObjectType):
maxConcurrentRuns = graphene.NonNull(graphene.Int)
tagConcurrencyLimitsYaml = graphene.String()
isOpConcurrencyAware = graphene.Boolean()
class Meta:
name = "RunQueueConfig"
def __init__(self, run_queue_config: "RunQueueConfig"):
super().__init__()
... | GrapheneRunQueueConfig |
python | huggingface__transformers | tests/models/swinv2/test_modeling_swinv2.py | {
"start": 7739,
"end": 17364
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
Swinv2Model,
Swinv2ForImageClassification,
Swinv2ForMaskedImageModeling,
Swinv2Backbone,
)
if is_torch_available()
else ()
)
pipeline_... | Swinv2ModelTest |
python | apache__airflow | airflow-core/tests/unit/dag_processing/test_dagbag.py | {
"start": 45857,
"end": 48045
} | class ____:
@staticmethod
def raise_warnings():
warnings.warn("Foo", UserWarning, stacklevel=2)
warnings.warn("Bar", UserWarning, stacklevel=2)
warnings.warn("Baz", UserWarning, stacklevel=2)
def test_capture_no_warnings(self):
with warnings.catch_warnings():
war... | TestCaptureWithReraise |
python | wandb__wandb | wandb/sdk/artifacts/storage_policies/_multipart.py | {
"start": 2211,
"end": 2992
} | class ____:
__slots__ = ("offset", "data") # slots=True only introduced in Python 3.10
offset: int
data: bytes
QueuedChunk: TypeAlias = Union[ChunkContent, _ChunkSentinel]
def should_multipart_download(size: int | None, override: bool | None = None) -> bool:
return ((size or 0) >= MIN_MULTI_DOWNLOA... | ChunkContent |
python | falconry__falcon | tests/test_utils.py | {
"start": 46566,
"end": 48021
} | class ____(testing.TestCase):
def setUp(self):
super().setUp()
with pytest.warns(UserWarning, match='API class will be removed in Falcon 5.0'):
self.app = falcon.API()
self.app.add_route('/', testing.SimpleTestResource(body='test'))
def test_something(self):
self.ass... | TestSetupApi |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/git_ref_package/package.py | {
"start": 228,
"end": 1988
} | class ____(AutotoolsPackage):
"""
dummy package copied from zlib-ng
"""
homepage = "https://github.com/dummy/dummy"
url = "https://github.com/dummy/dummy/archive/2.0.0.tar.gz"
git = "https://github.com/dummy/dummy.git"
version("develop", branch="develop")
version("main", branch="main")... | GitRefPackage |
python | tensorflow__tensorflow | tensorflow/python/util/nest_test.py | {
"start": 2146,
"end": 2755
} | class ____:
mask: bool
value: tensor.Tensor
def __tf_flatten__(self):
metadata = (self.mask,)
components = (self.value,)
return metadata, components
@classmethod
def __tf_unflatten__(cls, metadata, components):
mask = metadata[0]
value = components[0]
return MaskedTensor(mask=mask, v... | MaskedTensor |
python | scrapy__scrapy | tests/test_squeues.py | {
"start": 1453,
"end": 1665
} | class ____(t.FifoDiskQueueTest, FifoDiskQueueTestMixin):
chunksize = 100000
def queue(self):
return _MarshalFifoSerializationDiskQueue(self.qpath, chunksize=self.chunksize)
| MarshalFifoDiskQueueTest |
python | ray-project__ray | rllib/utils/from_config.py | {
"start": 10310,
"end": 11848
} | class ____:
"""Singleton class to provide a "not provided" value for AlgorithmConfig signatures.
Using the only instance of this class indicates that the user does NOT wish to
change the value of some property.
.. testcode::
:skipif: True
from ray.rllib.algorithms.algorithm_config imp... | _NotProvided |
python | pypa__warehouse | tests/unit/search/test_tasks.py | {
"start": 5546,
"end": 5720
} | class ____:
def __init__(*a, **kw):
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
| NotLock |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride3.py | {
"start": 2559,
"end": 2883
} | class ____:
@property
def prop1(self) -> str:
return ""
@property
def prop2(self) -> int:
return 3
@property
def prop3(self) -> int:
return 3
@prop3.setter
def prop3(self, val: str) -> None:
pass
# This should generate three errors: prop1, prop2 and p... | H2 |
python | Textualize__textual | src/textual/suggester.py | {
"start": 547,
"end": 2903
} | class ____(ABC):
"""Defines how widgets generate completion suggestions.
To define a custom suggester, subclass `Suggester` and implement the async method
`get_suggestion`.
See [`SuggestFromList`][textual.suggester.SuggestFromList] for an example.
"""
cache: LRUCache[str, str | None] | None
... | Suggester |
python | django__django | tests/fixtures_regress/models.py | {
"start": 6777,
"end": 6819
} | class ____(BaseNKModel):
pass
| M2MSimpleB |
python | getsentry__sentry | src/sentry/utils/marketo_client.py | {
"start": 90,
"end": 151
} | class ____(TypedDict):
code: str
message: str
| ErrorDict |
python | pydantic__pydantic | tests/mypy/modules/pydantic_settings.py | {
"start": 65,
"end": 288
} | class ____(BaseSettings):
foo: str
s = Settings()
s = Settings(foo='test', _case_sensitive=True, _env_prefix='test__', _env_file='test')
s = Settings(foo='test', _case_sensitive=1, _env_prefix=2, _env_file=3)
| Settings |
python | walkccc__LeetCode | solutions/2368. Reachable Nodes With Restrictions/2368.py | {
"start": 0,
"end": 417
} | class ____:
def reachableNodes(
self,
n: int,
edges: list[list[int]],
restricted: list[int],
) -> int:
tree = [[] for _ in range(n)]
seen = set(restricted)
for u, v in edges:
tree[u].append(v)
tree[v].append(u)
def dfs(u: int) -> int:
if u in seen:
... | Solution |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/decorators/__init__.py | {
"start": 1433,
"end": 2307
} | class ____:
"""Implementation to provide the ``@task`` syntax."""
run_if = staticmethod(run_if)
skip_if = staticmethod(skip_if)
def __getattr__(self, name: str) -> TaskDecorator:
"""Dynamically get provider-registered task decorators, e.g. ``@task.docker``."""
if name.startswith("__"):... | TaskDecoratorCollection |
python | pytorch__pytorch | torch/distributions/transforms.py | {
"start": 8515,
"end": 12879
} | class ____(Transform):
"""
Composes multiple transforms in a chain.
The transforms being composed are responsible for caching.
Args:
parts (list of :class:`Transform`): A list of transforms to compose.
cache_size (int): Size of cache. If zero, no caching is done. If one,
the... | ComposeTransform |
python | jazzband__django-model-utils | tests/test_models/test_softdeletable_model.py | {
"start": 170,
"end": 2361
} | class ____(TestCase):
def test_can_only_see_not_removed_entries(self) -> None:
SoftDeletable.available_objects.create(name='a', is_removed=True)
SoftDeletable.available_objects.create(name='b', is_removed=False)
queryset = SoftDeletable.available_objects.all()
self.assertEqual(quer... | SoftDeletableModelTests |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_cluster_trust_bundle_list.py | {
"start": 383,
"end": 7236
} | 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... | V1beta1ClusterTrustBundleList |
python | keras-team__keras | keras/src/distillation/distillation_loss.py | {
"start": 869,
"end": 2983
} | class ____:
"""Base class for distillation loss computation.
Distillation losses define how to compute the distillation loss
between teacher and student outputs. Each loss implements a specific
approach to knowledge transfer, from simple logits matching to feature-based
distillation.
To create... | DistillationLoss |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 13285,
"end": 14387
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = (
"ADDED_TO_PROJECT_EVENT",
"ASSIGNED_EVENT",
"CLOSED_EVENT",
"COMMENT_DELETED_EVENT",
"CONNECTED_EVENT",
"CONVERTED_NOTE_TO_ISSUE_EVENT",
... | IssueTimelineItemsItemType |
python | kamyu104__LeetCode-Solutions | Python/find-the-pivot-integer.py | {
"start": 36,
"end": 242
} | class ____(object):
def pivotInteger(self, n):
"""
:type n: int
:rtype: int
"""
x = int(((n+1)*n//2)**0.5+0.5)
return x if x**2 == (n+1)*n//2 else -1
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor32.py | {
"start": 272,
"end": 375
} | class ____(type):
def __call__(cls, *args, **kwargs):
super().__call__(*args, **kwargs)
| AMeta |
python | sphinx-doc__sphinx | sphinx/ext/graphviz.py | {
"start": 2871,
"end": 3522
} | class ____(nodes.General, nodes.Inline, nodes.Element):
pass
def figure_wrapper(
directive: SphinxDirective, node: graphviz, caption: str
) -> nodes.figure:
figure_node = nodes.figure('', node)
if 'align' in node:
figure_node['align'] = node.attributes.pop('align')
inodes, messages = dire... | graphviz |
python | pypa__warehouse | tests/unit/oidc/forms/test_github.py | {
"start": 4386,
"end": 17299
} | class ____:
@pytest.mark.parametrize(
("token", "headers"),
[
(
None,
{},
),
("fake-token", {"Authorization": "token fake-token"}),
],
)
def test_validate(self, token, headers, monkeypatch):
data = MultiDict(... | TestGitHubPublisherForm |
python | PrefectHQ__prefect | tests/utilities/test_pydantic.py | {
"start": 3657,
"end": 5755
} | class ____:
def test_init(self):
p = PartialModel(SimplePydantic)
assert p.model_cls == SimplePydantic
assert p.fields == {}
def test_init_with_fields(self):
p = PartialModel(SimplePydantic, x=1, y=2)
assert p.fields == {"x": 1, "y": 2}
m = p.finalize()
a... | TestPartialModel |
python | davidhalter__jedi | test/completion/pep0484_typing.py | {
"start": 209,
"end": 1883
} | class ____:
pass
def we_can_has_sequence(p: Sequence[int], q: Sequence[B], r: Sequence[int],
s: Sequence["int"], t: MutableSequence[dict], u: List[float]):
#? ["count"]
p.c
#? int()
p[1]
#? ["count"]
q.c
#? B()
q[1]
#? ["count"]
r.c
#? int()
r... | B |
python | numba__numba | numba/core/types/abstract.py | {
"start": 13989,
"end": 14323
} | class ____(Dummy):
"""Reference to a type.
Used when a type is passed as a value.
"""
def __init__(self, instance_type):
self.instance_type = instance_type
super(TypeRef, self).__init__('typeref[{}]'.format(self.instance_type))
@property
def key(self):
return self.insta... | TypeRef |
python | protocolbuffers__protobuf | python/google/protobuf/runtime_version.py | {
"start": 1024,
"end": 3037
} | class ____(Exception):
"""Exception class for version violation."""
def _ReportVersionError(msg):
raise VersionError(msg)
def ValidateProtobufRuntimeVersion(
gen_domain, gen_major, gen_minor, gen_patch, gen_suffix, location
):
"""Function to validate versions.
Args:
gen_domain: The domain where the... | VersionError |
python | pandas-dev__pandas | pandas/tests/series/test_iteration.py | {
"start": 0,
"end": 1278
} | class ____:
def test_keys(self, datetime_series):
assert datetime_series.keys() is datetime_series.index
def test_iter_datetimes(self, datetime_series):
for i, val in enumerate(datetime_series):
assert val == datetime_series.iloc[i]
def test_iter_strings(self, string_series):
... | TestIteration |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/debugger_cli_common_test.py | {
"start": 1513,
"end": 10488
} | class ____(test_util.TensorFlowTestCase):
def testRichTextLinesConstructorComplete(self):
# Test RichTextLines constructor.
screen_output = debugger_cli_common.RichTextLines(
["Roses are red", "Violets are blue"],
font_attr_segs={0: [(0, 5, "red")],
1: [(0, 7, "blue")]... | RichTextLinesTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/kubernetes_engine.py | {
"start": 2818,
"end": 3061
} | class ____(BaseGoogleLink):
"""Helper class for constructing Kubernetes Engine Workloads Link."""
name = "Kubernetes Workloads"
key = "kubernetes_workloads_conf"
format_str = KUBERNETES_WORKLOADS_LINK
| KubernetesEngineWorkloadsLink |
python | instagram__MonkeyType | tests/test_typing.py | {
"start": 1010,
"end": 3881
} | class ____:
@pytest.mark.parametrize(
'typ, other_type, expected_output',
[
(Any, Any, True),
(Any, int, False),
(Union[int, str], Union[int, str], True),
(Union[int, str], Union[int], False),
(Union[int, str], int, False),
(mak... | TestTypesEqual |
python | huggingface__transformers | src/transformers/models/glm4v/configuration_glm4v.py | {
"start": 1307,
"end": 5545
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Glm4vVisionModel`]. It is used to instantiate an Glm4vVisionModel
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield
a... | Glm4vVisionConfig |
python | pytorch__pytorch | test/cpp_extensions/open_registration_extension/torch_openreg/torch_openreg/openreg/__init__.py | {
"start": 174,
"end": 1666
} | class ____:
r"""Context-manager that changes the selected device.
Args:
device (torch.device or int): device index to select. It's a no-op if
this argument is a negative integer or ``None``.
"""
def __init__(self, device):
self.idx = torch.accelerator._get_device_index(devi... | device |
python | gevent__gevent | src/greentest/3.12/test_weakref.py | {
"start": 2019,
"end": 31471
} | class ____(TestBase):
def test_basic_ref(self):
self.check_basic_ref(C)
self.check_basic_ref(create_function)
self.check_basic_ref(create_bound_method)
# Just make sure the tp_repr handler doesn't raise an exception.
# Live reference:
o = C()
wr = weakref.re... | ReferencesTestCase |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 7638,
"end": 7726
} | class ____:
def __init_subclass__(cls, *args, **kwargs):
...
| InitSubclassParent |
python | django-haystack__django-haystack | haystack/backends/elasticsearch_backend.py | {
"start": 1623,
"end": 31027
} | class ____(BaseSearchBackend):
# Word reserved by Elasticsearch for special use.
RESERVED_WORDS = ("AND", "NOT", "OR", "TO")
# Characters reserved by Elasticsearch for special use.
# The '\\' must come first, so as not to overwrite the other slash replacements.
RESERVED_CHARACTERS = (
"\\",... | ElasticsearchSearchBackend |
python | huggingface__transformers | src/transformers/utils/quantization_config.py | {
"start": 56463,
"end": 64561
} | class ____(QuantizationConfigMixin):
"""
This is a wrapper class that handles compressed-tensors quantization config options.
It is a wrapper around `compressed_tensors.QuantizationConfig`
Args:
config_groups (`typing.dict[str, typing.Union[ForwardRef('QuantizationScheme'), typing.list[str]]]`, ... | CompressedTensorsConfig |
python | Pylons__pyramid | tests/test_encode.py | {
"start": 50,
"end": 2072
} | class ____(unittest.TestCase):
def _callFUT(self, query, doseq=False, **kw):
from pyramid.encode import urlencode
return urlencode(query, doseq, **kw)
def test_ascii_only(self):
result = self._callFUT([('a', 1), ('b', 2)])
self.assertEqual(result, 'a=1&b=2')
def test_unico... | UrlEncodeTests |
python | openai__openai-python | src/openai/types/beta/realtime/transcription_session.py | {
"start": 697,
"end": 1469
} | class ____(BaseModel):
language: Optional[str] = None
"""The language of the input audio.
Supplying the input language in
[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`)
format will improve accuracy and latency.
"""
model: Optional[Literal["gpt-4o-transcribe"... | InputAudioTranscription |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/synthesis.py | {
"start": 856,
"end": 1208
} | class ____(BaseEvent):
"""
GetResponseStartEvent.
Args:
query_str (str): Query string.
text_chunks (List[str]): List of text chunks.
"""
query_str: str
text_chunks: List[str]
@classmethod
def class_name(cls) -> str:
"""Class name."""
return "GetRespons... | GetResponseStartEvent |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/yaml_utils/__init__.py | {
"start": 559,
"end": 1735
} | class ____:
# Adds a "remove_implicit_resolver" method that can be used to selectively
# disable default PyYAML resolvers
@classmethod
def remove_implicit_resolver(cls, tag):
# See https://github.com/yaml/pyyaml/blob/master/lib/yaml/resolver.py#L26 for inspiration
if "yaml_implicit_reso... | _CanRemoveImplicitResolver |
python | numba__numba | numba/core/typing/templates.py | {
"start": 16150,
"end": 16986
} | class ____(FunctionTemplate):
"""
Defines attributes "cases" as a list of signature to match against the
given input types.
"""
def apply(self, args, kws):
cases = getattr(self, 'cases')
return self._select(cases, args, kws)
def get_template_info(self):
import operator
... | ConcreteTemplate |
python | sympy__sympy | sympy/assumptions/predicates/matrices.py | {
"start": 2626,
"end": 3663
} | class ____(Predicate):
"""
Orthogonal matrix predicate.
Explanation
===========
``Q.orthogonal(x)`` is true iff ``x`` is an orthogonal matrix.
A square matrix ``M`` is an orthogonal matrix if it satisfies
``M^TM = MM^T = I`` where ``M^T`` is the transpose matrix of
``M`` and ``I`` is a... | OrthogonalPredicate |
python | huggingface__transformers | tests/pipelines/test_pipelines_image_to_text.py | {
"start": 1131,
"end": 10081
} | class ____(unittest.TestCase):
model_mapping = MODEL_FOR_VISION_2_SEQ_MAPPING
def get_test_pipeline(
self,
model,
tokenizer=None,
image_processor=None,
feature_extractor=None,
processor=None,
dtype="float32",
):
pipe = ImageToTextPipeline(
... | ImageToTextPipelineTests |
python | apache__airflow | airflow-core/tests/unit/utils/test_entry_points.py | {
"start": 1155,
"end": 1975
} | class ____:
def distributions(self):
return [
MockDistribution(
"dist1",
[metadata.EntryPoint("a", "b", "group_x"), metadata.EntryPoint("c", "d", "group_y")],
),
MockDistribution("Dist2", [metadata.EntryPoint("e", "f", "group_x")]),
... | MockMetadata |
python | huggingface__transformers | src/transformers/models/megatron_bert/modeling_megatron_bert.py | {
"start": 1797,
"end": 4190
} | class ____(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.E... | MegatronBertEmbeddings |
python | redis__redis-py | redis/_parsers/commands.py | {
"start": 925,
"end": 1282
} | class ____:
def __init__(
self,
request_policy: RequestPolicy = RequestPolicy.DEFAULT_KEYLESS,
response_policy: ResponsePolicy = ResponsePolicy.DEFAULT_KEYLESS,
):
self.request_policy = request_policy
self.response_policy = response_policy
PolicyRecords = dict[str, dict... | CommandPolicies |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.