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 | ray-project__ray | python/ray/dashboard/http_server_head.py | {
"start": 3326,
"end": 17542
} | class ____:
def __init__(
self,
ip: str,
http_host: str,
http_port: int,
http_port_retries: int,
gcs_address: str,
session_name: str,
metrics: DashboardPrometheusMetrics,
):
self.ip = ip
self.http_host = http_host
self.http_... | HttpServerDashboardHead |
python | facebookresearch__faiss | contrib/datasets.py | {
"start": 5418,
"end": 6848
} | class ____(Dataset):
"""
The original dataset is available at: http://corpus-texmex.irisa.fr/
(ANN_SIFT1B)
"""
def __init__(self, nb_M=1000):
Dataset.__init__(self)
assert nb_M in (1, 2, 5, 10, 20, 50, 100, 200, 500, 1000)
self.nb_M = nb_M
nb = nb_M * 10**6
s... | DatasetBigANN |
python | sympy__sympy | sympy/stats/random_matrix_models.py | {
"start": 8146,
"end": 9522
} | class ____(RandomMatrixEnsembleModel):
"""
Abstract class for Circular ensembles.
Contains the properties and methods
common to all the circular ensembles.
References
==========
.. [1] https://en.wikipedia.org/wiki/Circular_ensemble
"""
def density(self, expr):
# TODO : Add... | CircularEnsembleModel |
python | lazyprogrammer__machine_learning_examples | rl2/atari/dqn_theano.py | {
"start": 1478,
"end": 5937
} | class ____:
def __init__(self, size=MAX_EXPERIENCES, frame_height=IM_SIZE, frame_width=IM_SIZE,
agent_history_length=4, batch_size=32):
"""
Args:
size: Integer, Number of stored transitions
frame_height: Integer, Height of a frame of an Atari game
frame_width: Integer, ... | ReplayMemory |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 10202,
"end": 11525
} | class ____(Pix2SkyProjection, Zenithal):
r"""
Slant zenithal perspective projection - pixel to sky.
Corresponds to the ``SZP`` projection in FITS WCS.
Parameters
----------
mu : float
Distance from point of projection to center of sphere
in spherical radii, μ. Default is 0.
... | Pix2Sky_SlantZenithalPerspective |
python | getsentry__sentry-python | tests/integrations/wsgi/test_wsgi.py | {
"start": 501,
"end": 14767
} | class ____:
def __init__(self, exc_func):
self._exc_func = exc_func
def __iter__(self):
return self
def __next__(self):
raise self._exc_func()
def next(self):
return type(self).__next__(self)
def test_basic(sentry_init, crashing_app, capture_events):
sentry_init(... | ExitingIterable |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/generic_utils.py | {
"start": 6879,
"end": 8190
} | class ____(dict):
"""A configuration container that keeps track of references.
`SharedObjectConfig` will automatically attach a shared object ID to any
configs which are referenced more than once, allowing for proper shared
object reconstruction at load time.
In most cases, it would be more proper to subcla... | SharedObjectConfig |
python | prabhupant__python-ds | data_structures/bst/kth_largest_in_bst.py | {
"start": 178,
"end": 997
} | class ____():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def reverse_inorder(root, k):
if not root:
return None
counter = 1
stack = []
while True:
if root:
stack.append(root)
root = root.right
... | Node |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/mpich/package.py | {
"start": 217,
"end": 1542
} | class ____(Package):
homepage = "http://www.mpich.org"
url = "http://www.mpich.org/static/downloads/3.0.4/mpich-3.0.4.tar.gz"
list_url = "http://www.mpich.org/static/downloads/"
list_depth = 2
tags = ["tag1", "tag2"]
executables = ["^mpichversion$"]
variant("debug", default=False, descript... | Mpich |
python | huggingface__transformers | src/transformers/models/gemma3/modular_gemma3.py | {
"start": 2165,
"end": 12423
} | class ____(Gemma2Config, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Gemma3TextModel`]. It is used to instantiate an Gemma3Text
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will ... | Gemma3TextConfig |
python | numba__numba | numba/core/errors.py | {
"start": 1249,
"end": 1393
} | class ____(NumbaWarning):
"""
Warning category for when an operation might not be
as fast as expected.
"""
| NumbaPerformanceWarning |
python | mlflow__mlflow | mlflow/gateway/schemas/completions.py | {
"start": 1521,
"end": 2023
} | class ____(ResponseModel):
index: int
finish_reason: str | None = None
text: str | None = None
_STREAM_RESPONSE_PAYLOAD_EXTRA_SCHEMA = {
"example": {
"id": "cmpl-123",
"object": "text_completion",
"created": 1589478378,
"model": "gpt-4",
"choices": [
... | StreamChoice |
python | allegroai__clearml | clearml/backend_interface/task/log.py | {
"start": 608,
"end": 7676
} | class ____(BackgroundMonitor):
__max_event_size = 1024 * 1024
def __init__(
self,
session: Any,
wait_period: float,
worker: Any = None,
task: Any = None,
offline_log_filename: Path = None,
) -> None:
super(BackgroundLogService, self).__init__(task=tas... | BackgroundLogService |
python | python-markdown__markdown | tests/test_syntax/extensions/test_smarty.py | {
"start": 5717,
"end": 6380
} | class ____(TestCase):
default_kwargs = {
'extensions': ['smarty'],
'extension_configs': {
'smarty': {
'smart_angled_quotes': True,
},
},
}
def test_angled_quotes(self):
self.assertMarkdownRenders(
'<<hello>>',
... | TestSmartyAngledQuotes |
python | ansible__ansible | lib/ansible/module_utils/_internal/_messages.py | {
"start": 1416,
"end": 1757
} | class ____(_datatag.AnsibleSerializableDataclass):
"""Information about a loaded plugin."""
resolved_name: _t.Optional[str]
"""The resolved canonical plugin name; always fully-qualified for collection plugins."""
type: _t.Optional[PluginType]
"""The plugin type."""
@_dataclasses.dataclass(**_dat... | PluginInfo |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 33709,
"end": 36385
} | class ____(Metric):
"""Calculates the number of the given confusion matrix condition.
Args:
confusion_matrix_cond: One of `metrics_utils.ConfusionMatrix` conditions.
thresholds: (Optional) Defaults to 0.5. A float value or a python list/tuple
of float threshold values in [0, 1]. A threshold is compar... | _ConfusionMatrixConditionCount |
python | allegroai__clearml | clearml/utilities/distutils_version.py | {
"start": 1163,
"end": 3330
} | class ____:
"""Abstract base class for version numbering classes. Just provides
constructor (__init__) and reproducer (__repr__), because those
seem to be the same for all version numbering classes; and route
rich comparisons to _cmp.
"""
def __init__(self, vstring: Optional[str] = None) -> No... | Version |
python | PyCQA__pyflakes | pyflakes/checker.py | {
"start": 17098,
"end": 17164
} | class ____(ModuleScope):
"""Scope for a doctest."""
| DoctestScope |
python | spack__spack | lib/spack/spack/externals.py | {
"start": 1060,
"end": 1190
} | class ____(TypedDict, total=False):
id: str
spec: str
deptypes: spack.deptypes.DepTypes
virtuals: str
| DependencyDict |
python | getsentry__sentry | src/sentry/data_secrecy/types.py | {
"start": 567,
"end": 2960
} | class ____:
cache_status: GrantCacheStatus
access_start: datetime | None = None
access_end: datetime | None = None
def __post_init__(self) -> None:
# Holds the invariant that access_end and access_start are always set when cache_status is VALID_WINDOW
if self.cache_status == GrantCacheS... | EffectiveGrantStatus |
python | spack__spack | lib/spack/spack/test/error_messages.py | {
"start": 3440,
"end": 3625
} | class ____(Package):
version("2.1")
version("2.0")
variant("v1", default=True)
requires("+v1", when="@2.1")
depends_on("t1")
""",
)
_pkgt2 = (
"t2",
"""\
| T3 |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/implementation/utils.py | {
"start": 23192,
"end": 25271
} | class ____(
NamedTuple(
"_ExecutionMetadata",
[
("run_id", Optional[str]),
("tags", Mapping[str, str]),
("root_run_id", Optional[str]),
("parent_run_id", Optional[str]),
],
)
):
def __new__(
cls,
run_id: Optional[str],
... | ExecutionMetadata |
python | redis__redis-py | tests/test_encoding.py | {
"start": 2657,
"end": 2885
} | class ____:
@pytest.fixture()
def r(self, request):
return _get_client(redis.Redis, request=request, encoding="utf-8")
def test_basic_command(self, r):
r.set("hello", "world")
| TestCommandsAreNotEncoded |
python | Textualize__textual | src/textual/widgets/_select.py | {
"start": 1067,
"end": 1203
} | class ____(Exception):
"""Raised when a [`Select`][textual.widgets.Select] has no options and `allow_blank=False`."""
| EmptySelectError |
python | huggingface__transformers | tests/models/blenderbot_small/test_tokenization_blenderbot_small.py | {
"start": 947,
"end": 3505
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "facebook/blenderbot_small-90M"
tokenizer_class = BlenderbotSmallTokenizer
test_rust_tokenizer = False
def test_full_blenderbot_small_tokenizer(self):
# Create temporary directory for vocab files
tmpdirname = temp... | BlenderbotSmallTokenizerTest |
python | catalyst-team__catalyst | tests/catalyst/callbacks/test_control_flow.py | {
"start": 476,
"end": 7104
} | class ____(Callback):
def __init__(self, order, method_to_raise: str):
super().__init__(order)
setattr(self, method_to_raise, _raise)
def test_controll_flow_callback_filter_fn_periodical_epochs():
wraped = ControlFlowCallbackWrapper(DummyCallback(), epochs=3)
mask = [i % 3 == 0 for i in ra... | RaiserCallback |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_wx.py | {
"start": 48713,
"end": 50403
} | class ____(wx.Dialog):
_instance = None # a reference to an open dialog singleton
headers = [("Action", "Shortcuts", "Description")]
widths = [100, 140, 300]
def __init__(self, parent, help_entries):
super().__init__(parent, title="Help",
style=wx.DEFAULT_DIALOG_STYLE ... | _HelpDialog |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_device_taint.py | {
"start": 383,
"end": 6700
} | 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... | V1beta1DeviceTaint |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/sensor_definition.py | {
"start": 3272,
"end": 3377
} | class ____(Enum):
RUNNING = "RUNNING"
STOPPED = "STOPPED"
@whitelist_for_serdes
| DefaultSensorStatus |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 212204,
"end": 212378
} | class ____:
def test_basic(self):
sk = np.array([0, -0.1, 0.1])
res = 250 * sk[:, np.newaxis]
assert_almost_equal(res.ravel(), 250 * sk)
| TestNewaxis |
python | ZoranPandovski__al-go-rithms | machine_learning/Neural_Networks/BasicMLP_python/mlp.py | {
"start": 3170,
"end": 9526
} | class ____(object):
def __init__(self, n_hidden_layers, n_activations, n_input, n_output):
self.n_hidden_layers = n_hidden_layers
self.n_activations = n_activations
self.n_input = n_input
self.function_activation = tanh
self.function_derivative = sigmoid_derivative
# ... | MLP |
python | Textualize__textual | src/textual/markup.py | {
"start": 1682,
"end": 2594
} | class ____(TokenizerState):
"""Tokenizes content markup."""
EXPECT = expect_markup.expect_eof()
STATE_MAP = {
"open_tag": expect_markup_tag,
"open_closing_tag": expect_markup_tag,
"end_tag": expect_markup,
"key": expect_markup_expression,
}
STATE_PUSH = {
"ro... | MarkupTokenizer |
python | pytorch__pytorch | torch/distributions/constraint_registry.py | {
"start": 3347,
"end": 10306
} | class ____:
"""
Registry to link constraints to transforms.
"""
def __init__(self):
self._registry = {}
super().__init__()
def register(self, constraint, factory=None):
"""
Registers a :class:`~torch.distributions.constraints.Constraint`
subclass in this reg... | ConstraintRegistry |
python | kubernetes-client__python | kubernetes/client/models/v1_role.py | {
"start": 383,
"end": 6576
} | 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... | V1Role |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_column03.py | {
"start": 315,
"end": 1377
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_column03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.go... | TestCompareXLSXFiles |
python | huggingface__transformers | src/transformers/models/gemma3n/configuration_gemma3n.py | {
"start": 23420,
"end": 29123
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration for a timm backbone [`TimmWrapper`]. It is used to
instantiate an timm model model according to the specified arguments, defining the model architecture.
Instantiating a configuration with the defaults will yie... | Gemma3nVisionConfig |
python | facebook__pyre-check | client/configuration/configuration.py | {
"start": 24740,
"end": 46766
} | class ____:
global_root: Path
binary: Optional[str] = None
buck_mode: Optional[platform_aware.PlatformAware[str]] = None
bxl_builder: Optional[str] = None
only_check_paths: Sequence[str] = field(default_factory=list)
dot_pyre_directory: Optional[Path] = None
enable_readonly_analysis: Option... | Configuration |
python | getsentry__sentry-python | sentry_sdk/utils.py | {
"start": 45547,
"end": 64210
} | class ____(threading.Thread):
"""Creates a Thread which runs (sleeps) for a time duration equal to
waiting_time and raises a custom ServerlessTimeout exception.
"""
def __init__(
self, waiting_time, configured_timeout, isolation_scope=None, current_scope=None
):
# type: (float, int,... | TimeoutThread |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-cohere-citation-chat/llama_index/packs/cohere_citation_chat/citations_context_chat_engine.py | {
"start": 6259,
"end": 8549
} | class ____(str, Enum):
"""Chat Engine Modes."""
SIMPLE = "simple"
"""Corresponds to `SimpleChatEngine`.
Chat with LLM, without making use of a knowledge base.
"""
CONDENSE_QUESTION = "condense_question"
"""Corresponds to `CondenseQuestionChatEngine`.
First generate a standalone quest... | ChatModeCitations |
python | plotly__plotly.py | plotly/graph_objs/parcoords/_domain.py | {
"start": 233,
"end": 5051
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "parcoords"
_path_str = "parcoords.domain"
_valid_props = {"column", "row", "x", "y"}
@property
def column(self):
"""
If there is a layout grid, use the domain for this column in
the grid for this parcoords trace .
... | Domain |
python | numba__numba | numba/tests/enum_usecases.py | {
"start": 803,
"end": 1018
} | class ____(IntEnum):
# Used for testing of hash, need to make sure -1 -> -2 to comply with CPy
one = 1
two = 2
too = 2
three = 3
negone = -1
negtwo = -2
negthree = -3
| IntEnumWithNegatives |
python | joke2k__faker | faker/providers/bank/en_IE/__init__.py | {
"start": 42,
"end": 197
} | class ____(BankProvider):
"""Implement bank provider for ``en_IE`` locale."""
bban_format = "#######################"
country_code = "IE"
| Provider |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 78109,
"end": 78411
} | class ____(TypedDict, total=False):
type: Required[Literal['with-info']]
function: Required[WithInfoWrapValidatorFunction]
field_name: str # deprecated
WrapValidatorFunction = Union[NoInfoWrapValidatorFunctionSchema, WithInfoWrapValidatorFunctionSchema]
| WithInfoWrapValidatorFunctionSchema |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 4126,
"end": 4384
} | class ____(PrefectBaseModel):
"""Model for validating concurrency lease holder information."""
model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
type: Literal["flow_run", "task_run", "deployment"]
id: UUID
| ConcurrencyLeaseHolder |
python | modin-project__modin | modin/config/envvars.py | {
"start": 23333,
"end": 23498
} | class ____(EnvironmentVariable, type=ExactStr):
"""Redis address to connect to when running in Ray cluster."""
varname = "MODIN_REDIS_ADDRESS"
| RayRedisAddress |
python | huggingface__transformers | src/transformers/models/flava/modeling_flava.py | {
"start": 64516,
"end": 65047
} | class ____(nn.Module):
def __init__(self, config, weight=None):
super().__init__()
self.config = config
self.transform = FlavaPredictionHeadTransform(config)
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
self.bias = nn.Parameter(torch.zeros(config... | FlavaMaskedPredictionHead |
python | PyCQA__pylint | tests/functional/u/unpacking/unpacking_non_sequence.py | {
"start": 1696,
"end": 2030
} | class ____:
""" does nothing """
a, b = NonSeq() # [unpacking-non-sequence]
a, b = ValueError # [unpacking-non-sequence]
a, b = None # [unpacking-non-sequence]
a, b = 1 # [unpacking-non-sequence]
a, b = nonseq # [unpacking-non-sequence]
a, b = nonseq() # [unpacking-non-sequence]
a, b = nonseq_func # [unpacking-non... | NonSeq |
python | pypa__setuptools | setuptools/_vendor/importlib_metadata/_meta.py | {
"start": 1201,
"end": 1801
} | class ____(Protocol):
"""
A minimal subset of pathlib.Path required by Distribution.
"""
def joinpath(
self, other: Union[str, os.PathLike[str]]
) -> SimplePath: ... # pragma: no cover
def __truediv__(
self, other: Union[str, os.PathLike[str]]
) -> SimplePath: ... # pragm... | SimplePath |
python | numpy__numpy | numpy/ma/core.py | {
"start": 223042,
"end": 229236
} | class ____(MaskedArray):
# the lone np.ma.masked instance
__singleton = None
@classmethod
def __has_singleton(cls):
# second case ensures `cls.__singleton` is not just a view on the
# superclass singleton
return cls.__singleton is not None and type(cls.__singleton) is cls
d... | MaskedConstant |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 197447,
"end": 198962
} | class ____(ParseElementEnhance):
"""Lookahead matching of the given parse expression.
``FollowedBy`` does *not* advance the parsing position within
the input string, it only verifies that the specified parse
expression matches at the current position. ``FollowedBy``
always returns a null token list... | FollowedBy |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_sns.py | {
"start": 3349,
"end": 5724
} | class ____:
"""The mock_aws decorator uses `moto` which does not currently support async SNS so we mock it manually."""
@pytest.fixture
def hook(self):
return SnsHook(aws_conn_id="aws_default")
@pytest.fixture
def mock_async_client(self):
mock_client = mock.AsyncMock()
mock... | TestAsyncSnsHook |
python | scrapy__scrapy | tests/CrawlerProcess/twisted_reactor_poll.py | {
"start": 58,
"end": 295
} | class ____(scrapy.Spider):
name = "poll_reactor"
process = CrawlerProcess(
settings={
"TWISTED_REACTOR": "twisted.internet.pollreactor.PollReactor",
}
)
process.crawl(PollReactorSpider)
process.start()
| PollReactorSpider |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/text_to_speech.py | {
"start": 1436,
"end": 5239
} | class ____(GoogleBaseHook):
"""
Hook for Google Cloud Text to Speech API.
All the methods in the hook where project_id is used must be called with
keyword arguments rather than positional.
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param impersonation_chain: O... | CloudTextToSpeechHook |
python | automl__auto-sklearn | autosklearn/evaluation/splitter.py | {
"start": 385,
"end": 4364
} | class ____(StratifiedShuffleSplit):
"""Splitter that deals with classes with too few samples"""
def _iter_indices(self, X, y, groups=None): # type: ignore
n_samples = _num_samples(X)
y = check_array(y, ensure_2d=False, dtype=None)
n_train, n_test = _validate_shuffle_split(
... | CustomStratifiedShuffleSplit |
python | astropy__astropy | astropy/table/meta.py | {
"start": 12238,
"end": 13553
} | class ____(Exception):
pass
def get_header_from_yaml(lines):
"""
Get a header dict from input ``lines`` which should be valid YAML. This
input will typically be created by get_yaml_from_header. The output is a
dictionary which describes all the table and column meta.
The get_cols() method i... | YamlParseError |
python | jazzband__django-oauth-toolkit | oauth2_provider/contrib/rest_framework/permissions.py | {
"start": 3174,
"end": 4143
} | class ____(BasePermission):
"""
The user is authenticated using some backend or the token has the right scope
This only returns True if the user is authenticated, but not using a token
or using a token, and the token has the correct scope.
This is useful when combined with the DjangoModelPermission... | IsAuthenticatedOrTokenHasScope |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-asana/source_asana/components.py | {
"start": 532,
"end": 3983
} | class ____(HttpRequester):
request_parameters: Optional[Union[str, Mapping[str, str]]] = None
def __post_init__(self, parameters: Mapping[str, Any]) -> None:
super().__post_init__(parameters)
self.request_parameters = self.request_parameters or {}
self._request_params_interpolator = Int... | AsanaHttpRequester |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/declared_attr_one.py | {
"start": 710,
"end": 1162
} | class ____(Base):
__tablename__ = "employee"
id = mapped_column(Integer, primary_key=True)
name = mapped_column(String(50))
type = mapped_column(String(20))
__mapper_args__ = {
"polymorphic_on": type,
"polymorphic_identity": "employee",
}
__table_args__ = (
Index("m... | Employee |
python | spack__spack | lib/spack/spack/patch.py | {
"start": 12523,
"end": 18369
} | class ____:
"""Index of patches used in a repository, by sha256 hash.
This allows us to look up patches without loading all packages. It's
also needed to properly implement dependency patching, as need a way
to look up patches that come from packages not in the Spec sub-DAG.
The patch index is st... | PatchCache |
python | mahmoud__boltons | boltons/funcutils.py | {
"start": 36040,
"end": 36840
} | class ____(ValueError):
pass
def _indent(text, margin, newline='\n', key=bool):
"based on boltons.strutils.indent"
indented_lines = [(margin + line if key(line) else line)
for line in text.splitlines()]
return newline.join(indented_lines)
def noop(*args, **kwargs):
"""
... | ExistingArgument |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py | {
"start": 1061,
"end": 1203
} | class ____(Exception):
"""Raised if the backend is invalid"""
def __init__(self, message):
self.message = message
| BackendInvalid |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 830597,
"end": 831347
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for PackageVersion."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("PackageVersionEdge"), graphql_name="edges")
"""A list of edges."""
... | PackageVersionConnection |
python | kamyu104__LeetCode-Solutions | Python/fixed-point.py | {
"start": 32,
"end": 414
} | class ____(object):
def fixedPoint(self, A):
"""
:type A: List[int]
:rtype: int
"""
left, right = 0, len(A)-1
while left <= right:
mid = left + (right-left)//2
if A[mid] >= mid:
right = mid-1
else:
le... | Solution |
python | RaRe-Technologies__gensim | gensim/models/callbacks.py | {
"start": 9093,
"end": 10832
} | class ____(Metric):
"""Metric class for perplexity evaluation."""
def __init__(self, corpus=None, logger=None, viz_env=None, title=None):
"""
Parameters
----------
corpus : {iterable of list of (int, float), scipy.sparse.csc}, optional
Stream of document vectors or s... | PerplexityMetric |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 1077,
"end": 4860
} | class ____(ASTBase):
def __init__(self, name: str) -> None:
if not isinstance(name, str) or len(name) == 0:
raise AssertionError
self.name = sys.intern(name)
self.is_anonymous = name[0] == '@'
# ASTBaseBase already implements this method,
# but specialising it here impro... | ASTIdentifier |
python | huggingface__transformers | src/transformers/models/omdet_turbo/modeling_omdet_turbo.py | {
"start": 51209,
"end": 65656
} | class ____(OmDetTurboPreTrainedModel):
def __init__(self, config: OmDetTurboConfig):
self.config = config
super().__init__(config)
self.gradient_checkpointing = False
hidden_dim = config.decoder_hidden_dim
self.num_queries = config.num_queries
self.class_distance_typ... | OmDetTurboDecoder |
python | walkccc__LeetCode | solutions/35. Search Insert Position/35.py | {
"start": 0,
"end": 278
} | class ____:
def searchInsert(self, nums: list[int], target: int) -> int:
l = 0
r = len(nums)
while l < r:
m = (l + r) // 2
if nums[m] == target:
return m
if nums[m] < target:
l = m + 1
else:
r = m
return l
| Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/strategies.py | {
"start": 19791,
"end": 21275
} | class ____(_AbstractRelationshipLoader):
"""Provide loading behavior for a :class:`.Relationship`
with "lazy=None".
"""
__slots__ = ()
@util.deprecated(
"2.1",
"The ``noload`` loader strategy is deprecated and will be removed "
"in a future release. This option "
... | _NoLoader |
python | PyCQA__pylint | tests/functional/f/function_redefined.py | {
"start": 219,
"end": 455
} | class ____:
"""docstring"""
def __init__(self):
pass
def method1(self):
"""docstring"""
def method2(self):
"""docstring"""
def method2(self): # [function-redefined]
"""docstring"""
| AAAA |
python | django__django | tests/messages_tests/utils.py | {
"start": 46,
"end": 341
} | class ____:
"""Dummy message-store to test the API methods."""
def __init__(self):
self.store = []
def add(self, level, message, extra_tags=""):
self.store.append(Message(level, message, extra_tags))
def __iter__(self):
return iter(self.store)
| DummyStorage |
python | sympy__sympy | sympy/physics/biomechanics/curve.py | {
"start": 17874,
"end": 25485
} | class ____(CharacteristicCurveFunction):
r"""Passive muscle fiber force-length curve based on De Groote et al., 2016
[1]_.
Explanation
===========
The function is defined by the equation:
$fl^M_{pas} = \frac{\frac{\exp{c_1 \left(\tilde{l^M} - 1\right)}}{c_0} - 1}{\exp{c_1} - 1}$
with con... | FiberForceLengthPassiveDeGroote2016 |
python | getsentry__sentry | src/sentry/preprod/size_analysis/download.py | {
"start": 897,
"end": 1809
} | class ____(SizeAnalysisError):
def __init__(self, message: str = "Size analysis not found"):
super().__init__(message, 404)
def get_size_analysis_file_response(size_metrics: PreprodArtifactSizeMetrics) -> FileResponse:
try:
file_obj = File.objects.get(id=size_metrics.analysis_file_id)
exce... | SizeAnalysisNotFoundError |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_container.py | {
"start": 14220,
"end": 14474
} | class ____:
def test_valid(self) -> None:
prop = bcpc.NonEmpty(bcpc.List(Int))
assert prop.is_valid([1])
def test_invalid(self) -> None:
prop = bcpc.NonEmpty(bcpc.List(Int))
assert not prop.is_valid([])
| Test_NonEmpty |
python | python-openxml__python-docx | src/docx/oxml/shape.py | {
"start": 1570,
"end": 1879
} | class ____(BaseOxmlElement):
"""``<a:graphicData>`` element, container for the XML of a DrawingML object."""
pic: CT_Picture = ZeroOrOne("pic:pic") # pyright: ignore[reportAssignmentType]
uri: str = RequiredAttribute("uri", XsdToken) # pyright: ignore[reportAssignmentType]
| CT_GraphicalObjectData |
python | pytorch__pytorch | torch/distributions/transforms.py | {
"start": 12879,
"end": 15560
} | class ____(Transform):
"""
Wrapper around another transform to treat
``reinterpreted_batch_ndims``-many extra of the right most dimensions as
dependent. This has no effect on the forward or backward transforms, but
does sum out ``reinterpreted_batch_ndims``-many of the rightmost dimensions
in :m... | IndependentTransform |
python | streamlit__streamlit | lib/tests/streamlit/web/server/server_test.py | {
"start": 1725,
"end": 14977
} | class ____(ServerTestCase):
def setUp(self) -> None:
self.original_ws_compression = config.get_option(
"server.enableWebsocketCompression"
)
return super().setUp()
def tearDown(self):
config.set_option(
"server.enableWebsocketCompression", self.original_w... | ServerTest |
python | etianen__django-reversion | tests/test_app/tests/test_models.py | {
"start": 618,
"end": 1193
} | class ____(TestModelMixin, TestBase):
databases = {"default", "mysql", "postgres"}
def testGetForModelDb(self):
with reversion.create_revision(using="postgres"):
obj = TestModel.objects.create()
self.assertEqual(Version.objects.using("postgres").get_for_model(obj.__class__).count(),... | GetForModelDbTest |
python | huggingface__transformers | src/transformers/models/siglip/image_processing_siglip.py | {
"start": 1378,
"end": 11831
} | class ____(BaseImageProcessor):
r"""
Constructs a SigLIP image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
`do_resize` in the `preprocess` method.
... | SiglipImageProcessor |
python | streamlit__streamlit | lib/streamlit/elements/arrow.py | {
"start": 9726,
"end": 45597
} | class ____:
@overload
def dataframe(
self,
data: Data = None,
width: Width = "stretch",
height: Height | Literal["auto"] = "auto",
*,
use_container_width: bool | None = None,
hide_index: bool | None = None,
column_order: Iterable[str] | None = None... | ArrowMixin |
python | pyqtgraph__pyqtgraph | pyqtgraph/Qt/OpenGLHelpers.py | {
"start": 2252,
"end": 3648
} | class ____(QtOpenGLWidgets.QOpenGLWidget):
def __init__(self):
super().__init__()
self._programs = {}
self._functions = None
def initializeGL(self):
# initializeGL gets called again when the context changes.
# so we start off by destroying old resources.
for prog... | GraphicsViewGLWidget |
python | scipy__scipy | benchmarks/benchmarks/stats.py | {
"start": 15757,
"end": 16549
} | class ____(Benchmark):
param_names = ['points']
params = [10, 6400]
def setup(self, points):
self.length = points
rng = np.random.default_rng(12345678)
n = 2000
m1 = rng.normal(size=n)
m2 = rng.normal(scale=0.5, size=n)
xmin = m1.min()
xmax = m1.max(... | GaussianKDE |
python | Textualize__textual | src/textual/widgets/_footer.py | {
"start": 3755,
"end": 11171
} | class ____(ScrollableContainer, can_focus=False, can_focus_children=False):
ALLOW_SELECT = False
DEFAULT_CSS = """
Footer {
layout: horizontal;
color: $footer-foreground;
background: $footer-background;
dock: bottom;
height: 1;
scrollbar-size: 0 0;
... | Footer |
python | keras-team__keras | guides/custom_train_step_in_tensorflow.py | {
"start": 9470,
"end": 12117
} | class ____(keras.Model):
def test_step(self, data):
# Unpack the data
x, y = data
# Compute predictions
y_pred = self(x, training=False)
# Updates the metrics tracking the loss
loss = self.compute_loss(y=y, y_pred=y_pred)
# Update the metrics.
for metr... | CustomModel |
python | tiangolo__fastapi | tests/test_default_response_class_router.py | {
"start": 159,
"end": 5117
} | class ____(JSONResponse):
media_type = "application/x-override"
app = FastAPI()
router_a = APIRouter()
router_a_a = APIRouter()
router_a_b_override = APIRouter() # Overrides default class
router_b_override = APIRouter() # Overrides default class
router_b_a = APIRouter()
router_b_a_c_override = APIRouter() # Ov... | OverrideResponse |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/runtime_wrappers.py | {
"start": 3292,
"end": 3924
} | class ____(CompilerWrapper):
indices_of_inps_to_detach: list[int]
trace_joint: bool
disable_amp: bool
def post_compile(
self,
compiled_fn,
aot_config: AOTConfig,
*,
runtime_metadata: ViewAndMutationMeta,
):
return _create_runtime_wrapper(
... | RuntimeWrapper |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py | {
"start": 8405,
"end": 9698
} | class ____:
def find_events(self, header: Sequence[str]) -> List[str]:
return [event.replace(" (Unique users)", "").strip() for event in header if " (Unique users)" in event]
def get_records(self, row: Dict, events: List[str]) -> List[Dict]:
identifiers = {
"Date": "date",
... | EventsMixin |
python | python-poetry__poetry | src/poetry/mixology/incompatibility.py | {
"start": 709,
"end": 15400
} | class ____:
def __init__(self, terms: list[Term], cause: IncompatibilityCauseError) -> None:
# Remove the root package from generated incompatibilities, since it will
# always be satisfied. This makes error reporting clearer, and may also
# make solving more efficient.
if (
... | Incompatibility |
python | google__jax | tests/hijax_test.py | {
"start": 7143,
"end": 19815
} | class ____(jtu.JaxTestCase):
def test_basic_register(self):
# older test that defines a slightly different QArray internally
@dataclass(frozen=True)
class QArray:
arr: jax.Array
scale: jax.Array
axis: int
@dataclass(frozen=True)
class QArrayTy(HiType):
shape: tuple[int, in... | HijaxTest |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_supervisor.py | {
"start": 101544,
"end": 108788
} | class ____:
"""Test retry logic for exit codes (signals and non-signal failures) in ActivitySubprocess."""
@pytest.mark.parametrize(
"signal",
[
signal.SIGTERM,
signal.SIGKILL,
signal.SIGABRT,
signal.SIGSEGV,
],
)
def test_signals_... | TestSignalRetryLogic |
python | django__django | tests/generic_views/test_base.py | {
"start": 754,
"end": 879
} | class ____(SimpleView):
parameter = {}
def decorator(view):
view.is_decorated = True
return view
| CustomizableView |
python | milvus-io__pymilvus | tests/test_bulk_writer_validators.py | {
"start": 9975,
"end": 12987
} | class ____:
def test_valid_dict(self):
"""Test valid dict format"""
data = {2: 13.23, 45: 0.54}
result = sparse_vector_validator(data)
assert result == data
def test_valid_indices_values_format(self):
"""Test valid indices/values format"""
data = {"indices": [1, ... | TestSparseVectorValidator |
python | fastai__fastai | fastai/text/models/awdlstm.py | {
"start": 1339,
"end": 3148
} | class ____(Module):
"A module that wraps another layer in which some weights will be replaced by 0 during training."
def __init__(self,
module:nn.Module, # Wrapped module
weight_p:float, # Weight dropout probability
layer_names:str|MutableSequence='weight_hh_l0' # Name(s) of the param... | WeightDropout |
python | falconry__falcon | falcon/testing/test_case.py | {
"start": 1064,
"end": 2932
} | class ____(unittest.TestCase, TestClient):
"""Extends :mod:`unittest` to support WSGI/ASGI functional testing.
Note:
If available, uses :mod:`testtools` in lieu of
:mod:`unittest`.
This base class provides some extra plumbing for unittest-style
test cases, to help simulate WSGI or ASGI... | TestCase |
python | django__django | tests/queries/models.py | {
"start": 5648,
"end": 5895
} | class ____(models.Model):
person = models.OneToOneField(Member, models.CASCADE, primary_key=True)
parent = models.ForeignKey(Member, models.CASCADE, related_name="children")
# Custom primary keys interfered with ordering in the past.
| Child |
python | apache__airflow | providers/opsgenie/src/airflow/providers/opsgenie/operators/opsgenie.py | {
"start": 7936,
"end": 9855
} | class ____(BaseOperator):
"""
This operator allows you to delete alerts in Opsgenie.
Accepts a connection that has an Opsgenie API key as the connection's password.
This operator sets the domain to conn_id.host, and if not set will default
to ``https://api.opsgenie.com``.
Each Opsgenie API key... | OpsgenieDeleteAlertOperator |
python | google__pytype | pytype/tests/test_pattern_matching.py | {
"start": 22513,
"end": 23824
} | class ____(test_base.BaseTest):
"""Test various pattern matching features."""
def test_or_pattern(self):
ty = self.Infer("""
def f(x: tuple[int, str]):
match x:
case [a, 'x'] | [2, a]:
return a
""")
self.assertTypesMatchPytd(
ty,
"""
def f(x: tu... | MatchFeaturesTest |
python | optuna__optuna | optuna/storages/_rdb/alembic/versions/v3.0.0.b.py | {
"start": 816,
"end": 924
} | class ____(enum.Enum):
RUNNING = 0
COMPLETE = 1
PRUNED = 2
FAIL = 3
WAITING = 4
| TrialState |
python | mamba-org__mamba | micromamba/test-server/reposerver.py | {
"start": 9817,
"end": 16451
} | class ____(SimpleHTTPRequestHandler):
url_pattern = re.compile(r"^/(?:t/[^/]+/)?([^/]+)")
def do_GET(self) -> None:
# First extract channel name
channel_name = None
if tuple(channels.keys()) != (None,):
match = self.url_pattern.match(self.path)
if match:
... | ChannelHandler |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 96374,
"end": 99325
} | class ____(IRNode):
data: IRNode
@cache_on_self_and_args("BaseView")
def get_free_symbol_uses(self, unbacked_only: bool = False) -> OrderedSet[Symbol]:
return self.data.get_free_symbol_uses(unbacked_only)
def make_reindexer(self) -> Callable[[Sequence[Expr]], Sequence[Expr]]:
raise Not... | BaseView |
python | mkdocs__mkdocs | hatch_build.py | {
"start": 86,
"end": 455
} | class ____(BuildHookInterface):
def initialize(self, version, build_data):
from babel.messages.frontend import compile_catalog
for theme in 'mkdocs', 'readthedocs':
cmd = compile_catalog()
cmd.directory = os.path.join('mkdocs', 'themes', theme, 'locales')
cmd.fin... | CustomBuildHook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.