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 | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassHash1.py | {
"start": 150,
"end": 264
} | class ____:
a: int
# This should generate an error.
v1: Hashable = DC1(0)
@dataclass(eq=True, frozen=True)
| DC1 |
python | huggingface__transformers | src/transformers/models/squeezebert/modeling_squeezebert.py | {
"start": 25807,
"end": 30544
} | class ____(SqueezeBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.transformer = SqueezeBertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, 1)
# Initialize weights and apply f... | SqueezeBertForMultipleChoice |
python | astropy__astropy | astropy/io/fits/header.py | {
"start": 68488,
"end": 69404
} | class ____:
"""
This class allows to access cards with the _BasicHeader.cards attribute.
This is needed because during the HDU class detection, some HDUs uses
the .cards interface. Cards cannot be modified here as the _BasicHeader
object will be deleted once the HDU object is created.
"""
... | _BasicHeaderCards |
python | encode__django-rest-framework | rest_framework/authentication.py | {
"start": 3639,
"end": 4896
} | class ____(BaseAuthentication):
"""
Use Django's session framework for authentication.
"""
def authenticate(self, request):
"""
Returns a `User` if the request session currently has a logged in user.
Otherwise returns `None`.
"""
# Get the session-based user fro... | SessionAuthentication |
python | huggingface__transformers | src/transformers/models/kosmos2_5/modeling_kosmos2_5.py | {
"start": 75303,
"end": 83188
} | class ____(Kosmos2_5PreTrainedModel, GenerationMixin):
config_class = Kosmos2_5Config
def __init__(self, config: Kosmos2_5Config):
super().__init__(config)
self.text_model = Kosmos2_5TextForCausalLM(config.text_config)
self.vision_model = Kosmos2_5VisionModel(config.vision_config)
... | Kosmos2_5ForConditionalGeneration |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 116932,
"end": 117161
} | class ____(ServerAdapter):
def run(self,handler):
from socketio import server
address = (self.host, self.port)
server.SocketIOServer(address, handler, **self.options).serve_forever()
| GeventSocketIOServer |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/workspace/context.py | {
"start": 33425,
"end": 49129
} | class ____(IWorkspaceProcessContext[WorkspaceRequestContext]):
"""Process-scoped object that tracks the state of a workspace.
1. Maintains an update-to-date dictionary of repository locations
2. Creates a `WorkspaceRequestContext` to be the workspace for each request
3. Runs watch thread processes that... | WorkspaceProcessContext |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 3496,
"end": 8171
} | class ____(NonStrictDataModel):
"""
:param id: ROI id
:type id: str
:param label: ROI labels
:type label: Sequence[str]
:param poly: ROI polygon (x0, y0, ..., xn, yn)
:type poly: Sequence[float]
:param confidence: ROI confidence
:type confidence: float
:param meta: Additional met... | Roi |
python | pytorch__pytorch | test/distributed/test_launcher.py | {
"start": 690,
"end": 1359
} | class ____(TestCase):
def test_launch_user_script(self):
nnodes = 1
nproc_per_node = 4
sock = get_socket_with_port()
with closing(sock):
master_port = sock.getsockname()[1]
args = [
f"--nnodes={nnodes}",
f"--nproc-per-node={nproc_per_node}"... | TestDistributedLaunch |
python | ansible__ansible | lib/ansible/modules/user.py | {
"start": 87676,
"end": 100643
} | class ____(User):
"""
This is a Darwin macOS User manipulation class.
Main differences are that Darwin:-
- Handles accounts in a database managed by dscl(1)
- Has no useradd/groupadd
- Does not create home directories
- User password must be cleartext
- UID must be given
... | DarwinUser |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/index_flat_map_test.py | {
"start": 1686,
"end": 7936
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
"""Tests for global shuffling of index flat map datasets."""
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(use_tensors=[True, False])))
def test_split_strings(self, u... | IndexFlatMapTest |
python | facebookresearch__faiss | tests/test_index_accuracy.py | {
"start": 687,
"end": 5410
} | class ____(unittest.TestCase):
def test_IndexFlatIP(self):
q = faiss.IndexFlatIP(d) # Ask inner product
res = ev.launch("FLAT / IP", q)
e = ev.evalres(res)
assert e[1] == 1.0
def test_IndexFlatL2(self):
q = faiss.IndexFlatL2(d)
res = ev.launch("FLAT / L2", q)
... | IndexAccuracy |
python | pytest-dev__pytest-xdist | testing/test_looponfail.py | {
"start": 10525,
"end": 12214
} | class ____:
def test_fail_to_ok(self, pytester: pytest.Pytester) -> None:
p = pytester.makepyfile(
textwrap.dedent(
"""
def test_one():
x = 0
assert x == 1
"""
)
)
# p = pytester.m... | TestFunctional |
python | pydantic__pydantic | tests/mypy/modules/plugin_success.py | {
"start": 992,
"end": 1088
} | class ____(Model):
z: int = 1
InheritingModel.model_validate(model.__dict__)
| InheritingModel |
python | huggingface__transformers | tests/models/gemma3n/test_modeling_gemma3n.py | {
"start": 12394,
"end": 29645
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = Gemma3nTextModelTester
_is_stateful = True
model_split_percents = [0.5, 0.6]
def _check_hidden_states_for_generate(
self, batch_size, hidden_states, prompt_length, output_length, config, use_cache=False
):
"Gemma... | Gemma3nTextModelTest |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/bmm_test.py | {
"start": 799,
"end": 2348
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, B, M, N, K, device, dtype, op_func):
self.inputs = {
"batch1": torch.rand(
(B, M, N), device=device, dtype=dtype, requires_grad=self.auto_set()
),
"batch2": torch.rand(
(B, N, K), devi... | BatchedBinaryOpBenchmark |
python | sympy__sympy | sympy/polys/domains/field.py | {
"start": 357,
"end": 3172
} | class ____(Ring[Ef]):
"""Represents a field domain. """
is_Field = True
is_PID = True
def get_ring(self):
"""Returns a ring associated with ``self``. """
raise DomainError('there is no ring associated with %s' % self)
def get_field(self) -> Self:
"""Returns a field associa... | Field |
python | django__django | tests/template_tests/syntax_tests/test_named_endblock.py | {
"start": 116,
"end": 2475
} | class ____(SimpleTestCase):
@setup(
{
"namedendblocks01": "1{% block first %}_{% block second %}"
"2{% endblock second %}_{% endblock first %}3"
}
)
def test_namedendblocks01(self):
output = self.engine.render_to_string("namedendblocks01")
self.assertE... | NamedEndblockTests |
python | pypa__pipenv | pipenv/patched/pip/_internal/utils/temp_dir.py | {
"start": 6612,
"end": 9325
} | class ____(TempDirectory):
"""Helper class that creates a temporary directory adjacent to a real one.
Attributes:
original
The original directory to create a temp directory for.
path
After calling create() or entering, contains the full
path to the temporary ... | AdjacentTempDirectory |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_blocks/test_general_blocks.py | {
"start": 10447,
"end": 12227
} | class ____(util.MdCase):
"""Test Nested blocks and lists."""
extension = ['pymdownx.blocks.tab', 'pymdownx.blocks.html']
extension_configs = {
'pymdownx.blocks.tab': {'alternate_style': True}
}
def test_nested_blocks_in_lists(self):
"""Test a nested blocks case with lists."""
... | TestNestedBlocksAndLists |
python | tensorflow__tensorflow | tensorflow/python/ops/nn_fused_batchnorm_d9m_test.py | {
"start": 1408,
"end": 7073
} | class ____(test.TestCase,
parameterized.TestCase):
"""Test determinsitic functionality and exceptions for FusedBatchNorm.
Test that tf.errors.UnimplementedError is thrown, as
appropriate, by the GPU code-path through FusedBatchNormFreezeGrad when
deterministic ops... | FusedBatchNormalizationDeterministicTest |
python | huggingface__transformers | tests/models/internvl/test_video_processing_internvl.py | {
"start": 1043,
"end": 2923
} | class ____:
def __init__(
self,
parent,
batch_size=5,
num_frames=8,
num_channels=3,
min_resolution=30,
max_resolution=80,
do_resize=True,
size=None,
do_normalize=True,
image_mean=OPENAI_CLIP_MEAN,
image_std=OPENAI_CLIP_S... | InternVLVideoProcessingTester |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/interactive.py | {
"start": 827,
"end": 7351
} | class ____:
"""
``interact`` can be used with regular functions. However, when they are connected to
changed or changing signals, there is no way to access these connections later to
i.e. disconnect them temporarily. This utility class wraps a normal function but
can provide an external scope for ac... | InteractiveFunction |
python | pytorch__pytorch | torch/ao/quantization/backend_config/backend_config.py | {
"start": 1475,
"end": 2146
} | class ____(Enum):
"""An enum that represents different ways of how an operator/operator pattern
should be observed
"""
OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT = 0
"""this means input and output are observed with different observers, based
on qconfig.activation
example: conv, linear, softmax
... | ObservationType |
python | getsentry__sentry | src/sentry/conf/types/role_dict.py | {
"start": 80,
"end": 322
} | class ____(TypedDict):
id: str
name: str
desc: str
scopes: set[str]
is_retired: NotRequired[bool]
is_global: NotRequired[bool]
is_minimum_role_for: NotRequired[str]
is_team_roles_allowed: NotRequired[bool]
| RoleDict |
python | spyder-ide__spyder | spyder/plugins/pylint/main_widget.py | {
"start": 1981,
"end": 2164
} | class ____:
ChangeHistory = "change_history_depth_action"
RunCodeAnalysis = "run_analysis_action"
BrowseFile = "browse_action"
ShowLog = "log_action"
| PylintWidgetActions |
python | pyqtgraph__pyqtgraph | doc/source/images/gen_example_gradient_plot.py | {
"start": 181,
"end": 2027
} | class ____(pg.GraphicsLayoutWidget):
""" example application main window """
def __init__(self):
super().__init__()
self.resize(420,400)
self.show()
# Prepare demonstration data
raw = np.linspace(0.0, 2.0, 400)
y_data1 = ( (raw+0.1)%1 ) ** 4
y_data2 = ( (... | MainWindow |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/links/emr.py | {
"start": 4385,
"end": 5032
} | class ____(BaseAwsLink):
"""Helper class for constructing Amazon EMR Serverless link to Spark stdout logs."""
name = "Spark Driver stdout"
key = "emr_serverless_logs"
def format_link(self, application_id: str | None = None, job_run_id: str | None = None, **kwargs) -> str:
if not application_id... | EmrServerlessLogsLink |
python | pytorch__pytorch | test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_storage.py | {
"start": 805,
"end": 8437
} | class ____(TestCase):
def test_serialization(self):
storage = torch.UntypedStorage(4, device=torch.device("openreg"))
self.assertEqual(torch.serialization.location_tag(storage), "openreg:0")
storage = torch.UntypedStorage(4, device=torch.device("openreg:0"))
self.assertEqual(torch.s... | TestSerialization |
python | ray-project__ray | python/ray/serve/_private/router.py | {
"start": 39735,
"end": 44418
} | class ____(Router):
"""Wrapper class that runs an AsyncioRouter on a separate thread.
The motivation for this is to avoid user code blocking the event loop and
preventing the router from making progress.
Maintains a singleton event loop running in a daemon thread that is shared by
all AsyncioRoute... | SingletonThreadRouter |
python | run-llama__llama_index | llama-index-core/llama_index/core/query_engine/flare/schema.py | {
"start": 68,
"end": 163
} | class ____:
"""Query task."""
query_str: str
start_idx: int
end_idx: int
| QueryTask |
python | PrefectHQ__prefect | src/prefect/client/collections.py | {
"start": 196,
"end": 1050
} | class ____(Protocol):
async def read_worker_metadata(self) -> Dict[str, Any]: ...
async def __aenter__(self) -> "CollectionsMetadataClient": ...
async def __aexit__(self, *exc_info: Any) -> Any: ...
def get_collections_metadata_client(
httpx_settings: Optional[Dict[str, Any]] = None,
) -> "Collectio... | CollectionsMetadataClient |
python | kubernetes-client__python | kubernetes/client/models/v1_stateful_set_status.py | {
"start": 383,
"end": 14116
} | 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... | V1StatefulSetStatus |
python | realpython__materials | python-enum/iterate.py | {
"start": 24,
"end": 423
} | class ____(Enum):
VANILLA = 1
CHOCOLATE = 2
MINT = 3
# Iterating over members
for flavor in Flavor:
print(flavor)
# Iterating over members' names
for flavor in Flavor:
print(flavor.name)
# Iterating over members' value
for flavor in Flavor:
print(flavor.value)
# Iterating over __members__
f... | Flavor |
python | huggingface__transformers | src/transformers/models/xlm/modeling_xlm.py | {
"start": 62985,
"end": 66878
} | class ____(XLMPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.transformer = XLMModel(config)
self.dropout = nn.Dropout(config.dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
... | XLMForTokenClassification |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-koda-retriever/llama_index/packs/koda_retriever/base.py | {
"start": 10025,
"end": 11245
} | class ____(BaseLlamaPack):
def __init__(
self,
index: VectorStoreIndex,
llm: Optional[LLM] = None, # if I could, I'd default to
reranker: Optional[BaseNodePostprocessor] = None,
default_alpha: float = 0.5,
matrix: dict or AlphaMatrix = DEFAULT_CATEGORIES, # type: ig... | KodaRetrieverPack |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_util_test.py | {
"start": 10833,
"end": 11060
} | class ____(object):
def __init__(self, domain_dimension):
self._domain_dimension = ops.convert_to_tensor(domain_dimension)
def domain_dimension_tensor(self):
return self._domain_dimension
| DomainDimensionStubOperator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor15.py | {
"start": 414,
"end": 602
} | class ____(Generic[_M, _N]):
def __new__(cls, m: _M, n: _N) -> "B[_M, _N]": ...
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
b: B[Literal[3], Literal[4]] = B(3, 4)
| B |
python | sqlalchemy__sqlalchemy | test/orm/test_deferred.py | {
"start": 54029,
"end": 72863
} | class ____(_Polymorphic):
__dialect__ = "default"
@classmethod
def setup_mappers(cls):
super().setup_mappers()
from sqlalchemy import inspect
inspect(Company).add_property(
"managers", relationship(Manager, viewonly=True)
)
def test_load_only_subclass(self)... | InheritanceTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/forLoop1.py | {
"start": 1606,
"end": 1962
} | class ____:
@overload
def __getitem__(self, i: int) -> str:
...
@overload
def __getitem__(self, i: slice) -> list[str]:
...
def __getitem__(self, i: int | slice) -> str | list[str]:
...
c = C()
for c1 in iter(c):
reveal_type(c1, expected_text="str")
for c2 in c:
... | C |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 13285,
"end": 13476
} | class ____(SchemaBase):
_rootschema = load_schema()
@classmethod
def _default_wrapper_classes(cls) -> Iterator[type[Any]]:
return _subclasses(VegaLiteSchema)
| VegaLiteSchema |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-words-found-in-sentences.py | {
"start": 29,
"end": 227
} | class ____(object):
def mostWordsFound(self, sentences):
"""
:type sentences: List[str]
:rtype: int
"""
return 1+max(s.count(' ') for s in sentences)
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/components/core/defs_module.py | {
"start": 2139,
"end": 3663
} | class ____(BaseModel):
model_config = ConfigDict(extra="forbid")
type: str
attributes: Optional[Mapping[str, Any]] = None
template_vars_module: Optional[str] = None
requirements: Optional[ComponentRequirementsModel] = None
post_processing: Optional[Mapping[str, Any]] = None
def _add_defs_yaml... | ComponentFileModel |
python | PrefectHQ__prefect | tests/experimental/test_bundles.py | {
"start": 13108,
"end": 20786
} | class ____:
def test_is_local_module_builtin(self):
"""Test that built-in modules are not considered local."""
assert not _is_local_module("sys")
assert not _is_local_module("os")
assert not _is_local_module("json")
@pytest.mark.skipif(
not hasattr(sys, "stdlib_module_na... | TestLocalDependencyDiscovery |
python | PyCQA__pylint | pylint/pyreverse/mermaidjs_printer.py | {
"start": 3767,
"end": 4506
} | class ____(MermaidJSPrinter):
"""Printer for MermaidJS diagrams wrapped in a html boilerplate."""
HTML_OPEN_BOILERPLATE = """<html>
<body>
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<div class="mermaid">
"""
HTML_CLOSE_BOILERPLATE = """
</div>
... | HTMLMermaidJSPrinter |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 3008,
"end": 3122
} | class ____(factory.django.DjangoModelFactory):
class Meta:
model = models.WithSignals
| WithSignalsFactory |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_import_functionality.py | {
"start": 15745,
"end": 20940
} | class ____(AdminTestMixin, TransactionTestCase):
fixtures = ["author"]
def _is_str_in_response(
self,
filename,
input_format,
encoding=None,
str_in_response=None,
follow=False,
status_code=200,
):
response = self._do_import_post(
s... | TestImportSkipConfirm |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_price.py | {
"start": 1603,
"end": 3806
} | class ____(ColumnMapExpectation):
"""Expect column values to conform to valid price formats."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"well_formed_price": [
... | ExpectColumnValuesToBeValidPrice |
python | bokeh__bokeh | src/bokeh/models/widgets/inputs.py | {
"start": 17968,
"end": 19750
} | class ____(InputWidget):
''' Color palette select widget.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
value = Required(String, help="""
The name of the initial or selected color palette.
... | PaletteSelect |
python | eth-brownie__brownie | brownie/network/middlewares/catch_tx_revert.py | {
"start": 195,
"end": 1144
} | class ____(BrownieMiddlewareABC):
"""
Middleware to handle reverting transactions, bypasses web3 error formatting.
As of web3.py version 5.13.0, a new error formatting middleware was added by default
`raise_solidity_error_on_revert` which when a `eth_call` or `eth_estimateGas` tx
raises a `Contract... | TxRevertCatcherMiddleware |
python | etianen__django-reversion | tests/test_app/tests/test_api.py | {
"start": 433,
"end": 574
} | class ____(TestModelMixin, TestBase):
def testModelSave(self):
TestModel.objects.create()
self.assertNoRevision()
| SaveTest |
python | scrapy__scrapy | scrapy/exceptions.py | {
"start": 663,
"end": 749
} | class ____(Exception):
"""Request the spider not to be closed yet"""
| DontCloseSpider |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_outside_compilation_test.py | {
"start": 17406,
"end": 26482
} | class ____(test.TestCase,
parameterized.TestCase):
def setUp(self):
super(OutsideCompilationOnUnsupportedOpTest, self).setUp()
config.set_soft_device_placement(True)
def testStringOpWithManualOutsideCompilation(self):
strategy = get_tpu_strategy()
@def_... | OutsideCompilationOnUnsupportedOpTest |
python | pandas-dev__pandas | pandas/tests/indexes/timedeltas/test_scalar_compat.py | {
"start": 355,
"end": 4851
} | class ____:
def test_tdi_total_seconds(self):
# GH#10939
# test index
rng = timedelta_range("1 days, 10:11:12.100123456", periods=2, freq="s")
expt = [
1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456.0 / 1e9,
1 * 86400 + 10 * 3600 + 11 * 60 + 13 + 100123456.0... | TestVectorizedTimedelta |
python | plotly__plotly.py | plotly/graph_objs/layout/yaxis/_tickfont.py | {
"start": 235,
"end": 9884
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.yaxis"
_path_str = "layout.yaxis.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@prop... | Tickfont |
python | chroma-core__chroma | chromadb/segment/distributed/__init__.py | {
"start": 238,
"end": 1003
} | class ____(Component):
"""A segment directory is a data interface that manages the location of segments. Concretely, this
means that for distributed chroma, it provides the grpc endpoint for a segment."""
@abstractmethod
def get_segment_endpoints(self, segment: Segment, n: int) -> List[str]:
""... | SegmentDirectory |
python | pytorch__pytorch | test/export/test_draft_export.py | {
"start": 597,
"end": 25619
} | class ____(TestCase):
def setUp(self):
super().setUp()
init_torchbind_implementations()
self.torch_bind_ops = [
torch.ops._TorchScriptTesting.queue_pop,
torch.ops._TorchScriptTesting.queue_push,
torch.ops._TorchScriptTesting.queue_size,
]
def... | TestDraftExport |
python | getsentry__sentry | src/sentry/interfaces/stacktrace.py | {
"start": 3809,
"end": 11512
} | class ____(Interface):
grouping_variants = ["system", "app"]
@classmethod
def to_python(cls, data, **kwargs):
for key in (
"abs_path",
"colno",
"context_line",
"data",
"errors",
"filename",
"function",
"... | Frame |
python | numba__numba | numba/core/typing/arraydecl.py | {
"start": 7907,
"end": 8193
} | class ____(AbstractTemplate):
def generic(self, args, kws):
assert not kws
[ary, idx] = args
out = get_array_index_type(ary, idx)
if out is not None:
return signature(out.result, ary, out.index)
@infer_global(operator.setitem)
| GetItemBuffer |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 23221,
"end": 26789
} | class ____:
def __init__(self, body: LoopBody) -> None:
self.body = body
self.graphs: dict[Union[Callable[..., Any], str], Any] = {
"root": body.root_block.graph
}
for k, v in body.subblocks.items():
self.graphs[k] = v.graph
def deduce_node_dtype_by_input... | DataTypePropagation |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_tests.py | {
"start": 81616,
"end": 83084
} | class ____(TestCase):
class Schema(Config):
plugins = c.Plugins(default=[])
hooks = c.Hooks('plugins')
@tempdir()
def test_hooks(self, src_dir) -> None:
write_file(
b'def on_page_markdown(markdown, **kwargs): return markdown.replace("f", "z")',
os.path.join(s... | HooksTest |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/linux/mkl/set-build-env.py | {
"start": 7901,
"end": 13493
} | class ____(object):
"""Prepares the proper environment settings for various Intel platforms."""
default_platform_ = "haswell"
PLATFORMS_ = {
"nehalem": NehalemPlatform(),
"sandybridge": SandyBridgePlatform(),
"haswell": HaswellPlatform(),
"skylake": SkylakePlatform(),
"cascadelake":... | BuildEnvSetter |
python | ray-project__ray | python/ray/autoscaler/_private/cli_logger.py | {
"start": 677,
"end": 1919
} | class ____:
def __init__(self):
# do not do any color work
self.identity = lambda x: x
self.colorful = self
self.colormode = None
self.NO_COLORS = None
self.ANSI_8_COLORS = None
def disable(self):
pass
@contextmanager
def with_style(self, x):
... | _ColorfulMock |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dags.py | {
"start": 45897,
"end": 48456
} | class ____(TestDagEndpoint):
"""Unit tests for Delete DAG."""
def _create_dag_for_deletion(
self,
dag_maker,
dag_id=None,
dag_display_name=None,
has_running_dagruns=False,
):
with dag_maker(
dag_id,
dag_display_name=dag_display_name,
... | TestDeleteDAG |
python | huggingface__transformers | src/transformers/models/gptj/modeling_gptj.py | {
"start": 18707,
"end": 19029
} | class ____(PreTrainedModel):
config: GPTJConfig
base_model_prefix = "transformer"
supports_gradient_checkpointing = True
_no_split_modules = ["GPTJBlock"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_can_compile_fullgraph = True
@auto_docstring
| GPTJPreTrainedModel |
python | h5py__h5py | h5py/_hl/base.py | {
"start": 11537,
"end": 11741
} | class ____(KeysView):
def __str__(self):
return "<KeysViewHDF5 {}>".format(list(self))
def __reversed__(self):
yield from reversed(self._mapping)
__repr__ = __str__
| KeysViewHDF5 |
python | pytorch__pytorch | torch/_inductor/codegen/memory_planning.py | {
"start": 691,
"end": 1398
} | class ____:
"""
A range where a given tensor is live. Begin and end are both counters
representing points in the program of grouped memory operations.
Begin is inclusive, end is exclusive.
Invariant: begin <= end
"""
begin: float # int | +/-inf
end: float # int | +/-inf
def con... | LiveRange |
python | kamyu104__LeetCode-Solutions | Python/find-special-substring-of-length-k.py | {
"start": 38,
"end": 406
} | class ____(object):
def hasSpecialSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: bool
"""
l = 0
for i in xrange(len(s)):
l += 1
if i+1 == len(s) or s[i] != s[i+1]:
if l == k:
return True... | Solution |
python | getsentry__sentry | tests/sentry/uptime/subscriptions/test_tasks.py | {
"start": 1404,
"end": 2891
} | class ____(UptimeTestCase):
__test__ = Abstract(__module__, __qualname__)
def assert_redis_config(
self,
region: str,
sub: UptimeSubscription,
action: str | None,
region_mode: UptimeSubscriptionRegion.RegionMode | None,
):
region_config = get_region_config(re... | ConfigPusherTestMixin |
python | getsentry__sentry | src/sentry/data_export/models.py | {
"start": 824,
"end": 5683
} | class ____(Model):
"""
Stores references to asynchronous data export jobs
"""
__relocation_scope__ = RelocationScope.Excluded
organization = FlexibleForeignKey("sentry.Organization")
user_id = HybridCloudForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete="SET_NULL")
file_id = Bounde... | ExportedData |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 8106,
"end": 8422
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneMessageEvent, GrapheneStepEvent, GrapheneDisplayableEvent)
name = "ExecutionStepOutputEvent"
output_name = graphene.NonNull(graphene.String)
type_check = graphene.NonNull(GrapheneTypeCheck)
| GrapheneExecutionStepOutputEvent |
python | allegroai__clearml | clearml/backend_api/session/errors.py | {
"start": 291,
"end": 343
} | class ____(SessionError):
pass
| TimeoutExpiredError |
python | FactoryBoy__factory_boy | factory/errors.py | {
"start": 537,
"end": 748
} | class ____(FactoryError):
"""Raised when a sub-declaration has no related declaration.
This means that the user declared 'foo__bar' without adding a declaration
at 'foo'.
"""
| InvalidDeclarationError |
python | ansible__ansible | lib/ansible/galaxy/collection/gpg.py | {
"start": 3921,
"end": 4101
} | class ____(GpgBaseError):
"""The signature with the keyid is good, but the signature is expired."""
keyid: str
username: str
@dataclass(frozen=True, slots=True)
| GpgExpSig |
python | python-poetry__poetry | src/poetry/mixology/version_solver.py | {
"start": 5060,
"end": 26690
} | class ____:
"""
The version solver that finds a set of package versions that satisfy the
root package's dependencies.
See https://github.com/dart-lang/pub/tree/master/doc/solver.md for details
on how this solver works.
"""
def __init__(self, root: ProjectPackage, provider: Provider) -> Non... | VersionSolver |
python | django__django | django/templatetags/i18n.py | {
"start": 2092,
"end": 3341
} | class ____(Node):
child_nodelists = ()
def __init__(self, filter_expression, noop, asvar=None, message_context=None):
self.noop = noop
self.asvar = asvar
self.message_context = message_context
self.filter_expression = filter_expression
if isinstance(self.filter_expressio... | TranslateNode |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/autoclass_content.py | {
"start": 503,
"end": 678
} | class ____:
"""A class having both __init__ and __new__"""
def __init__(self):
"""__init__ docstring"""
def __new__(cls):
"""__new__ docstring"""
| F |
python | pytorch__pytorch | test/inductor/test_ordered_set.py | {
"start": 53769,
"end": 53985
} | class ____(TestCopying, TestCase):
def setUp(self):
super().setUp()
self.OrderedSet = OrderedSet()
# ------------------------------------------------------------------------------
| TestCopyingEmpty |
python | numba__numba | numba/core/typing/context.py | {
"start": 445,
"end": 1186
} | class ____(object):
__slots__ = 'promote', 'safe_convert', "unsafe_convert"
def __init__(self):
self.promote = 0
self.safe_convert = 0
self.unsafe_convert = 0
def astuple(self):
"""Returns a tuple suitable for comparing with the worse situation
start first.
... | Rating |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_getlimits.py | {
"start": 4919,
"end": 7576
} | class ____(TestCase):
@skip(reason="Instantiate {i,f}info from dtypes.")
def test_instances(self):
iinfo(10)
finfo(3.0)
@skip(reason="MachAr no implemented (does it need to)?")
def test_known_types(self):
# Test we are correctly compiling parameters for known types
for f... | TestMisc |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 11417,
"end": 11580
} | class ____(Document):
history = HistoricalRecords()
@Document._history_user.setter
def _history_user(self, value):
self.changed_by = value
| Paper |
python | jupyterlab__jupyterlab | jupyterlab/extensions/manager.py | {
"start": 4434,
"end": 4957
} | class ____:
"""Plugin manager options.
Attributes:
lock_all: Whether to lock (prevent enabling/disabling) all plugins.
lock_rules: A list of plugins or extensions that cannot be toggled.
If extension name is provided, all its plugins will be disabled.
The plugin names ne... | PluginManagerOptions |
python | getsentry__sentry-python | sentry_sdk/integrations/pymongo.py | {
"start": 2802,
"end": 6164
} | class ____(monitoring.CommandListener):
def __init__(self):
# type: () -> None
self._ongoing_operations = {} # type: Dict[int, Span]
def _operation_key(self, event):
# type: (Union[CommandFailedEvent, CommandStartedEvent, CommandSucceededEvent]) -> int
return event.request_id
... | CommandTracer |
python | huggingface__transformers | src/transformers/models/camembert/modular_camembert.py | {
"start": 15281,
"end": 18428
} | class ____(RobertaForQuestionAnswering):
def __init__(self, config):
super().__init__(config)
del self.camembert
self.roberta = CamembertModel(config, add_pooling_layer=False)
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTen... | CamembertForQuestionAnswering |
python | rapidsai__cudf | python/cudf/cudf/core/series.py | {
"start": 14236,
"end": 14290
} | class ____(_SeriesLocIndexer):
pass
| _SeriesAtIndexer |
python | lazyprogrammer__machine_learning_examples | rl2/a3c/thread_example.py | {
"start": 90,
"end": 982
} | class ____:
def __init__(self, id_, global_counter):
self.id = id_
self.global_counter = global_counter
self.local_counter = itertools.count()
def run(self):
while True:
time.sleep(np.random.rand()*2)
global_step = next(self.global_counter)
local_step = next(self.local_counter)
... | Worker |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 18419,
"end": 18836
} | class ____(ChainedSource):
idx: int
def __post_init__(self) -> None:
assert self.base is not None
def reconstruct(self, codegen: "PyCodegen") -> None:
raise NotImplementedError
def guard_source(self) -> GuardSource:
return self.base.guard_source()
def name(self) -> str:
... | IndexedSource |
python | python-pillow__Pillow | Tests/test_imagewin.py | {
"start": 116,
"end": 620
} | class ____:
def test_sanity(self) -> None:
dir(ImageWin)
def test_hdc(self) -> None:
# Arrange
dc = 50
# Act
hdc = ImageWin.HDC(dc)
dc2 = int(hdc)
# Assert
assert dc2 == 50
def test_hwnd(self) -> None:
# Arrange
wnd = 50
... | TestImageWin |
python | huggingface__transformers | src/transformers/models/instructblipvideo/modular_instructblipvideo.py | {
"start": 6823,
"end": 6943
} | class ____(InstructBlipForConditionalGenerationModelOutput):
pass
| InstructBlipVideoForConditionalGenerationModelOutput |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 34853,
"end": 35835
} | class ____(nn.Module):
def __init__(self, length, channels, max_timescale=10000):
super().__init__()
if channels % 2 != 0:
raise ValueError("SinusoidsPositionEmbedding needs even channels input")
log_timescale_increment = np.log(max_timescale) / (channels // 2 - 1)
inv_ti... | SinusoidsPositionEmbedding |
python | plotly__plotly.py | tests/test_core/test_graph_objs/test_instantiate_hierarchy.py | {
"start": 303,
"end": 1406
} | class ____(TestCase):
def test_construct_datatypes(self):
for datatypes_module in datatype_modules:
module = importlib.import_module(datatypes_module)
for name in getattr(module, "__all__", []):
if name.startswith("_") or name[0].islower() or name == "FigureWidget":
... | HierarchyTest |
python | huggingface__transformers | src/transformers/models/pixtral/modeling_pixtral.py | {
"start": 1743,
"end": 8336
} | class ____(nn.Module):
"""
The key with pixtral embedding is just that you have a frequency for each pixel positions.
If you have height x width pixels (or embedding pixels), then the frequency used for ROPE
is given by indexing the pre_computed frequency on the width and height.
What you output is... | PixtralRotaryEmbedding |
python | ray-project__ray | python/ray/train/base_trainer.py | {
"start": 4480,
"end": 37414
} | class ____(abc.ABC):
"""Defines interface for distributed training on Ray.
Note: The base ``BaseTrainer`` class cannot be instantiated directly. Only
one of its subclasses can be used.
Note to developers: If a new trainer is added, please update
`air/_internal/usage.py`.
**How does a trainer ... | BaseTrainer |
python | getsentry__sentry | src/sentry/search/events/fields.py | {
"start": 37674,
"end": 38539
} | class ____(ColumnArg):
def __init__(self, name: str, **kwargs):
super().__init__(name, **kwargs)
self.has_default = True
def get_default(self, _) -> None:
return None
def normalize(
self, value: str, params: ParamsType, combinator: Combinator | None
) -> str | list[Any]... | CountColumn |
python | spack__spack | lib/spack/spack/util/file_cache.py | {
"start": 617,
"end": 1037
} | class ____:
def __init__(self, path: Union[str, pathlib.Path]) -> None:
self.path = path
def __enter__(self) -> Optional[IO[str]]:
"""Return a file object for the cache if it exists."""
self.cache_file = _maybe_open(self.path)
return self.cache_file
def __exit__(self, type,... | ReadContextManager |
python | huggingface__transformers | src/transformers/models/janus/modeling_janus.py | {
"start": 16779,
"end": 17791
} | class ____(nn.Module):
"""
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`JanusVisionEncoderLayer`].
Args:
config: JanusVisionConfig
"""
def __init__(self, config: JanusVisionConfig):
super().__init__()
self.config ... | JanusVisionEncoder |
python | geekcomputers__Python | BrowserHistory/tests/test_browser_history.py | {
"start": 201,
"end": 3525
} | class ____(unittest.TestCase):
def setUp(self):
"""Set up test cases"""
self.browser = BrowserHistory("homepage.com")
def test_initialization(self):
"""Test proper initialization of BrowserHistory"""
self.assertEqual(self.browser._curr.val, "homepage.com")
self.assertEqu... | TestBrowserHistory |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/taskqueue/pull-counter/main.py | {
"start": 1640,
"end": 2588
} | class ____(webapp2.RequestHandler):
def get(self):
"""Indefinitely fetch tasks and update the datastore."""
queue = taskqueue.Queue("pullq")
while True:
try:
tasks = queue.lease_tasks_by_tag(3600, 1000, deadline=60)
except (
taskqueue.T... | CounterWorker |
python | mlflow__mlflow | mlflow/store/artifact/utils/models.py | {
"start": 1760,
"end": 6353
} | class ____(NamedTuple):
model_id: str | None = None
name: str | None = None
version: str | None = None
stage: str | None = None
alias: str | None = None
def _parse_model_uri(uri, scheme: str = "models") -> ParsedModelUri:
"""
Returns a ParsedModelUri tuple. Since a models:/ or prompts:/ UR... | ParsedModelUri |
python | pytorch__pytorch | benchmarks/tensorexpr/reduction.py | {
"start": 7170,
"end": 7666
} | class ____(DynamicReduce2DBench):
def __init__(self, mode, device, dtype, dim0, dim1):
super().__init__(mode, device, dtype, 1, dim0, dim1)
@staticmethod
def default_configs():
parent_config = DynamicReduce2DBench.default_configs()[0]
return [parent_config[1:]]
def config(self)... | DynamicReduce2DInnerBench |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.