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/serve/handle.py | {
"start": 25264,
"end": 29338
} | class ____(_DeploymentHandleBase):
"""A handle used to make requests to a deployment at runtime.
This is primarily used to compose multiple deployments within a single application.
It can also be used to make calls to the ingress deployment of an application (e.g.,
for programmatic testing).
Examp... | DeploymentHandle |
python | huggingface__transformers | src/transformers/models/hiera/modeling_hiera.py | {
"start": 1436,
"end": 2451
} | class ____(ModelOutput):
r"""
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
... | HieraEncoderOutput |
python | dask__distributed | distributed/http/scheduler/api.py | {
"start": 149,
"end": 302
} | class ____(RequestHandler):
def get(self):
self.write("API V1")
self.set_header("Content-Type", "text/plain; charset=utf-8")
| APIHandler |
python | kamyu104__LeetCode-Solutions | Python/permutations.py | {
"start": 709,
"end": 1608
} | class ____(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.dfs(nums, [], res)
return res
def dfs(self, nums, path, res):
if not nums:
res.append(path)
for i in xrange(len(n... | Solution2 |
python | pytorch__pytorch | torch/utils/tensorboard/_pytorch_graph.py | {
"start": 852,
"end": 1650
} | class ____:
def __init__(
self,
debugName=None,
inputs=None,
scope=None,
tensor_size=None,
op_type="UnSpecified",
attributes="",
) -> None:
# TODO; Specify a __slots__ for this class or potentially
# used namedtuple instead
self.deb... | NodeBase |
python | numba__numba | numba/pycc/platform.py | {
"start": 2157,
"end": 7421
} | class ____(object):
def __init__(self):
if not external_compiler_works():
self._raise_external_compiler_error()
self._verbose = False
self._compiler = new_compiler()
customize_compiler(self._compiler)
self._build_ext = build_ext(Distribution())
self._bui... | Toolchain |
python | mlflow__mlflow | mlflow/system_metrics/metrics/rocm_monitor.py | {
"start": 608,
"end": 4426
} | class ____(BaseMetricsMonitor):
"""
Class for monitoring AMD GPU stats. This is
class has been modified and has been inspired by
the original GPUMonitor class written by MLflow.
This class uses the package pyrsmi which is an
official ROCM python package which tracks and monitor
AMD GPU's, ha... | ROCMMonitor |
python | ray-project__ray | ci/ray_ci/doc/api.py | {
"start": 418,
"end": 566
} | class ____(Enum):
PUBLIC_API = "PublicAPI"
DEVELOPER_API = "DeveloperAPI"
DEPRECATED = "Deprecated"
UNKNOWN = "Unknown"
| AnnotationType |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_test.py | {
"start": 133507,
"end": 134023
} | class ____(object):
"""Pretend user-side class for `ConvertToCompositeTensorTest ."""
def __init__(self, components):
super(_MyTuple, self).__init__()
self._components = tuple(components)
def __getitem__(self, key):
return self._components[key]
def __len__(self):
return len(self._components)
... | _MyTuple |
python | realpython__materials | python-protocol/contents.py | {
"start": 30,
"end": 105
} | class ____(Protocol):
def create_content(self) -> str: ...
| ContentCreator |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 254767,
"end": 255231
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "enterprise", "organization")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
enterprise = sgqlc.types.Field("Enterprise"... | CreateEnterpriseOrganizationPayload |
python | pyinstaller__pyinstaller | PyInstaller/lib/modulegraph/modulegraph.py | {
"start": 23780,
"end": 23824
} | class ____(BaseModule):
pass
| BuiltinModule |
python | huggingface__transformers | tests/models/glm4v/test_modeling_glm4v.py | {
"start": 6149,
"end": 10606
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (Glm4vModel, Glm4vForConditionalGeneration) if is_torch_available() else ()
model_split_percents = [0.7, 0.9] # model too big to split at 0.5
_is_composite = True
def setUp(self):
self.model_tester = G... | Glm4vModelTest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 2345,
"end": 2516
} | class ____(graphene.ObjectType):
invalidRunId = graphene.NonNull(graphene.String)
class Meta:
name = "MissingRunIdErrorEvent"
| GrapheneMissingRunIdErrorEvent |
python | tensorflow__tensorflow | tensorflow/python/saved_model/loader_test.py | {
"start": 2607,
"end": 12460
} | class ____(test.TestCase, parameterized.TestCase):
def export_simple_graph(self, builder_cls):
g, sig_def_map, _ = build_graph_helper()
with session.Session(graph=g) as sess:
self.evaluate(variables.global_variables_initializer())
builder = builder_cls(SIMPLE_ADD_SAVED_MODEL)
builder.add_me... | SavedModelLoaderTest |
python | django__django | django/contrib/gis/db/models/lookups.py | {
"start": 11705,
"end": 11805
} | class ____(DistanceLookupFromFunction):
lookup_name = "distance_lte"
op = "<="
| DistanceLTELookup |
python | pola-rs__polars | py-polars/src/polars/io/database/_executor.py | {
"start": 1936,
"end": 23014
} | class ____:
"""Abstraction for querying databases with user-supplied connection objects."""
# indicate if we can/should close the cursor on scope exit. note that we
# should never close the underlying connection, or a user-supplied cursor.
can_close_cursor: bool = False
def __init__(self, connecti... | ConnectionExecutor |
python | huggingface__transformers | tests/models/kosmos2/test_modeling_kosmos2.py | {
"start": 9243,
"end": 20164
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (Kosmos2Model, Kosmos2ForConditionalGeneration) if is_torch_available() else ()
additional_model_inputs = ["input_ids", "image_embeds_position_mask"]
pipeline_model_mapping = (
{
... | Kosmos2ModelTest |
python | apache__airflow | providers/presto/src/airflow/providers/presto/hooks/presto.py | {
"start": 2583,
"end": 2893
} | class ____(Exception):
"""Presto exception."""
def _boolify(value):
if isinstance(value, bool):
return value
if isinstance(value, str):
if value.lower() == "false":
return False
if value.lower() == "true":
return True
return value
| PrestoException |
python | spyder-ide__spyder | spyder/plugins/explorer/widgets/remote_explorer.py | {
"start": 1345,
"end": 1463
} | class ____:
General = 'remote_general_section'
Language = 'remote_language_section'
| RemoteViewNewSubMenuSections |
python | doocs__leetcode | solution/0600-0699/0650.2 Keys Keyboard/Solution.py | {
"start": 0,
"end": 346
} | class ____:
def minSteps(self, n: int) -> int:
@cache
def dfs(n):
if n == 1:
return 0
i, ans = 2, n
while i * i <= n:
if n % i == 0:
ans = min(ans, dfs(n // i) + i)
i += 1
return ans
... | Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/llama_dataset/evaluator_evaluation.py | {
"start": 5015,
"end": 9620
} | class ____(BaseLlamaDataset[BaseEvaluator]):
"""LabelledEvalationDataset class."""
_example_type = LabelledEvaluatorDataExample
def to_pandas(self) -> Any:
"""Create pandas dataframe."""
try:
import pandas as pd
except ImportError:
raise ImportError(
... | LabelledEvaluatorDataset |
python | donnemartin__interactive-coding-challenges | online_judges/license_key/test_format_license_key.py | {
"start": 18,
"end": 834
} | class ____(unittest.TestCase):
def test_format_license_key(self):
solution = Solution()
self.assertRaises(TypeError, solution.format_license_key, None, None)
license_key = '---'
k = 3
expected = ''
self.assertEqual(solution.format_license_key(license_key, k), expecte... | TestSolution |
python | pypa__packaging | tests/test_markers.py | {
"start": 2619,
"end": 4676
} | class ____:
def test_matches_expected(self) -> None:
environment = default_environment()
iver = (
f"{sys.implementation.version.major}."
f"{sys.implementation.version.minor}."
f"{sys.implementation.version.micro}"
)
if sys.implementation.version.r... | TestDefaultEnvironment |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/evaluator_test.py | {
"start": 5809,
"end": 11002
} | class ____(test_util.TensorFlowTestCase):
def testEvaluateSingleTensor(self):
dump = test.mock.MagicMock()
def fake_get_tensors(node_name, output_slot, debug_op, device_name=None):
del node_name, output_slot, debug_op, device_name # Unused.
return [np.array([[1.0, 2.0, 3.0]])]
with test.moc... | EvaluatorTest |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 1994,
"end": 2149
} | class ____(AttributeSet):
_known = frozenset(['fast', 'nnan', 'ninf', 'nsz', 'arcp', 'contract',
'afn', 'reassoc'])
| FastMathFlags |
python | charliermarsh__ruff | crates/ty_python_semantic/resources/corpus/ty_extensions.py | {
"start": 294,
"end": 472
} | class ____: ...
def _(x: Not[A]):
pass
def _(x: Intersection[A], y: Intersection[A, B]):
pass
def _(x: TypeOf[1j]):
pass
def _(x: CallableTypeOf[str]):
pass
| B |
python | apache__airflow | providers/yandex/tests/unit/yandex/secrets/test_lockbox.py | {
"start": 1278,
"end": 16055
} | class ____:
@patch("airflow.providers.yandex.secrets.lockbox.LockboxSecretBackend._get_secret_value")
def test_yandex_lockbox_secret_backend_get_connection(self, mock_get_value):
conn_id = "fake_conn"
conn_type = "scheme"
host = "host"
login = "user"
password = "pass"
... | TestLockboxSecretBackend |
python | getsentry__sentry | src/sentry/auth/authenticators/u2f.py | {
"start": 1683,
"end": 9873
} | class ____(AuthenticatorInterface):
type = 3
interface_id = "u2f"
configure_button = _("Configure")
name = _("Passkey / Biometric / Security Key")
description = _(
"Authenticate using a Passkey, Biometrics, or a physical security key such as a YubiKey."
)
allow_multi_enrollment = Tru... | U2fInterface |
python | kamyu104__LeetCode-Solutions | Python/split-array-into-maximum-number-of-subarrays.py | {
"start": 38,
"end": 343
} | class ____(object):
def maxSubarrays(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = curr = 0
for x in nums:
curr = curr&x if curr else x
if not curr:
result += 1
return max(result, 1)
| Solution |
python | getsentry__sentry | src/sentry/deletions/defaults/monitor_incident.py | {
"start": 134,
"end": 506
} | class ____(ModelDeletionTask[MonitorIncident]):
def get_child_relations(self, instance: MonitorIncident) -> list[BaseRelation]:
from sentry.monitors import models
return [
ModelRelation(
models.MonitorEnvBrokenDetection,
{"monitor_incident_id": instance.i... | MonitorIncidentDeletionTask |
python | openai__openai-python | src/openai/types/responses/tool_choice_function.py | {
"start": 195,
"end": 384
} | class ____(BaseModel):
name: str
"""The name of the function to call."""
type: Literal["function"]
"""For function calling, the type is always `function`."""
| ToolChoiceFunction |
python | walkccc__LeetCode | solutions/96. Unique Binary Search Trees/96.py | {
"start": 0,
"end": 263
} | class ____:
def numTrees(self, n: int) -> int:
# dp[i] := the number of unique BST's that store values 1..i
dp = [1, 1] + [0] * (n - 1)
for i in range(2, n + 1):
for j in range(i):
dp[i] += dp[j] * dp[i - j - 1]
return dp[n]
| Solution |
python | getsentry__sentry | src/sentry/issues/auto_source_code_config/frame_info.py | {
"start": 1048,
"end": 1725
} | class ____(ABC):
raw_path: str
normalized_path: str
stack_root: str
def __init__(self, frame: Mapping[str, Any]) -> None:
self.process_frame(frame)
def __repr__(self) -> str:
return f"FrameInfo: {self.raw_path} stack_root: {self.stack_root}"
def __eq__(self, other: object) -> ... | FrameInfo |
python | arrow-py__arrow | tests/test_parser.py | {
"start": 61283,
"end": 61837
} | class ____:
# Regression test for issue #860
def test_no_match_group(self):
fmt_str = str(b"[|\x1f\xb9\x03\x00\x00\x00\x00:-yI:][\x01yI:yI:I")
payload = str(b"")
with pytest.raises(parser.ParserMatchError):
self.parser.parse(payload, fmt_str)
# Regression test for issue... | TestFuzzInput |
python | dagster-io__dagster | examples/with_wandb/with_wandb/assets/example/fashion_data.py | {
"start": 122,
"end": 6462
} | class ____(data.Dataset):
"""`MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset.
Args:
root (string): Root directory of dataset where ``processed/training.pt``
and ``processed/test.pt`` exist.
train (bool, optional): If True, creates dataset from ``training.pt``,
othe... | fashion |
python | google__jax | tests/pallas/export_back_compat_pallas_test.py | {
"start": 1692,
"end": 5474
} | class ____(bctu.CompatTestBase):
def setUp(self):
if jax.config.x64_enabled:
self.skipTest("Only works in 32-bit")
super().setUp()
@unittest.skip("This test is checking backwards compatibility "
"of Triton IR, but Triton doesn't promise backwards "
"compatibility fo... | CompatTest |
python | kamyu104__LeetCode-Solutions | Python/next-greater-element-iii.py | {
"start": 50,
"end": 716
} | class ____(object):
def nextGreaterElement(self, n):
"""
:type n: int
:rtype: int
"""
digits = map(int, list(str(n)))
k, l = -1, 0
for i in xrange(len(digits) - 1):
if digits[i] < digits[i + 1]:
k = i
if k == -1:
... | Solution |
python | Textualize__textual | src/textual/widgets/_option_list.py | {
"start": 1035,
"end": 1155
} | class ____(OptionListError):
"""Raised if a duplicate ID is used when adding options to an option list."""
| DuplicateID |
python | huggingface__transformers | src/transformers/models/yolos/modeling_yolos.py | {
"start": 15732,
"end": 16970
} | class ____(GradientCheckpointingLayer):
"""This corresponds to the Block class in the timm implementation."""
def __init__(self, config: YolosConfig):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = YolosAtte... | YolosLayer |
python | joke2k__faker | faker/providers/currency/de_DE/__init__.py | {
"start": 48,
"end": 286
} | class ____(CurrencyProvider):
price_formats = ["#,##", "%#,##", "%##,##", "%.###,##", "%#.###,##"]
def pricetag(self):
return self.numerify(self.random_element(self.price_formats)) + "\N{NO-BREAK SPACE}\N{EURO SIGN}"
| Provider |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_athena.py | {
"start": 1215,
"end": 3174
} | class ____:
def setup_method(self, _):
self.default_op_kwargs = dict(
task_id="test_athena_sensor",
query_execution_id="abc",
sleep_time=5,
max_retries=1,
)
self.sensor = AthenaSensor(**self.default_op_kwargs, aws_conn_id=None)
def test_ba... | TestAthenaSensor |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 30322,
"end": 30386
} | class ____(str, Enum):
ASC = "asc"
DESC = "desc"
| Direction |
python | neetcode-gh__leetcode | python/0678-valid-parenthesis-string.py | {
"start": 725,
"end": 1268
} | class ____:
def checkValidString(self, s: str) -> bool:
leftMin, leftMax = 0, 0
for c in s:
if c == "(":
leftMin, leftMax = leftMin + 1, leftMax + 1
elif c == ")":
leftMin, leftMax = leftMin - 1, leftMax - 1
else:
l... | Solution |
python | huggingface__transformers | tests/models/mbart/test_modeling_mbart.py | {
"start": 15261,
"end": 15897
} | class ____(unittest.TestCase):
maxDiff = 1000 # longer string compare tracebacks
checkpoint_name = None
@classmethod
def setUpClass(cls):
cls.tokenizer = AutoTokenizer.from_pretrained(cls.checkpoint_name, use_fast=False)
return cls
@cached_property
def model(self):
"""... | AbstractSeq2SeqIntegrationTest |
python | ansible__ansible | lib/ansible/plugins/doc_fragments/action_common_attributes.py | {
"start": 183,
"end": 2442
} | class ____(object):
# Standard documentation fragment
DOCUMENTATION = r"""
attributes:
check_mode:
description: Can run in check_mode and return changed status prediction without modifying target, if not supported the action will be skipped.
diff_mode:
description: Will return details on wh... | ModuleDocFragment |
python | pypa__setuptools | setuptools/_vendor/jaraco/collections/__init__.py | {
"start": 24086,
"end": 24852
} | class ____:
"""
A value that is always greater than any other
>>> greatest = Greatest()
>>> 3 < greatest
True
>>> 3 > greatest
False
>>> greatest < 3
False
>>> greatest > 3
True
>>> greatest >= 3
True
>>> 'x' > greatest
False
>>> None > greatest
False... | Greatest |
python | pytorch__pytorch | torch/distributed/pipelining/stage.py | {
"start": 41057,
"end": 52612
} | class ____(_PipelineStageBase):
def __init__(
self,
stage_module: torch.nn.Module,
stage_index: int,
pipe_info: PipeInfo,
device: torch.device,
group: dist.ProcessGroup | None = None,
):
"""
Create a pipeline stage given a stage_module to be wrappe... | _PipelineStage |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 6319,
"end": 7599
} | class ____:
@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
@pytest.mark.parametrize('dt', ('float64', 'complex128'))
def test_simple(self, dt, xp):
dtyp = getattr(xp, dt)
z_r = xp.asarray([0.5, -0.5])
p_r = xp.asarray([1.j / math.sqrt(2), -1.j /... | TestTf2zpk |
python | walkccc__LeetCode | solutions/84. Largest Rectangle in Histogram/84.py | {
"start": 0,
"end": 368
} | class ____:
def largestRectangleArea(self, heights: list[int]) -> int:
ans = 0
stack = []
for i in range(len(heights) + 1):
while stack and (i == len(heights) or heights[stack[-1]] > heights[i]):
h = heights[stack.pop()]
w = i - stack[-1] - 1 if stack else i
ans = max(ans, h... | Solution |
python | ray-project__ray | python/ray/data/examples/data/video_processing/http_utils.py | {
"start": 564,
"end": 5835
} | class ____:
"""Small helper around ``requests``/``aiohttp`` for reuseable HTTP clients."""
def __init__(self, *, reuse_client: bool = True) -> None:
self.reuse_client = reuse_client
self._sync_client: Optional[Any] = None
self._async_client: Optional[Any] = None
def get_sync_client... | HTTPConnection |
python | getsentry__sentry | src/sentry/api/endpoints/organization_stats_summary.py | {
"start": 5142,
"end": 10920
} | class ____(OrganizationEndpoint):
publish_status = {"GET": ApiPublishStatus.PUBLIC}
owner = ApiOwner.ENTERPRISE
@extend_schema(
operation_id="Retrieve an Organization's Events Count by Project",
parameters=[GlobalParams.ORG_ID_OR_SLUG, OrgStatsSummaryQueryParamsSerializer],
request=... | OrganizationStatsSummaryEndpoint |
python | kamyu104__LeetCode-Solutions | Python/maximum-balanced-shipments.py | {
"start": 38,
"end": 368
} | class ____(object):
def maxBalancedShipments(self, weight):
"""
:type weight: List[int]
:rtype: int
"""
result = mx = 0
for x in weight:
if x < mx:
mx = 0
result += 1
else:
mx = x
return r... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI026.py | {
"start": 485,
"end": 555
} | class ____(FooEnum):
BAR = None
VarAlias = str
AliasFoo = Foo
| BarEnum |
python | huggingface__transformers | tests/test_sequence_feature_extraction_common.py | {
"start": 773,
"end": 16592
} | class ____(FeatureExtractionSavingTestMixin):
# to overwrite at feature extractactor specific tests
feat_extract_tester = None
feature_extraction_class = None
@property
def feat_extract_dict(self):
return self.feat_extract_tester.prepare_feat_extract_dict()
def test_feat_extract_common... | SequenceFeatureExtractionTestMixin |
python | pypa__pipenv | pipenv/vendor/tomlkit/exceptions.py | {
"start": 3049,
"end": 3301
} | class ____(ParseError):
"""
An empty table name was found during parsing.
"""
def __init__(self, line: int, col: int) -> None:
message = "Empty table name"
super().__init__(line, col, message=message)
| EmptyTableNameError |
python | modin-project__modin | modin/core/dataframe/base/interchange/dataframe_protocol/dataframe.py | {
"start": 1877,
"end": 2227
} | class ____(TypedDict): # noqa: GL08
# whether the ordering of dictionary indices is semantically meaningful
is_ordered: bool
# whether a column-style mapping of categorical values to other objects exists
is_dictionary: bool
# None if not a column-style categorical.
categories: Optional["Protoco... | CategoricalDescription |
python | matplotlib__matplotlib | galleries/tutorials/artists.py | {
"start": 2490,
"end": 30284
} | class ____ the Matplotlib API, and the one you will be working with most
of the time. This is because the ``Axes`` is the plotting area into
which most of the objects go, and the ``Axes`` has many special helper
methods (:meth:`~matplotlib.axes.Axes.plot`,
:meth:`~matplotlib.axes.Axes.text`,
:meth:`~matplotlib.axes.Ax... | in |
python | Textualize__textual | src/textual/css/_help_renderables.py | {
"start": 1828,
"end": 2833
} | class ____:
"""Renderable for help text - the user is shown this when they
encounter a style-related error (e.g. setting a style property to an invalid
value).
Attributes:
summary: A succinct summary of the issue.
bullets: Bullet points which provide additional
context aroun... | HelpText |
python | eventlet__eventlet | tests/greenthread_test.py | {
"start": 2887,
"end": 3533
} | class ____(Spawn):
def test_basic(self):
gt = greenthread.spawn_after(0.1, passthru, 20)
self.assertEqual(gt.wait(), ((20,), {}))
def test_cancel(self):
gt = greenthread.spawn_after(0.1, passthru, 21)
gt.cancel()
self.assert_dead(gt)
def test_cancel_already_started(... | SpawnAfter |
python | pytorch__pytorch | test/dynamo/test_unittest.py | {
"start": 160,
"end": 768
} | class ____(torch._dynamo.test_case.TestCase):
def setUp(self):
self._prev = torch._dynamo.config.enable_trace_unittest
torch._dynamo.config.enable_trace_unittest = True
def tearDown(self):
torch._dynamo.config.enable_trace_unittest = self._prev
@make_dynamo_test
def test_SkipTe... | TestUnittest |
python | ApeWorX__ape | tests/integration/cli/conftest.py | {
"start": 330,
"end": 5277
} | class ____:
"""
A test module in 'tests.integration.cli'.
"""
def __init__(self, path: Path):
self._path = path
module = import_module(f"tests.integration.cli.{path.stem}")
test_methods = [
getattr(module, t)
for t in dir(module)
if t.startswi... | IntegrationTestModule |
python | cython__cython | tests/run/ext_auto_richcmp.py | {
"start": 4301,
"end": 4925
} | class ____(ClassEqNeGe):
"""
>>> a = ClassRichcmpOverride(1)
>>> b = ClassRichcmpOverride(1)
>>> a == a
True
>>> a != a
False
>>> a != b if compiled else a == b # Python ignores __richcmp__()
True
>>> a == b if compiled else a != b # Python ignores __richcmp__()
False
... | ClassRichcmpOverride |
python | mlflow__mlflow | mlflow/tensorflow/callback.py | {
"start": 271,
"end": 3966
} | class ____(keras.callbacks.Callback, metaclass=ExceptionSafeClass):
"""Callback for logging Tensorflow training metrics to MLflow.
This callback logs model information at training start, and logs training metrics every epoch or
every n steps (defined by the user) to MLflow.
Args:
log_every_epo... | MlflowCallback |
python | pytorch__pytorch | test/distributed/_composable/test_replicate.py | {
"start": 2619,
"end": 9232
} | class ____(MultiProcessTestCase):
@property
def world_size(self) -> int:
return 2
def setUp(self) -> None:
super().setUp()
self._spawn_processes()
def tearDown(self):
super().tearDown()
try:
os.remove(self.file_name)
except OSError:
... | ReplicateTest |
python | scrapy__scrapy | tests/spiders.py | {
"start": 3734,
"end": 3924
} | class ____(SimpleSpider):
name = "asyncdef"
async def parse(self, response):
await defer.succeed(42)
self.logger.info(f"Got response {response.status}")
| AsyncDefSpider |
python | dask__distributed | distributed/recreate_tasks.py | {
"start": 1276,
"end": 7061
} | class ____:
"""
A plugin for the client allowing replay of remote tasks locally
Adds the following methods to the given client:
- ``recreate_error_locally``: main user method for replaying failed tasks
- ``recreate_task_locally``: main user method for replaying any task
"""
def __init__(s... | ReplayTaskClient |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 916265,
"end": 916635
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("Ref", graphql_name="node"... | RefEdge |
python | ray-project__ray | python/ray/data/aggregate.py | {
"start": 34968,
"end": 42380
} | class ____(AggregateFnV2):
"""Counts the number of times each value appears in a column.
This aggregation computes value counts for a specified column, similar to pandas'
`value_counts()` method. It returns a dictionary with two lists: "values" containing
the unique values found in the column, and "cou... | ValueCounter |
python | numpy__numpy | numpy/lib/tests/test_type_check.py | {
"start": 14458,
"end": 14796
} | class ____:
def test_basic(self):
a = np.random.rand(10)
b = real_if_close(a + 1e-15j)
assert_all(isrealobj(b))
assert_array_equal(a, b)
b = real_if_close(a + 1e-7j)
assert_all(iscomplexobj(b))
b = real_if_close(a + 1e-7j, tol=1e-6)
assert_all(isrealo... | TestRealIfClose |
python | kamyu104__LeetCode-Solutions | Python/manhattan-distances-of-all-arrangements-of-pieces.py | {
"start": 508,
"end": 975
} | class ____(object):
def distanceSum(self, m, n, k):
"""
:type m: int
:type n: int
:type k: int
:rtype: int
"""
def sum_n(n):
return (n+1)*n//2
def sum_n_square(n):
return n*(n+1)*(2*n+1)//6
def f(n):
# sum(... | Solution |
python | huggingface__transformers | src/transformers/quantizers/quantizer_fp_quant.py | {
"start": 1072,
"end": 7664
} | class ____(HfQuantizer):
"""
Quantizer for the FP-Quant method. Enables the loading of prequantized models and in-flight quantization of full-precision models.
"""
requires_calibration = False
requires_parameters_quantization = True
is_qat_trainable = True
required_packages = ["fp_quant"]
... | FPQuantHfQuantizer |
python | django__django | tests/admin_scripts/tests.py | {
"start": 16627,
"end": 20145
} | class ____(AdminScriptTestCase):
"""
A series of tests for django-admin when using a settings.py file that
doesn't contain the test application.
"""
def setUp(self):
super().setUp()
self.write_settings(
"settings.py", apps=["django.contrib.auth", "django.contrib.contentt... | DjangoAdminMinimalSettings |
python | huggingface__transformers | src/transformers/models/edgetam/modeling_edgetam.py | {
"start": 21559,
"end": 22729
} | class ____(nn.Module):
def __init__(self, config: EdgeTamPromptEncoderConfig):
super().__init__()
self.scale = config.scale
positional_embedding = self.scale * torch.randn((2, config.hidden_size // 2))
self.register_buffer("positional_embedding", positional_embedding)
def forwar... | EdgeTamPositionalEmbedding |
python | getsentry__sentry | tests/sentry/plugins/test_config.py | {
"start": 171,
"end": 515
} | class ____(forms.Form):
text = forms.CharField(help_text="text field")
textarea = forms.CharField(widget=forms.Textarea, required=False)
password = forms.CharField(label="A Password", widget=forms.PasswordInput)
choice = forms.ChoiceField(choices=((1, "one"), (2, "two")))
url = forms.URLField(assume... | DummyForm |
python | pallets__jinja | src/jinja2/exceptions.py | {
"start": 4742,
"end": 4885
} | class ____(TemplateRuntimeError):
"""Raised if a template tries to do something insecure if the
sandbox is enabled.
"""
| SecurityError |
python | getsentry__sentry | src/sentry/models/grouphashmetadata.py | {
"start": 1310,
"end": 3065
} | class ____(models.TextChoices):
# Message logged by `capture_message`, or exception type and value (when there's no stack or
# when all frames have been ruled out by stacktrace rules)
MESSAGE = "message"
# Either in-app or full stacktrace
STACKTRACE = "stacktrace"
# Custom fingerprint set by the... | HashBasis |
python | astropy__astropy | astropy/cosmology/_src/flrw/w0cdm.py | {
"start": 7892,
"end": 13358
} | class ____(FlatFLRWMixin, wCDM):
"""FLRW cosmology with a constant dark energy EoS and no spatial curvature.
This has one additional attribute beyond those of FLRW.
Parameters
----------
H0 : float or scalar quantity-like ['frequency']
Hubble constant at z = 0. If a float, must be in [km/s... | FlatwCDM |
python | huggingface__transformers | src/transformers/models/albert/modeling_albert.py | {
"start": 13032,
"end": 14032
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.
prediction_logits (`torch.FloatTensor` of shape `(batch... | AlbertForPreTrainingOutput |
python | ray-project__ray | python/ray/dashboard/modules/aggregator/publisher/async_publisher_client.py | {
"start": 987,
"end": 1782
} | class ____(ABC):
"""Abstract interface for publishing Ray event batches to external destinations.
Implementations should handle the actual publishing logic, filtering,
and format conversion appropriate for their specific destination type.
"""
def count_num_events_in_batch(self, batch: PublishBatch... | PublisherClientInterface |
python | coleifer__peewee | tests/sql.py | {
"start": 48287,
"end": 52069
} | class ____(BaseTestCase):
def test_update_query(self):
query = (User
.update({
User.c.username: 'nuggie',
User.c.admin: False,
User.c.counter: User.c.counter + 1})
.where(User.c.username == 'nugz'))
self... | TestUpdateQuery |
python | tensorflow__tensorflow | tensorflow/python/distribute/integration_test/saved_model_test.py | {
"start": 2571,
"end": 3893
} | class ____(test.TestCase, parameterized.TestCase):
def test_read_sync_on_read_variable(self, strategy):
# TODO(b/178943315): Enable test when the design in b/17894331 is
# implemented.
self.skipTest(
"This test fails today due to issue in multiple workers trying to write"
" to same file l... | SaveModelForMultipleWorkers |
python | getsentry__sentry | src/sentry/monitors/system_incidents.py | {
"start": 12264,
"end": 13371
} | class ____(StrEnum):
ABNORMALITY_STARTED = "abnormality_started"
"""
An abnormality has been detected during normal operations. We may
transition into a complete system incident, or the abnormality may recover
to normal.
"""
ABNORMALITY_RECOVERED = "abnormality_recovered"
"""
An abn... | AnomalyTransition |
python | spack__spack | lib/spack/spack/vendor/attr/_make.py | {
"start": 20051,
"end": 82281
} | class ____:
"""
Iteratively build *one* class.
"""
__slots__ = (
"_attr_names",
"_attrs",
"_base_attr_map",
"_base_names",
"_cache_hash",
"_cls",
"_cls_dict",
"_delete_attribs",
"_frozen",
"_has_pre_init",
"_has_pos... | _ClassBuilder |
python | anthropics__anthropic-sdk-python | src/anthropic/types/citation_char_location.py | {
"start": 224,
"end": 473
} | class ____(BaseModel):
cited_text: str
document_index: int
document_title: Optional[str] = None
end_char_index: int
file_id: Optional[str] = None
start_char_index: int
type: Literal["char_location"]
| CitationCharLocation |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_pair_values_to_be_in_set.py | {
"start": 1382,
"end": 10151
} | class ____(ColumnPairMapExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectColumnPairValuesToBeInSet is a \
Column Pair Map Expectation.
Column Pair Map Expectations are evaluated for a pair of columns and ask a yes/no question about the row-wise relationship between those two columns.
... | ExpectColumnPairValuesToBeInSet |
python | gevent__gevent | src/gevent/tests/test__socket_send_memoryview.py | {
"start": 659,
"end": 779
} | class ____(unittest.TestCase):
def test_send(self):
import socket
_send(socket)
| TestSendBuiltinSocket |
python | PrefectHQ__prefect | src/prefect/client/schemas/actions.py | {
"start": 23657,
"end": 24111
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to update a block type."""
logo_url: Optional[objects.HttpUrl] = Field(default=None)
documentation_url: Optional[objects.HttpUrl] = Field(default=None)
description: Optional[str] = Field(default=None)
code_example: Optional[str] = Fi... | BlockTypeUpdate |
python | pytorch__pytorch | test/onnx/model_defs/squeezenet.py | {
"start": 968,
"end": 3497
} | class ____(nn.Module):
def __init__(self, version=1.0, num_classes=1000, ceil_mode=False):
super().__init__()
if version not in [1.0, 1.1]:
raise ValueError(
f"Unsupported SqueezeNet version {version}:1.0 or 1.1 expected"
)
self.num_classes = num_class... | SqueezeNet |
python | cython__cython | Cython/Compiler/TypeSlots.py | {
"start": 25444,
"end": 26007
} | class ____(SlotDescriptor):
# Slot descriptor for the base class slot.
def __init__(self, name):
SlotDescriptor.__init__(self, name, dynamic=True)
def generate_dynamic_init_code(self, scope, code):
base_type = scope.parent_type.base_type
if base_type:
base_typeptr_cnam... | BaseClassSlot |
python | apache__airflow | task-sdk/src/airflow/sdk/api/datamodels/_generated.py | {
"start": 1437,
"end": 2230
} | class ____(BaseModel):
"""
Profile of an asset-like object.
Asset will have name, uri defined, with type set to 'Asset'.
AssetNameRef will have name defined, type set to 'AssetNameRef'.
AssetUriRef will have uri defined, type set to 'AssetUriRef'.
AssetAlias will have name defined, type set to ... | AssetProfile |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_translate.py | {
"start": 18372,
"end": 20669
} | class ____:
@mock.patch("airflow.providers.google.cloud.links.translate.TranslationModelsListLink.persist")
@mock.patch("airflow.providers.google.cloud.operators.translate.TranslateHook")
def test_minimal_green_path(self, mock_hook, mock_link_persist):
MODEL_ID_1 = "sample_model_1"
MODEL_ID_... | TestTranslateListModels |
python | gevent__gevent | src/gevent/tests/test__socket_dns.py | {
"start": 22689,
"end": 23951
} | class ____(HostsFile):
def iter_all_host_addr_pairs(self):
for name, addr in super(SanitizedHostsFile, self).iter_all_host_addr_pairs():
if (RESOLVER_NOT_SYSTEM
and (name.endswith('local') # ignore bonjour, ares can't find them
# ignore common aliases... | SanitizedHostsFile |
python | ray-project__ray | python/ray/train/_internal/accelerator.py | {
"start": 13,
"end": 107
} | class ____(abc.ABC):
"""A utility that contains methods to accelerate training."""
| Accelerator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 955895,
"end": 957297
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of
RevokeEnterpriseOrganizationsMigratorRole
"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "organizations")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identi... | RevokeEnterpriseOrganizationsMigratorRolePayload |
python | astral-sh__uv | python/uv/_find_uv.py | {
"start": 76,
"end": 3139
} | class ____(FileNotFoundError): ...
def find_uv_bin() -> str:
"""Return the uv binary path."""
uv_exe = "uv" + sysconfig.get_config_var("EXE")
targets = [
# The scripts directory for the current Python
sysconfig.get_path("scripts"),
# The scripts directory for the base prefix
... | UvNotFound |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 473919,
"end": 475542
} | class ____(sgqlc.types.Type):
"""Represents an auto-merge request for a pull request"""
__schema__ = github_schema
__field_names__ = ("author_email", "commit_body", "commit_headline", "enabled_at", "enabled_by", "merge_method", "pull_request")
author_email = sgqlc.types.Field(String, graphql_name="auth... | AutoMergeRequest |
python | rq__rq | rq/logutils.py | {
"start": 2153,
"end": 4994
} | class ____(logging.StreamHandler):
levels = {
logging.WARNING: yellow,
logging.ERROR: red,
logging.CRITICAL: red,
}
def __init__(self, exclude=None, *args, **kwargs):
self.exclude = exclude
super().__init__(*args, **kwargs)
@property
def is_tty(self):
... | ColorizingStreamHandler |
python | optuna__optuna | optuna/distributions.py | {
"start": 7933,
"end": 8916
} | class ____(FloatDistribution):
"""A uniform distribution in the log domain.
This object is instantiated by :func:`~optuna.trial.Trial.suggest_float` with ``log=True``,
and passed to :mod:`~optuna.samplers` in general.
Attributes:
low:
Lower endpoint of the range of the distribution... | LogUniformDistribution |
python | rapidsai__cudf | python/cudf/cudf/core/dtypes.py | {
"start": 12720,
"end": 18492
} | class ____(_BaseDtype):
"""
Type to represent list data.
Parameters
----------
element_type : object
A dtype with which represents the element types in the list.
Attributes
----------
element_type
leaf_type
Methods
-------
from_arrow
to_arrow
Examples
... | ListDtype |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.