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 | getsentry__sentry | tests/sentry/services/eventstore/test_base.py | {
"start": 334,
"end": 1520
} | class ____(TestCase):
def setUp(self) -> None:
self.eventstorage = EventStorage()
def test_minimal_columns(self) -> None:
assert len(self.eventstorage.minimal_columns[Dataset.Events]) == 5
assert len(self.eventstorage.minimal_columns[Dataset.Transactions]) == 4
def test_bind_nodes(... | EventStorageTest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/sqs.py | {
"start": 1731,
"end": 10672
} | class ____(AwsBaseSensor[SqsHook]):
"""
Get messages from an Amazon SQS queue and then delete the messages from the queue.
If deletion of messages fails, an AirflowException is thrown. Otherwise, the messages
are pushed through XCom with the key ``messages``.
By default,the sensor performs one and... | SqsSensor |
python | getsentry__sentry | tests/sentry/release_health/test_tasks.py | {
"start": 991,
"end": 22447
} | class ____(TestCase, BaseMetricsTestCase):
__test__ = Abstract(__module__, __qualname__)
backend_class: type[BaseReleaseMonitorBackend]
def setUp(self) -> None:
super().setUp()
backend = self.backend_class()
self.backend = mock.patch("sentry.release_health.tasks.release_monitor", b... | BaseTestReleaseMonitor |
python | getsentry__sentry | src/sentry/api/endpoints/organization_search_details.py | {
"start": 1501,
"end": 4224
} | class ____(OrganizationEndpoint):
owner = ApiOwner.UNOWNED
publish_status = {
"DELETE": ApiPublishStatus.PRIVATE,
"PUT": ApiPublishStatus.PRIVATE,
}
permission_classes = (OrganizationSearchEditPermission,)
def convert_args(self, request: Request, organization_id_or_slug, search_id, ... | OrganizationSearchDetailsEndpoint |
python | huggingface__transformers | src/transformers/models/detr/image_processing_detr.py | {
"start": 27942,
"end": 76914
} | class ____(BaseImageProcessor):
r"""
Constructs a Detr image processor.
Args:
format (`str`, *optional*, defaults to `"coco_detection"`):
Data format of the annotations. One of "coco_detection" or "coco_panoptic".
do_resize (`bool`, *optional*, defaults to `True`):
C... | DetrImageProcessor |
python | joke2k__faker | faker/providers/color/es/__init__.py | {
"start": 98,
"end": 6166
} | class ____(ColorProvider):
"""Implement color provider for ``es`` locale."""
all_colors = OrderedDict(
(
("Agua marina medio", "#66CDAA"),
("Agua-marina", "#7FFFD4"),
("Almendra blanqueado", "#FFEBCD"),
("Amarillo", "#FFFF00"),
("Amarillo clar... | Provider |
python | huggingface__transformers | tests/models/gpt_bigcode/test_modeling_gpt_bigcode.py | {
"start": 20190,
"end": 20366
} | class ____(GPTBigCodeModelTest):
# `parameterized_class` breaks with mixins, so we use inheritance instead
multi_query = False
@slow
@require_torch
| GPTBigCodeMHAModelTest |
python | huggingface__transformers | tests/models/mllama/test_modeling_mllama.py | {
"start": 4492,
"end": 9591
} | class ____:
def __init__(
self,
parent,
ignore_index=-100,
image_token_index=4,
seq_length=7,
is_training=True,
text_config={
"model_type": "mllama",
"vocab_size": 99,
"hidden_size": 32,
"num_hidden_layers": 2,
... | MllamaVisionText2TextModelTester |
python | zarr-developers__zarr-python | src/zarr/codecs/transpose.py | {
"start": 922,
"end": 4079
} | class ____(ArrayArrayCodec):
"""Transpose codec"""
is_fixed_size = True
order: tuple[int, ...]
def __init__(self, *, order: Iterable[int]) -> None:
order_parsed = parse_transpose_order(order)
object.__setattr__(self, "order", order_parsed)
@classmethod
def from_dict(cls, dat... | TransposeCodec |
python | sympy__sympy | sympy/assumptions/predicates/ntheory.py | {
"start": 88,
"end": 931
} | class ____(Predicate):
"""
Prime number predicate.
Explanation
===========
``ask(Q.prime(x))`` is true iff ``x`` is a natural number greater
than 1 that has no positive divisors other than ``1`` and the
number itself.
Examples
========
>>> from sympy import Q, ask
>>> ask... | PrimePredicate |
python | mahmoud__glom | glom/core.py | {
"start": 64821,
"end": 65059
} | class ____(_AbstractIterableBase):
__metaclass__ = ABCMeta
@classmethod
def __subclasshook__(cls, C):
if C in (str, bytes):
return False
return callable(getattr(C, "__iter__", None))
| _AbstractIterable |
python | bokeh__bokeh | src/bokeh/models/tools.py | {
"start": 8522,
"end": 8780
} | class ____(GestureTool):
''' A base class for tools that respond to drag events.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@abstract
| Drag |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/mixins.py | {
"start": 7860,
"end": 8561
} | class ____(OAuthLibMixin):
"""
Helper mixin that implements OAuth2 protection on request dispatch,
specially useful for Django Generic Views
"""
def dispatch(self, request, *args, **kwargs):
# let preflight OPTIONS requests pass
if request.method.upper() == "OPTIONS":
re... | ProtectedResourceMixin |
python | eventlet__eventlet | tests/websocket_new_test.py | {
"start": 8268,
"end": 22838
} | class ____(tests.wsgi_test._TestBase):
TEST_TIMEOUT = 5
def set_site(self):
self.site = wsapp
def setUp(self):
super().setUp()
self.connect = '\r\n'.join([
"GET /echo HTTP/1.1",
"Upgrade: websocket",
"Connection: upgrade",
"Host: %s:%... | TestWebSocketWithCompression |
python | huggingface__transformers | tests/models/autoformer/test_modeling_autoformer.py | {
"start": 1404,
"end": 8081
} | class ____:
def __init__(
self,
parent,
d_model=16,
batch_size=13,
prediction_length=7,
context_length=14,
label_length=10,
cardinality=19,
embedding_dimension=5,
num_time_features=4,
is_training=True,
hidden_size=16,
... | AutoformerModelTester |
python | google__pytype | pytype/tests/test_base_test.py | {
"start": 154,
"end": 5490
} | class ____(test_base.BaseTest):
def test_error_comments(self):
err = self.CheckWithErrors("""
a = 10 # a random comment
b = "hello" + 3 # unsupported-operands[.mark]
c = (10).foo # attribute-error
d = int(int) # wrong-arg-types[.another_mark]
""")
self.assertEqual(
{ma... | ErrorLogTest |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_pool_test.py | {
"start": 40330,
"end": 41210
} | class ____(object):
def __init__(self, name, package, messages, dependencies=None,
public_dependencies=None):
self.name = name
self.package = package
self.messages = messages
self.dependencies = dependencies or []
self.public_dependencies = public_dependencies or []
def CheckFil... | ProtoFile |
python | django__django | django/views/generic/dates.py | {
"start": 15013,
"end": 15193
} | class ____(MultipleObjectTemplateResponseMixin, BaseYearArchiveView):
"""List of objects published in a given year."""
template_name_suffix = "_archive_year"
| YearArchiveView |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/tridiagonal_matmul_op_test.py | {
"start": 1561,
"end": 11554
} | class ____(test.TestCase):
def _testAllFormats(self,
superdiag,
maindiag,
subdiag,
rhs,
expected,
dtype=dtypes.float64):
superdiag_extended = np.pad(superdiag, [0, 1], 'constant')
... | TridiagonalMulOpTest |
python | walkccc__LeetCode | solutions/3452. Sum of Good Numbers/3452.py | {
"start": 0,
"end": 240
} | class ____:
def sumOfGoodNumbers(self, nums: list[int], k: int) -> int:
return sum(num for i, num in enumerate(nums)
if (i - k < 0 or num > nums[i - k])
and (i + k >= len(nums) or num > nums[i + k]))
| Solution |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_v2.py | {
"start": 123160,
"end": 127179
} | class ____(
CategoricalColumn,
fc_old._CategoricalColumn, # pylint: disable=protected-access
collections.namedtuple('HashedCategoricalColumn',
('key', 'hash_bucket_size', 'dtype'))):
"""see `categorical_column_with_hash_bucket`."""
@property
def _is_v2_column(self):
re... | HashedCategoricalColumn |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 1973,
"end": 2108
} | class ____(ShowFieldType, PolymorphicModel):
polymorphic_showfield_deferred = True
field_b = models.CharField(max_length=30)
| Base |
python | django__django | django/contrib/gis/db/models/lookups.py | {
"start": 4612,
"end": 4825
} | class ____(GISLookup):
"""
The 'left' operator returns true if A's bounding box is strictly to the
left of B's bounding box.
"""
lookup_name = "left"
@BaseSpatialField.register_lookup
| LeftLookup |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/self1.py | {
"start": 2547,
"end": 2571
} | class ____(D[Self]): ...
| E |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 52315,
"end": 53567
} | class ____:
@pytest.mark.parametrize('dt', ['f', 'd', 'g'])
def test_log2_values(self, dt):
x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
xf = np.array(x, dtype=dt)
yf = np.array(y, dtype=dt)
assert_almost_equal(np.log2(xf), yf)
... | TestLog2 |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 25405,
"end": 26983
} | class ____(RegexLexer):
"""
Generic `cheetah templates`_ lexer. Code that isn't Cheetah
markup is yielded as `Token.Other`. This also works for
`spitfire templates`_ which use the same syntax.
.. _cheetah templates: http://www.cheetahtemplate.org/
.. _spitfire templates: http://code.google.com... | CheetahLexer |
python | networkx__networkx | networkx/algorithms/tree/tests/test_coding.py | {
"start": 196,
"end": 2458
} | class ____:
"""Unit tests for the Prüfer sequence encoding and decoding
functions.
"""
def test_nontree(self):
with pytest.raises(nx.NotATree):
G = nx.cycle_graph(3)
nx.to_prufer_sequence(G)
def test_null_graph(self):
with pytest.raises(nx.NetworkXPointless... | TestPruferSequence |
python | apache__thrift | test/py/SerializationTest.py | {
"start": 13816,
"end": 15239
} | class ____(unittest.TestCase):
def testSplit(self):
"""Test FramedTransport and BinaryProtocolAccelerated
Tests that TBinaryProtocolAccelerated and TFramedTransport
play nicely together when a read spans a frame"""
protocol_factory = TBinaryProtocol.TBinaryProtocolAcceleratedFactor... | AcceleratedFramedTest |
python | Lightning-AI__lightning | src/lightning/pytorch/trainer/connectors/accelerator_connector.py | {
"start": 2435,
"end": 28769
} | class ____:
def __init__(
self,
devices: Union[list[int], str, int] = "auto",
num_nodes: int = 1,
accelerator: Union[str, Accelerator] = "auto",
strategy: Union[str, Strategy] = "auto",
plugins: Optional[Union[_PLUGIN_INPUT, Iterable[_PLUGIN_INPUT]]] = None,
p... | _AcceleratorConnector |
python | django__django | tests/auth_tests/test_remote_user.py | {
"start": 17501,
"end": 19286
} | class ____(RemoteUserTest):
"""
Tests a custom RemoteUserBackend subclass that overrides the clean_username
and configure_user methods.
"""
backend = "auth_tests.test_remote_user.CustomRemoteUserBackend"
# REMOTE_USER strings with email addresses for the custom backend to
# clean.
known... | RemoteUserCustomTest |
python | apache__airflow | providers/apache/kafka/tests/unit/apache/kafka/queues/test_kafka.py | {
"start": 1080,
"end": 4949
} | class ____:
"""Tests for KafkaMessageQueueProvider."""
def setup_method(self):
"""Set up the test environment."""
from airflow.providers.apache.kafka.queues.kafka import KafkaMessageQueueProvider
self.provider = KafkaMessageQueueProvider()
def test_queue_create(self):
"""T... | TestKafkaMessageQueueProvider |
python | getsentry__sentry | src/sentry/issues/endpoints/organization_release_previous_commits.py | {
"start": 807,
"end": 3855
} | class ____(OrganizationReleasesBaseEndpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.ISSUES
rate_limits = RateLimitConfig(group="CLI")
def get(self, request: Request, organization: Organization, version: str) -> Response:
"""
Retrieve an Organ... | OrganizationReleasePreviousCommitsEndpoint |
python | huggingface__transformers | tests/models/whisper/test_modeling_whisper.py | {
"start": 235057,
"end": 238989
} | class ____:
def __init__(
self,
parent,
batch_size=3, # need batch_size != num_hidden layers
seq_length=60,
is_training=True,
use_labels=True,
hidden_size=16,
num_hidden_layers=2,
num_attention_heads=4,
input_channels=1,
hidden... | WhisperEncoderModelTester |
python | numba__numba | numba/tests/test_datamodel.py | {
"start": 5260,
"end": 5667
} | class ____(unittest.TestCase):
def test_issue2921(self):
import numpy as np
from numba import njit
@njit
def copy(a, b):
for i in range(a.shape[0]):
a[i] = b[i]
b = np.arange(5, dtype=np.uint8).view(np.bool_)
a = np.zeros_like(b)
... | TestMisc |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/base.py | {
"start": 1814,
"end": 2150
} | class ____(Generic[T]):
"""
Generic column-statistic.
Parameters
----------
value
Statistics value. Value will be None
if the statistics is unknown.
exact
Whether the statistics is known exactly.
"""
value: T | None = None
exact: bool = False
@dataclasses.... | ColumnStat |
python | django-extensions__django-extensions | django_extensions/collision_resolvers.py | {
"start": 3900,
"end": 4399
} | class ____(PathBasedCR):
"""
Collision resolver which transform full model name to alias by changing dots to underscores.
He also removes 'models' part of alias, because all models are in models.py files.
Model from last application in alphabetical order is selected.
""" # noqa: E501
def trans... | FullPathCR |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/generic.py | {
"start": 879,
"end": 1132
} | class ____(ClientProtectedResourceMixin, View):
"""View for protecting a resource with client-credentials method.
This involves allowing access tokens, Basic Auth and plain credentials in request body.
"""
pass
| ClientProtectedResourceView |
python | joke2k__faker | faker/providers/ssn/en_IN/__init__.py | {
"start": 77,
"end": 731
} | class ____(BaseProvider):
"""
Faker provider for Indian Identifiers
"""
aadhaar_id_formats = ("%##########",)
def aadhaar_id(self) -> str:
"""
Aadhaar is a 12 digit person identifier generated for residents of
India.
Details: https://en.wikipedia.org/wiki/Aadhaar
... | Provider |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/utils.py | {
"start": 8497,
"end": 9638
} | class ____(ast.NodeVisitor):
"""Get the nonlocal variables accessed of a function."""
def __init__(self) -> None:
"""Create a FunctionNonLocals visitor."""
self.nonlocals: set[str] = set()
@override
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
"""Visit a function... | FunctionNonLocals |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py | {
"start": 2947,
"end": 3346
} | class ____(Groups, GeneratorMixin):
"""
https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-groups/#api-rest-api-3-group-post
"""
def path(self, **kwargs) -> str:
return "group"
def generate(self):
for index in range(20):
payload = json.dumps({"name": ... | GroupsGenerator |
python | jazzband__django-waffle | waffle/tests/test_waffle.py | {
"start": 30938,
"end": 31350
} | class ____(TransactionTestMixin, TransactionTestCase):
def create_toggle(self):
return waffle.get_waffle_sample_model().objects.create(
name="transaction-sample-name", percent=0
)
def flip_toggle(self, sample):
sample.percent = 100
sample.save()
def toggle_is_ac... | SampleTransactionTests |
python | google__pytype | pytype/load_pytd.py | {
"start": 13086,
"end": 31340
} | class ____:
"""A cache for loaded PyTD files.
Typically, you'll have one instance of this class, per module.
Attributes:
options: A config.Options object.
builtins: The builtins ast.
typing: The typing ast.
"""
def __init__(self, options, modules=None, missing_modules=()):
self.options = op... | Loader |
python | pallets__quart | src/quart/utils.py | {
"start": 706,
"end": 5858
} | class ____(Exception):
pass
def file_path_to_path(*paths: FilePath) -> Path:
# Flask supports bytes paths
safe_paths: list[str | os.PathLike] = []
for path in paths:
if isinstance(path, bytes):
safe_paths.append(path.decode())
else:
safe_paths.append(path)
r... | MustReloadError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/psycopg2.py | {
"start": 20781,
"end": 20869
} | class ____(_Psycopg2Range):
_psycopg2_range_cls = "NumericRange"
| _Psycopg2NumericRange |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/cx_oracle.py | {
"start": 22470,
"end": 22543
} | class ____(_OracleNumericCommon, sqltypes.Numeric):
pass
| _OracleNumeric |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_managed_kafka.py | {
"start": 12470,
"end": 13774
} | class ____:
@mock.patch(MANAGED_KAFKA_PATH.format("types.Topic.to_dict"))
@mock.patch(MANAGED_KAFKA_PATH.format("ManagedKafkaHook"))
def test_execute(self, mock_hook, to_dict_mock):
op = ManagedKafkaUpdateTopicOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
im... | TestManagedKafkaUpdateTopicOperator |
python | mwaskom__seaborn | seaborn/relational.py | {
"start": 7023,
"end": 7244
} | class ____(VectorPlotter):
wide_structure = {
"x": "@index", "y": "@values", "hue": "@columns", "style": "@columns",
}
# TODO where best to define default parameters?
sort = True
| _RelationalPlotter |
python | getsentry__sentry | src/sentry/grouping/parameterization.py | {
"start": 9148,
"end": 9513
} | class ____:
"""
Represents a callable that can be used to modify a string, which can give
us more flexibility than just using regex.
"""
name: str # name of the pattern (also used as group name in combined regex)
apply: Callable[[str], tuple[str, int]] # function for modifying the input strin... | ParameterizationCallable |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 198198,
"end": 200588
} | class ____(Operation):
def __init__(self, axes=2, *, name=None):
super().__init__(name=name)
self.axes = axes
def call(self, x1, x2):
return backend.numpy.tensordot(x1, x2, axes=self.axes)
def compute_output_spec(self, x1, x2):
x1_shape = list(getattr(x1, "shape", []))
... | Tensordot |
python | doocs__leetcode | solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.py | {
"start": 0,
"end": 335
} | class ____:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
ans = [""]
for i in digits:
s = d[int(i) - 2]
ans = [a + b for a in ans for b in s]
... | Solution |
python | astropy__astropy | astropy/io/votable/tree.py | {
"start": 19800,
"end": 25290
} | class ____(SimpleElementWithContent, _IDProperty, _XtypeProperty, _UtypeProperty):
"""
INFO_ elements: arbitrary key-value pairs for extensions to the standard.
The keyword arguments correspond to setting members of the same
name, documented below.
"""
_element_name = "INFO"
_attr_list_11 ... | Info |
python | sympy__sympy | sympy/functions/special/bessel.py | {
"start": 67470,
"end": 68611
} | class ____(DefinedFunction):
"""
Helper function to make the $\\mathrm{besselk}(nu, z)$
function tractable for the Gruntz algorithm.
"""
def _eval_aseries(self, n, args0, x, logx):
from sympy.functions.combinatorial.factorials import RisingFactorial
from sympy.series.order import O... | _besselk |
python | getsentry__sentry | src/sentry/issues/endpoints/group_reprocessing.py | {
"start": 338,
"end": 1684
} | class ____(GroupEndpoint):
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
def post(self, request: Request, group) -> Response:
"""
Reprocess a group
`````````````````
This endpoint triggers reprocessing for all events in a group.
:pparam string issu... | GroupReprocessingEndpoint |
python | numba__numba | numba/tests/test_llvm_version_check.py | {
"start": 47,
"end": 1284
} | class ____(unittest.TestCase):
def test_llvmlite_version(self):
# test the system it's running on
import llvmlite
import numba
self.assertTrue(numba.__version__)
llvmlite_version = llvmlite.__version__
def cleanup():
llvmlite.__version__ = llvmlite_versi... | TestLlvmVersion |
python | charliermarsh__ruff | scripts/update_schemastore.py | {
"start": 914,
"end": 984
} | class ____(NamedTuple):
fork: str
upstream: str
| SchemastoreRepos |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/inputs.py | {
"start": 9111,
"end": 13867
} | class ____(StepInputSource, IHaveNew):
"""This step input source is the output of a previous step.
Source handle may refer to graph in case of input mapping.
"""
step_output_handle: StepOutputHandle
fan_in: bool
# deprecated, preserved for back-compat
node_handle: NodeHandle
input_name... | FromStepOutput |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 27781,
"end": 28434
} | class ____(BaseModel, extra="forbid"):
x: "Expression" = Field(..., description="")
target: Optional["Expression"] = Field(
default=None, description="The target value to start decaying from. Defaults to 0."
)
scale: Optional[float] = Field(
default=None,
description="The scale f... | DecayParamsExpression |
python | pydata__xarray | xarray/namedarray/parallelcompat.py | {
"start": 6172,
"end": 28119
} | class ____(ABC, Generic[T_ChunkedArray]):
"""
Interface between a particular parallel computing framework and xarray.
This abstract base class must be subclassed by libraries implementing chunked array types, and
registered via the ``chunkmanagers`` entrypoint.
Abstract methods on this class must ... | ChunkManagerEntrypoint |
python | sanic-org__sanic | sanic/cli/arguments.py | {
"start": 1440,
"end": 2588
} | class ____(Group):
name = None
def attach(self):
self.container.add_argument(
"--version",
action="version",
version=f"Sanic {__version__}; Routing {__routing_version__}",
)
self.container.add_argument(
"target",
help=(
... | GeneralGroup |
python | astropy__astropy | astropy/visualization/stretch.py | {
"start": 2450,
"end": 4446
} | class ____(BaseStretch):
"""
A linear stretch with a slope and offset.
The stretch is given by:
.. math::
y = slope * x + intercept
Parameters
----------
slope : float, optional
The ``slope`` parameter used in the above formula. Default is 1.
intercept : float, option... | LinearStretch |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 17456,
"end": 18044
} | class ____(DelegatingLexer):
"""
Subclass of the `MyghtyLexer` that highlights unlexed data
with the `JavascriptLexer`.
.. versionadded:: 0.6
"""
name = 'JavaScript+Myghty'
aliases = ['js+myghty', 'javascript+myghty']
mimetypes = ['application/x-javascript+myghty',
'te... | MyghtyJavascriptLexer |
python | pytorch__pytorch | test/onnx/model_defs/op_test.py | {
"start": 67,
"end": 462
} | class ____(nn.Module):
def __init__(self, num_classes=1000):
super().__init__()
self.features = nn.Sequential(
nn.LeakyReLU(0.02),
nn.BatchNorm2d(3),
nn.AvgPool2d(kernel_size=3, stride=2, padding=1, ceil_mode=False),
)
def forward(self, x):
ou... | DummyNet |
python | pytorch__pytorch | torch/cuda/__init__.py | {
"start": 19015,
"end": 19366
} | class ____:
def __init__(self, index: int):
self.idx = index
self.prev_idx = -1
def __enter__(self):
self.prev_idx = torch.cuda._exchange_device(self.idx)
def __exit__(self, type: Any, value: Any, traceback: Any):
self.idx = torch.cuda._maybe_exchange_device(self.prev_idx)
... | _DeviceGuard |
python | pypa__warehouse | warehouse/db.py | {
"start": 2203,
"end": 2318
} | class ____(Exception): ...
# The Global metadata object.
metadata = sqlalchemy.MetaData()
| DatabaseNotAvailableError |
python | python-poetry__poetry | tests/types.py | {
"start": 1452,
"end": 1738
} | class ____(Protocol):
def __call__(
self,
command: str,
poetry: Poetry | None = None,
installer: Installer | None = None,
executor: Executor | None = None,
environment: Env | None = None,
) -> CommandTester: ...
| CommandTesterFactory |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/signal/spectral_ops_test.py | {
"start": 1324,
"end": 16162
} | class ____(test.TestCase, parameterized.TestCase):
@staticmethod
def _np_hann_periodic_window(length):
if length == 1:
return np.ones(1)
odd = length % 2
if not odd:
length += 1
window = 0.5 - 0.5 * np.cos(2.0 * np.pi * np.arange(length) / (length - 1))
if not odd:
window = wi... | SpectralOpsTest |
python | great-expectations__great_expectations | great_expectations/data_context/cloud_constants.py | {
"start": 283,
"end": 500
} | class ____(str, Enum):
BASE_URL = "GX_CLOUD_BASE_URL"
ORGANIZATION_ID = "GX_CLOUD_ORGANIZATION_ID"
ACCESS_TOKEN = "GX_CLOUD_ACCESS_TOKEN"
WORKSPACE_ID = "GX_CLOUD_WORKSPACE_ID"
| GXCloudEnvironmentVariable |
python | doocs__leetcode | solution/2900-2999/2981.Find Longest Special Substring That Occurs Thrice I/Solution.py | {
"start": 0,
"end": 615
} | class ____:
def maximumLength(self, s: str) -> int:
def check(x: int) -> bool:
cnt = defaultdict(int)
i = 0
while i < n:
j = i + 1
while j < n and s[j] == s[i]:
j += 1
cnt[s[i]] += max(0, j - i - x + 1)
... | Solution |
python | ray-project__ray | python/ray/tests/test_actor_retry_2.py | {
"start": 2033,
"end": 11991
} | class ____:
"""
Same as TroubleMaker, just all methods are async.
"""
def __init__(self, *, counter_key: Optional[str] = None):
self._counter_key = counter_key
@ray.method(max_task_retries=5, retry_exceptions=[MyError])
async def may_raise_n_times(self, counter, n):
c = await c... | AsyncTroubleMaker |
python | pennersr__django-allauth | allauth/socialaccount/providers/yandex/views.py | {
"start": 181,
"end": 1032
} | class ____(OAuth2Adapter):
provider_id = "yandex"
access_token_url = "https://oauth.yandex.ru/token" # nosec
authorize_url = "https://oauth.yandex.com/authorize"
profile_url = "https://login.yandex.ru/info"
def complete_login(self, request, app, token, **kwargs):
resp = (
get_a... | YandexOAuth2Adapter |
python | tiangolo__fastapi | fastapi/dependencies/utils.py | {
"start": 20715,
"end": 38641
} | class ____:
values: Dict[str, Any]
errors: List[Any]
background_tasks: Optional[StarletteBackgroundTasks]
response: Response
dependency_cache: Dict[DependencyCacheKey, Any]
async def solve_dependencies(
*,
request: Union[Request, WebSocket],
dependant: Dependant,
body: Optional[Uni... | SolvedDependency |
python | lxml__lxml | src/lxml/html/tests/test_feedparser_data.py | {
"start": 656,
"end": 3172
} | class ____(unittest.TestCase):
def __init__(self, filename):
self.filename = filename
unittest.TestCase.__init__(self)
def parse(self):
with open(self.filename) as f:
headers = Message(f)
c = f.read()
if not c.strip():
c = headers.get_payload... | FeedTestCase |
python | huggingface__transformers | src/transformers/models/camembert/tokenization_camembert.py | {
"start": 1154,
"end": 7538
} | class ____(TokenizersBackend):
"""
Construct a "fast" CamemBERT tokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
[`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
[Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
This... | CamembertTokenizer |
python | tensorflow__tensorflow | tensorflow/dtensor/python/input_util.py | {
"start": 15142,
"end": 27727
} | class ____(dataset_ops.UnaryUnchangedStructureDataset):
"""A dataset of DTensors.
DTensorDataset encapsulates a `tf.data.Dataset` whose elements are
automatically packed and returned as DTensors based on a given mesh and
layouts.
"""
def __init__(self,
dataset: data_types.DatasetV2,
... | DTensorDataset |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 22906,
"end": 24236
} | class ____(TypeDefinition):
__slots__ = ('loc', 'name', 'interfaces', 'directives', 'fields',)
_fields = ('name', 'interfaces', 'fields',)
def __init__(self, name, fields, interfaces=None, loc=None, directives=None):
self.loc = loc
self.name = name
self.interfaces = interfaces
... | ObjectTypeDefinition |
python | dagster-io__dagster | python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py | {
"start": 39920,
"end": 40706
} | class ____(ColumnConstraint):
"""A column constraint that ensures all values in a pandas column are not null."""
def __init__(self):
description = "No Null values allowed."
super().__init__(error_description=description, markdown_description=description)
def validate(self, dataframe, colum... | NonNullableColumnConstraint |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline.py | {
"start": 46465,
"end": 47795
} | class ____(graphene.ObjectType):
name = graphene.NonNull(graphene.String)
solidSelection = graphene.List(graphene.NonNull(graphene.String))
runConfigYaml = graphene.NonNull(graphene.String)
mode = graphene.NonNull(graphene.String)
tags = non_null_list(GraphenePipelineTag)
class Meta:
na... | GraphenePipelinePreset |
python | google__jax | jax/_src/config.py | {
"start": 45321,
"end": 56922
} | class ____(enum.StrEnum):
ALLOW = 'allow'
WARN = 'warn'
ERROR = 'error'
legacy_prng_key = enum_class_state(
name='jax_legacy_prng_key',
enum_class=LegacyPrngKeyState,
default=LegacyPrngKeyState.ALLOW,
help=('Specify the behavior when raw PRNG keys are passed to '
'jax.random APIs.')
)
... | LegacyPrngKeyState |
python | matplotlib__matplotlib | lib/matplotlib/hatch.py | {
"start": 1544,
"end": 2160
} | class ____(HatchPatternBase):
def __init__(self, hatch, density):
self.num_lines = int((hatch.count('|') + hatch.count('+')) * density)
self.num_vertices = self.num_lines * 2
def set_vertices_and_codes(self, vertices, codes):
steps, stepsize = np.linspace(0.0, 1.0, self.num_lines, False... | VerticalHatch |
python | kamyu104__LeetCode-Solutions | Python/student-attendance-record-i.py | {
"start": 29,
"end": 443
} | class ____(object):
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
count_A = 0
for i in xrange(len(s)):
if s[i] == 'A':
count_A += 1
if count_A == 2:
return False
if i < len(s) - ... | Solution |
python | doocs__leetcode | solution/3200-3299/3250.Find the Count of Monotonic Pairs I/Solution.py | {
"start": 0,
"end": 519
} | class ____:
def countOfPairs(self, nums: List[int]) -> int:
mod = 10**9 + 7
n, m = len(nums), max(nums)
f = [[0] * (m + 1) for _ in range(n)]
for j in range(nums[0] + 1):
f[0][j] = 1
for i in range(1, n):
s = list(accumulate(f[i - 1]))
for ... | Solution |
python | realpython__materials | django-vue-graphql/source_code_final/back_end/blog/schema.py | {
"start": 219,
"end": 304
} | class ____(DjangoObjectType):
class Meta:
model = models.Profile
| AuthorType |
python | huggingface__transformers | src/transformers/models/glm4v_moe/modeling_glm4v_moe.py | {
"start": 24822,
"end": 26766
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: Glm4vMoeTextConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = Glm4vMoeTextAttention(config=config, layer_idx=layer_idx)
if layer_idx >= config.first_k_dense_replace:
... | Glm4vMoeTextDecoderLayer |
python | sqlalchemy__sqlalchemy | test/sql/test_from_linter.py | {
"start": 774,
"end": 14108
} | class ____(fixtures.TablesTest):
@classmethod
def define_tables(cls, metadata):
Table("table_a", metadata, Column("col_a", Integer, primary_key=True))
Table("table_b", metadata, Column("col_b", Integer, primary_key=True))
Table("table_c", metadata, Column("col_c", Integer, primary_key=Tr... | TestFindUnmatchingFroms |
python | h5py__h5py | h5py/_hl/group.py | {
"start": 29629,
"end": 29812
} | class ____:
"""
Represents a hard link in an HDF5 file. Provided only so that
Group.get works in a sensible way. Has no other function.
"""
pass
| HardLink |
python | uqfoundation__dill | dill/tests/test_abc.py | {
"start": 988,
"end": 4227
} | class ____(OneTwoThree):
def __init__(self):
self._bar = None
def foo(self):
return "Instance Method FOO"
@property
def bar(self):
return self._bar
@bar.setter
def bar(self, value):
self._bar = value
@classmethod
def cfoo(cls):
return "Class Me... | EasyAsAbc |
python | openai__openai-python | src/openai/resources/realtime/calls.py | {
"start": 31936,
"end": 32531
} | class ____:
def __init__(self, calls: Calls) -> None:
self._calls = calls
self.create = to_custom_streamed_response_wrapper(
calls.create,
StreamedBinaryAPIResponse,
)
self.accept = to_streamed_response_wrapper(
calls.accept,
)
sel... | CallsWithStreamingResponse |
python | kamyu104__LeetCode-Solutions | Python/the-dining-philosophers.py | {
"start": 48,
"end": 995
} | class ____(object):
def __init__(self):
self._l = [threading.Lock() for _ in xrange(5)]
# call the functions directly to execute, for example, eat()
def wantsToEat(self, philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork):
"""
:type philosopher: int
:ty... | DiningPhilosophers |
python | kamyu104__LeetCode-Solutions | Python/minimum-score-after-removals-on-a-tree.py | {
"start": 4362,
"end": 5897
} | class ____(object):
def minimumScore(self, nums, edges):
"""
:type nums: List[int]
:type edges: List[List[int]]
:rtype: int
"""
def iter_dfs(nums, adj, u, p):
result = []
stk = [(1, (u, p, [0]))]
while stk:
step, arg... | Solution4 |
python | pytorch__pytorch | test/distributed/test_dist2.py | {
"start": 8091,
"end": 8654
} | class ____(Dist2MultiProcessTestCase):
@property
def device(self) -> torch.device:
return torch.device("cpu")
@requires_gloo()
def new_group(self) -> torch.distributed.ProcessGroup:
os.environ["RANK"] = str(self.rank)
os.environ["WORLD_SIZE"] = str(self.world_size)
os.en... | ProcessGroupGlooTest |
python | kamyu104__LeetCode-Solutions | Python/maximum-manhattan-distance-after-k-changes.py | {
"start": 38,
"end": 525
} | class ____(object):
def maxDistance(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
result = x = y = 0
for i, c in enumerate(s, 1):
if c == 'E':
x += 1
elif c == 'W':
x -= 1
elif c ... | Solution |
python | astropy__astropy | astropy/wcs/tests/test_wcs.py | {
"start": 1693,
"end": 3152
} | class ____:
def setup_method(self):
# get the list of the hdr files that we want to test
self._file_list = list(get_pkg_data_filenames("data/maps", pattern="*.hdr"))
def test_consistency(self):
# Check to see that we actually have the list we expect, so that we
# do not get in a... | TestMaps |
python | astropy__astropy | astropy/nddata/mixins/ndio.py | {
"start": 234,
"end": 1880
} | class ____(registry.UnifiedReadWrite):
"""Read and parse gridded N-dimensional data and return as an NDData-derived
object.
This function provides the NDDataBase interface to the astropy unified I/O
layer. This allows easily reading a file in the supported data formats,
for example::
>>> fr... | NDDataRead |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_tags.py | {
"start": 4790,
"end": 8206
} | class ____(TestDagEndpoint):
"""Unit tests for Get DAG Tags."""
@pytest.mark.parametrize(
("query_params", "expected_status_code", "expected_dag_tags", "expected_total_entries"),
[
# test with offset, limit, and without any tag_name_pattern
(
{},
... | TestDagTags |
python | django__django | tests/migrations/test_executor.py | {
"start": 707,
"end": 34807
} | class ____(MigrationTestBase):
"""
Tests the migration executor (full end-to-end running).
Bear in mind that if these are failing you should fix the other
test failures first, as they may be propagating into here.
"""
available_apps = [
"migrations",
"migrations2",
"dja... | ExecutorTests |
python | getsentry__sentry | src/sentry/relay/config/metric_extraction.py | {
"start": 54208,
"end": 54604
} | class ____(TypedDict):
#: Whether a group of globally defined metrics and/or tags is enabled by default for every project.
#: This can be overridden in project configs.
isEnabled: bool
#: List of metrics to extract.
metrics: NotRequired[list[MetricSpec]]
#: List of tags to apply to previously ex... | MetricExtractionGroup |
python | nedbat__coveragepy | coverage/python.py | {
"start": 4583,
"end": 8753
} | class ____(FileReporter):
"""Report support for a Python file."""
def __init__(self, morf: TMorf, coverage: Coverage | None = None) -> None:
self.coverage = coverage
filename = source_for_morf(morf)
fname = filename
canonicalize = True
if self.coverage is not None:
... | PythonFileReporter |
python | pytorch__pytorch | .ci/lumen_cli/tests/test_app.py | {
"start": 173,
"end": 1554
} | class ____(unittest.TestCase):
@patch("cli.build_cli.register_build.VllmBuildRunner.run", return_value=None)
@patch("cli.build_cli.register_build.VllmBuildRunner.__init__", return_value=None)
def test_cli_run_build_external(self, mock_init, mock_run):
from cli.run import main # import after patches... | TestArgparseCLI |
python | google__jax | jax/_src/pallas/mosaic_gpu/helpers.py | {
"start": 1130,
"end": 13545
} | class ____:
"""Container dataclass for loop iteration information.
Attributes:
index: The grid indices corresponding to the current loop iteration.
local_index: The local iteration index.
num_local_steps: The total number of local iterations to run. None
if unknown.
"""
index: tuple[jax.Array... | NDLoopInfo |
python | getsentry__sentry | src/sentry/replays/endpoints/data_export_notifications.py | {
"start": 467,
"end": 854
} | class ____(Endpoint):
"""PubSub notifications endpoint."""
owner = ApiOwner.REPLAY
publish_status = {"POST": ApiPublishStatus.PRIVATE}
permission_classes = (SentryIsAuthenticated,)
def post(self, request: Request) -> Response:
retry_transfer_job_run(request.data, request_run_transfer_job)
... | DataExportNotificationsEndpoint |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.