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 | pypa__installer | tests/test_utils.py | {
"start": 3813,
"end": 4061
} | class ____:
def test_basic_functionality(self):
data = b"input data is this"
size = len(data)
with BytesIO(data) as source:
result = get_stream_length(source)
assert result == size
| TestGetStreamLength |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 20655,
"end": 21070
} | class ____(_CReferenceDeclaratorBaseNode):
def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False):
if base_type.is_pyobject:
error(self.pos, "Reference base type cannot be a Python object")
ref_type = PyrexTypes.c_ref_type(base_type)
return self.base.analyse... | CReferenceDeclaratorNode |
python | jazzband__django-waffle | waffle/tests/test_management.py | {
"start": 9177,
"end": 10948
} | class ____(TestCase):
def test_create(self):
""" The command should create a new switch. """
name = 'test'
call_command('waffle_switch', name, 'on', create=True)
switch = get_waffle_switch_model().objects.get(name=name, active=True)
switch.delete()
call_command('waf... | WaffleSwitchManagementCommandTests |
python | sympy__sympy | sympy/combinatorics/rewritingsystem_fsm.py | {
"start": 0,
"end": 1276
} | class ____:
'''
A representation of a state managed by a ``StateMachine``.
Attributes:
name (instance of FreeGroupElement or string) -- State name which is also assigned to the Machine.
transisitons (OrderedDict) -- Represents all the transitions of the state object.
state_type (str... | State |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_storage_transfer_service.py | {
"start": 48320,
"end": 55207
} | class ____:
def test_constructor(self):
operator = CloudDataTransferServiceGCSToGCSOperator(
task_id=TASK_ID,
source_bucket=GCS_BUCKET_NAME,
destination_bucket=GCS_BUCKET_NAME,
project_id=GCP_PROJECT_ID,
description=DESCRIPTION,
schedul... | TestGoogleCloudStorageToGoogleCloudStorageTransferOperator |
python | redis__redis-py | redis/commands/search/field.py | {
"start": 2123,
"end": 2982
} | class ____(Field):
"""
TextField is used to define a text field in a schema definition
"""
NOSTEM = "NOSTEM"
PHONETIC = "PHONETIC"
def __init__(
self,
name: str,
weight: float = 1.0,
no_stem: bool = False,
phonetic_matcher: str = None,
withsuffix... | TextField |
python | getsentry__sentry | tests/sentry/integrations/vercel/test_integration.py | {
"start": 20892,
"end": 22349
} | class ____(TestCase):
def test_asdict(self) -> None:
assert metadata.asdict() == {
"description": "Vercel is an all-in-one platform with Global CDN supporting static & JAMstack deployment and Serverless Functions.",
"features": [
{
"description": ... | VercelIntegrationMetadataTest |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 26132,
"end": 27791
} | class ____(Request):
"""
Deletes a queue. If the queue is not empty and force is not set to true, queue will not be deleted.
:param queue: Queue id
:type queue: str
:param force: Force delete of non-empty queue. Defaults to false
:type force: bool
"""
_service = "queues"
_action = ... | DeleteRequest |
python | getsentry__sentry | src/sentry/api/endpoints/organization_metrics_meta.py | {
"start": 2639,
"end": 4535
} | class ____(OrganizationEventsEndpointBase):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
"""Return the total sum of metrics data, the null transactions and unparameterized transactions
This is so the frontend can have an idea given its current selection of projects how good/bad the dis... | OrganizationMetricsCompatibilitySums |
python | getsentry__sentry | src/sentry/integrations/services/assignment_source.py | {
"start": 353,
"end": 1230
} | class ____:
source_name: str
integration_id: int
queued: datetime = timezone.now()
@classmethod
def from_integration(cls, integration: Integration | RpcIntegration) -> AssignmentSource:
return AssignmentSource(
source_name=integration.name,
integration_id=integration... | AssignmentSource |
python | run-llama__llama_index | llama-index-integrations/protocols/llama-index-protocols-ag-ui/llama_index/protocols/ag_ui/events.py | {
"start": 1154,
"end": 1262
} | class ____(ToolCallArgsEvent, Event):
type: EventType = EventType.TOOL_CALL_ARGS
| ToolCallArgsWorkflowEvent |
python | kamyu104__LeetCode-Solutions | Python/longest-word-with-all-prefixes.py | {
"start": 98,
"end": 1126
} | class ____(object):
def longestWord(self, words):
"""
:type words: List[str]
:rtype: str
"""
def iter_dfs(words, node):
result = -1
stk = [node]
while stk:
node = stk.pop()
if result == -1 or len(words[node["... | Solution |
python | falconry__falcon | tests/test_buffered_reader.py | {
"start": 150,
"end": 420
} | class ____(io.BytesIO):
def read(self, size=None):
if size is None or size == -1:
raise WouldHang('unbounded read()')
result = super().read(size)
if not result:
raise WouldHang('EOF')
return result
| GlitchyStream |
python | kamyu104__LeetCode-Solutions | Python/set-intersection-size-at-least-two.py | {
"start": 33,
"end": 625
} | class ____(object):
def intersectionSizeTwo(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
intervals.sort(key = lambda s_e: (s_e[0], -s_e[1]))
cnts = [2] * len(intervals)
result = 0
while intervals:
(start, _), cnt =... | Solution |
python | google__pytype | pytype/pytd/booleq.py | {
"start": 5705,
"end": 7054
} | class ____(BooleanTerm):
"""A conjunction of equalities and disjunctions.
External code should use And rather than creating an _And instance directly.
"""
__slots__ = ("exprs",)
def __init__(self, exprs):
"""Initialize a conjunction.
Args:
exprs: A set. The subterms.
"""
self.exprs =... | _And |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 19130,
"end": 20482
} | class ____(
OfflineCompressTestCaseWithContextGenerator
):
"""
Test that the offline manifest is independent of STATIC_URL.
I.e. users can use the manifest with any other STATIC_URL in the future.
"""
templates_dir = "test_static_url_independence"
expected_hash = "b0bfc3754fd4"
addition... | OfflineCompressStaticUrlIndependenceTestCase |
python | kubernetes-client__python | kubernetes/client/models/v1_mutating_webhook.py | {
"start": 383,
"end": 23045
} | 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... | V1MutatingWebhook |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 803460,
"end": 826821
} | class ____(FieldChannelMixin, core.PositionFieldDefBase):
r"""
Theta schema wrapper.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :cla... | Theta |
python | pyca__cryptography | src/cryptography/hazmat/primitives/asymmetric/ec.py | {
"start": 9485,
"end": 9704
} | class ____(EllipticCurve):
name = "brainpoolP384r1"
key_size = 384
group_order = 0x8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565 # noqa: E501
| BrainpoolP384R1 |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 52083,
"end": 52506
} | class ____(TypedDict, total=False):
type: Required[Literal['include-exclude-sequence']]
include: set[int]
exclude: set[int]
def filter_seq_schema(*, include: set[int] | None = None, exclude: set[int] | None = None) -> IncExSeqSerSchema:
return _dict_not_none(type='include-exclude-sequence', include=in... | IncExSeqSerSchema |
python | mlflow__mlflow | mlflow/genai/judges/optimizers/dspy_utils.py | {
"start": 3156,
"end": 12276
} | class ____(dspy.BaseLM):
"""Special DSPy LM for Databricks environment using managed RAG client."""
def __init__(self):
super().__init__("databricks")
def dump_state(self):
return {}
def load_state(self, state):
pass
def forward(
self, prompt: str | None = None, m... | AgentEvalLM |
python | donnemartin__interactive-coding-challenges | staging/graphs_trees/binary_tree/test_binary_search_tree.py | {
"start": 17,
"end": 2238
} | class ____(unittest.TestCase):
def test_insert_traversals (self):
myTree = BinaryTree()
myTree2 = BinaryTree()
for num in [50, 30, 70, 10, 40, 60, 80, 7, 25, 38]:
myTree.insert(num)
[myTree2.insert(num) for num in range (1, 100, 10)]
print("Test: insert checking with in order traversal")
expectVal = [... | TestBinaryTree |
python | ansible__ansible | lib/ansible/modules/package_facts.py | {
"start": 13350,
"end": 17328
} | class ____(CLIMgr):
CLI = 'pkg_info'
def list_installed(self):
rc, out, err = module.run_command([self._cli, '-a'])
if rc != 0 or err:
raise Exception("Unable to list packages rc=%s : %s" % (rc, err))
return out.splitlines()
def get_package_details(self, package):
... | PKG_INFO |
python | tiangolo__fastapi | docs_src/path_operation_configuration/tutorial002_py39.py | {
"start": 104,
"end": 575
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
tags: set[str] = set()
@app.post("/items/", response_model=Item, tags=["items"])
async def create_item(item: Item):
return item
@app.get("/items/", tags=["items"])
async def read... | Item |
python | dagster-io__dagster | examples/project_analytics/dagster_pypi/resources.py | {
"start": 803,
"end": 942
} | class ____(ConfigurableResource):
def get_pypi_download_counts(self, _) -> pd.DataFrame:
raise NotImplementedError()
| PyPiResource |
python | pytorch__pytorch | torch/cpu/amp/grad_scaler.py | {
"start": 84,
"end": 958
} | class ____(torch.amp.GradScaler):
r"""
See :class:`torch.amp.GradScaler`.
``torch.cpu.amp.GradScaler(args...)`` is deprecated. Please use ``torch.amp.GradScaler("cpu", args...)`` instead.
"""
@deprecated(
"`torch.cpu.amp.GradScaler(args...)` is deprecated. "
"Please use `torch.amp.G... | GradScaler |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 11611,
"end": 11752
} | class ____(_TestIDCTBase):
def setup_method(self):
self.rdt = np.float32
self.dec = 5
self.type = 2
| TestIDCTIIFloat |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 66460,
"end": 67820
} | class ____(TypedDict, total=False):
"""
:class:`altair.BindInput` ``TypedDict`` wrapper.
Parameters
----------
autocomplete
A hint for form autofill. See the `HTML autocomplete attribute
<https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete>`__ for
addit... | BindInputKwds |
python | mahmoud__boltons | boltons/dictutils.py | {
"start": 3798,
"end": 23160
} | class ____(dict):
"""A MultiDict is a dictionary that can have multiple values per key
and the OrderedMultiDict (OMD) is a MultiDict that retains
original insertion order. Common use cases include:
* handling query strings parsed from URLs
* inverting a dictionary to create a reverse index (val... | OrderedMultiDict |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_multiple_wrapping.py | {
"start": 1102,
"end": 2450
} | class ____(FSDPTest):
@skip_if_lt_x_gpu(2)
def test_multiple_wrapping(self, device):
"""
This test simulates wrapping the module after training to run inference.
This is required in cases where later in a session, the model is wrapped again in FSDP but
contains nested FSDP wrappe... | TestMultipleWrapping |
python | doocs__leetcode | solution/2000-2099/2042.Check if Numbers Are Ascending in a Sentence/Solution.py | {
"start": 0,
"end": 264
} | class ____:
def areNumbersAscending(self, s: str) -> bool:
pre = 0
for t in s.split():
if t[0].isdigit():
if (cur := int(t)) <= pre:
return False
pre = cur
return True
| Solution |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/templates_test.py | {
"start": 1376,
"end": 1844
} | class ____(gast.NodeTransformer):
def __init__(self, test_instance, expected_ctx):
self.at_top_level = True
self.test_instance = test_instance
self.expected_ctx = expected_ctx
def visit(self, node):
if hasattr(node, 'ctx'):
self.test_instance.assertIsInstance(node.ctx, self.expected_ctx)
... | _CtxChecker |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/assets.py | {
"start": 651,
"end": 808
} | class ____(graphene.Union):
class Meta:
types = (GrapheneAssetConnection, GraphenePythonError)
name = "AssetsOrError"
| GrapheneAssetsOrError |
python | pypa__warehouse | warehouse/oidc/interfaces.py | {
"start": 457,
"end": 1746
} | class ____(Interface):
def verify_jwt_signature(
unverified_token: str, issuer_url: str
) -> SignedClaims | None:
"""
Verify the given JWT's signature, returning its signed claims if
valid. If the signature is invalid, `None` is returned.
This method does **not** verify ... | IOIDCPublisherService |
python | spack__spack | lib/spack/spack/spec.py | {
"start": 223048,
"end": 223154
} | class ____(spack.error.SpecError):
"""Called for errors in Spec format strings."""
| SpecFormatStringError |
python | great-expectations__great_expectations | tests/datasource/fluent/test_batch.py | {
"start": 5101,
"end": 6389
} | class ____:
@pytest.fixture
def expectation(self) -> Expectation:
return gxe.ExpectColumnValuesToNotBeNull(column="vendor_id", mostly=0.95)
@pytest.mark.filesystem
def test_boolean_validation_result(
self,
pandas_setup: Tuple[AbstractDataContext, Batch],
expectation: Exp... | TestBatchValidateExpectation |
python | walkccc__LeetCode | solutions/3112. Minimum Time to Visit Disappearing Nodes/3112.py | {
"start": 0,
"end": 855
} | class ____:
def minimumTime(
self,
n: int,
edges: list[list[int]],
disappear: list[int],
) -> list[int]:
graph = [[] for _ in range(n)]
for u, v, w in edges:
graph[u].append((v, w))
graph[v].append((u, w))
return self._dijkstra(graph, 0, disappear)
def _dijkstra(... | Solution |
python | openai__openai-python | src/openai/types/realtime/realtime_session_create_request.py | {
"start": 588,
"end": 5219
} | class ____(BaseModel):
type: Literal["realtime"]
"""The type of session to create. Always `realtime` for the Realtime API."""
audio: Optional[RealtimeAudioConfig] = None
"""Configuration for input and output audio."""
include: Optional[List[Literal["item.input_audio_transcription.logprobs"]]] = No... | RealtimeSessionCreateRequest |
python | doocs__leetcode | solution/2900-2999/2950.Number of Divisible Substrings/Solution.py | {
"start": 0,
"end": 465
} | class ____:
def countDivisibleSubstrings(self, word: str) -> int:
d = ["ab", "cde", "fgh", "ijk", "lmn", "opq", "rst", "uvw", "xyz"]
mp = {}
for i, s in enumerate(d, 1):
for c in s:
mp[c] = i
ans = 0
n = len(word)
for i in range(n):
... | Solution |
python | tensorflow__tensorflow | tensorflow/python/eager/gradient_input_output_exclusions_test.py | {
"start": 980,
"end": 1977
} | class ____(test.TestCase):
def testGeneratedFileMatchesHead(self):
expected_contents = gradient_input_output_exclusions.get_contents()
filename = os.path.join(
resource_loader.get_root_dir_with_all_resources(),
resource_loader.get_path_to_datafile("pywrap_gradient_exclusions.cc"))
actual_... | GradientInputOutputExclusionsTest |
python | marshmallow-code__marshmallow | src/marshmallow/fields.py | {
"start": 60446,
"end": 61069
} | class ____(String):
"""An email field.
:param args: The same positional arguments that :class:`String` receives.
:param kwargs: The same keyword arguments that :class:`String` receives.
"""
#: Default error messages.
default_error_messages = {"invalid": "Not a valid email address."}
def _... | Email |
python | pyodide__pyodide | tools/backport.py | {
"start": 4507,
"end": 6137
} | class ____:
"""A paragraph grouping of changelog entries separated by blank lines.
Introduced by a line starting with a -. Ended by a blank line, or ### or ##.
header:
Probably empty?
entries:
The list of entries.
cur_entry:
Parser state.
"""
header: list[str] = ... | ChangelogParagraph |
python | Textualize__textual | tests/command_palette/test_click_away.py | {
"start": 94,
"end": 303
} | class ____(Provider):
async def search(self, query: str) -> Hits:
def goes_nowhere_does_nothing() -> None:
pass
yield Hit(1, query, goes_nowhere_does_nothing, query)
| SimpleSource |
python | apache__airflow | task-sdk/tests/task_sdk/definitions/test_operator_resources.py | {
"start": 890,
"end": 1616
} | class ____:
def test_resource_eq(self):
r = Resources(cpus=0.1, ram=2048)
assert r not in [{}, [], None]
assert r == r
r2 = Resources(cpus=0.1, ram=2048)
assert r == r2
assert r2 == r
r3 = Resources(cpus=0.2, ram=2048)
assert r != r3
def test_to... | TestResources |
python | sympy__sympy | sympy/integrals/transforms.py | {
"start": 36021,
"end": 38727
} | class ____(FourierTypeTransform):
"""
Class representing unevaluated inverse Fourier transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse Fourier transforms, see the
:func:`inverse_fourier_transform` docstring.
"""
_name = 'Inverse ... | InverseFourierTransform |
python | pandas-dev__pandas | pandas/tests/io/parser/test_textreader.py | {
"start": 834,
"end": 12091
} | class ____:
@pytest.fixture
def csv_path(self, datapath):
return datapath("io", "data", "csv", "test1.csv")
def test_file_handle(self, csv_path):
with open(csv_path, "rb") as f:
reader = TextReader(f, **_na_value_kwargs)
reader.read()
def test_file_handle_mmap(s... | TestTextReader |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_geometry_distance_to_address_to_be_between.py | {
"start": 6883,
"end": 13675
} | class ____(ColumnMapExpectation):
"""Expect that column values as geometry points to be between a certain distance from a geocoded object.
expect_column_values_geometry_distance_to_address_to_be_between is a \
[Column Map Expectation](https://docs.greatexpectations.io/docs/guides/expectations/creating_cust... | ExpectColumnValuesGeometryDistanceToAddressToBeBetween |
python | Textualize__textual | src/textual/demo/widgets.py | {
"start": 19599,
"end": 20474
} | class ____(containers.VerticalGroup):
DEFAULT_CLASSES = "column"
TREES_MD = """\
## Tree
The Tree widget displays hierarchical data.
There is also the Tree widget's cousin, DirectoryTree, to navigate folders and files on the filesystem.
"""
DEFAULT_CSS = """
Trees {
Tree {
heig... | Trees |
python | skorch-dev__skorch | skorch/tests/callbacks/test_scoring.py | {
"start": 31727,
"end": 34879
} | class ____:
"""This test is about the possibility to control cache usage globally
See this issue for more context:
https://github.com/skorch-dev/skorch/issues/957
"""
@pytest.fixture
def net_cls(self):
from skorch import NeuralNetClassifier
return NeuralNetClassifier
@pyte... | TestScoringCacheGlobalControl |
python | pypa__setuptools | setuptools/command/alias.py | {
"start": 365,
"end": 2380
} | class ____(option_base):
"""Define a shortcut that invokes one or more commands"""
description = "define a shortcut to invoke one or more commands"
command_consumes_arguments = True
user_options = [
('remove', 'r', 'remove (unset) the alias'),
] + option_base.user_options
boolean_opti... | alias |
python | allegroai__clearml | clearml/backend_api/services/v2_23/queues.py | {
"start": 65829,
"end": 70427
} | class ____(Request):
"""
Returns metrics of the company queues. The metrics are avaraged in the specified interval.
:param from_date: Starting time (in seconds from epoch) for collecting metrics
:type from_date: float
:param to_date: Ending time (in seconds from epoch) for collecting metrics
:t... | GetQueueMetricsRequest |
python | huggingface__transformers | src/transformers/loss/loss_grounding_dino.py | {
"start": 2444,
"end": 5842
} | class ____(HungarianMatcher):
@torch.no_grad()
def forward(self, outputs, targets):
"""
Args:
outputs (`dict`):
A dictionary that contains at least these entries:
* "logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification ... | GroundingDinoHungarianMatcher |
python | openai__openai-python | src/openai/types/chat/completion_create_params.py | {
"start": 15341,
"end": 15887
} | class ____(TypedDict, total=False):
city: str
"""Free text input for the city of the user, e.g. `San Francisco`."""
country: str
"""
The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of
the user, e.g. `US`.
"""
region: str
"""Free text input for the region... | WebSearchOptionsUserLocationApproximate |
python | django__django | tests/staticfiles_tests/test_management.py | {
"start": 2153,
"end": 5073
} | class ____(TestDefaults, CollectionTestCase):
"""
Test ``findstatic`` management command.
"""
def _get_file(self, filepath):
path = call_command(
"findstatic", filepath, all=False, verbosity=0, stdout=StringIO()
)
with open(path, encoding="utf-8") as f:
r... | TestFindStatic |
python | simonw__datasette | datasette/permissions.py | {
"start": 3739,
"end": 3923
} | class ____(NamedTuple):
"""A resource with the reason it was allowed (for debugging)."""
resource: Resource
reason: str
@dataclass(frozen=True, kw_only=True)
| AllowedResource |
python | django__django | tests/project_template/test_settings.py | {
"start": 152,
"end": 1704
} | class ____(SimpleTestCase):
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(self.temp_dir.cleanup)
template_settings_py = os.path.join(
os.path.dirname(conf.__file__),
"project_template",
"project_name",
"settings... | TestStartProjectSettings |
python | getsentry__sentry | src/sentry/integrations/vercel/webhook.py | {
"start": 4784,
"end": 18106
} | class ____(Endpoint):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"DELETE": ApiPublishStatus.PRIVATE,
"POST": ApiPublishStatus.PRIVATE,
}
authentication_classes = ()
permission_classes = ()
provider = "vercel"
@csrf_exempt
def dispatch(self, request: HttpRequest, *a... | VercelWebhookEndpoint |
python | tensorflow__tensorflow | tensorflow/python/distribute/distribute_coordinator_test.py | {
"start": 34373,
"end": 36185
} | class ____(test.TestCase):
def test_std_server_arguments(self):
cs = {"worker": ["fake_worker"], "ps": ["fake_ps"]}
tf_config = {"cluster": cs, "task": {"type": "ps", "id": 0}}
def _mock_run_std_server(cluster_spec=None,
task_type=None,
task_id=N... | RunStandardTensorflowServerTest |
python | pytorch__pytorch | test/test_overrides.py | {
"start": 46546,
"end": 47333
} | class ____(TestCase):
""" test for gh-37141 """
def test_broadcast_all(self):
from torch.distributions.utils import broadcast_all
a = torch.tensor([1.2, 3.4, 5.6])
a_w = Wrapper(a)
b = torch.tensor(5.0)
b_w = Wrapper(b)
c = torch.tensor([5.0, 5.0, 5.0])
o... | TestBroadcastAllOverride |
python | django__django | tests/model_inheritance_regress/models.py | {
"start": 3657,
"end": 3747
} | class ____(models.Model):
keywords = models.CharField(max_length=255)
| SearchableLocation |
python | walkccc__LeetCode | solutions/915. Partition Array into Disjoint Intervals/915.py | {
"start": 0,
"end": 326
} | class ____:
def partitionDisjoint(self, nums: list[int]) -> int:
n = len(nums)
mn = [0] * (n - 1) + [nums[-1]]
mx = -math.inf
for i in range(n - 2, - 1, -1):
mn[i] = min(mn[i + 1], nums[i])
for i, num in enumerate(nums):
mx = max(mx, num)
if mx <= mn[i + 1]:
return i + ... | Solution |
python | astropy__astropy | astropy/io/votable/__init__.py | {
"start": 846,
"end": 1254
} | class ____(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.io.votable`.
"""
verify = _config.ConfigItem(
VERIFY_OPTIONS,
"Can be 'exception' (treat fixable violations of the VOTable spec as "
"exceptions), 'warn' (show warnings for VOTable spec violations), o... | Conf |
python | Lightning-AI__lightning | src/lightning/pytorch/callbacks/stochastic_weight_avg.py | {
"start": 1413,
"end": 17872
} | class ____(Callback):
def __init__(
self,
swa_lrs: Union[float, list[float]],
swa_epoch_start: Union[int, float] = 0.8,
annealing_epochs: int = 10,
annealing_strategy: Literal["cos", "linear"] = "cos",
avg_fn: Optional[_AVG_FN] = None,
device: Optional[Union[t... | StochasticWeightAveraging |
python | kamyu104__LeetCode-Solutions | Python/describe-the-painting.py | {
"start": 54,
"end": 632
} | class ____(object):
def splitPainting(self, segments):
"""
:type segments: List[List[int]]
:rtype: List[List[int]]
"""
counts = collections.defaultdict(int)
for s, e, c in segments:
counts[s] += c
counts[e] -= c
points = sorted(x for x ... | Solution |
python | coleifer__peewee | tests/fields.py | {
"start": 27636,
"end": 27728
} | class ____(TestModel):
price = IntegerField()
multiplier = FloatField(default=1.)
| Item |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-lancedb/tests/test_vector_stores_lancedb.py | {
"start": 804,
"end": 888
} | class ____(LanceModel):
text: str
id_: str
vector: Vector(dim=3)
| TestModel |
python | django-guardian__django-guardian | guardian/testapp/tests/test_backend_integration.py | {
"start": 541,
"end": 3448
} | class ____(TestCase):
"""Test that the backend integrates correctly with Django's auth system"""
def setUp(self):
self.user = User.objects.create_user(username="testuser", password="testpass")
self.superuser = User.objects.create_superuser(username="superuser", password="superpass")
sel... | BackendIntegrationTest |
python | scipy__scipy | scipy/stats/tests/test_morestats.py | {
"start": 114220,
"end": 122436
} | class ____:
def test_fixed_lmbda(self):
rng = np.random.RandomState(12345)
# Test positive input
x = _old_loggamma_rvs(5, size=50, random_state=rng) + 5
assert np.all(x > 0)
xt = stats.yeojohnson(x, lmbda=1)
assert_allclose(xt, x)
xt = stats.yeojohnson(x, lm... | TestYeojohnson |
python | wandb__wandb | wandb/integration/sb3/sb3.py | {
"start": 1469,
"end": 4797
} | class ____(BaseCallback):
"""Callback for logging experiments to Weights and Biases.
Log SB3 experiments to Weights and Biases
- Added model tracking and uploading
- Added complete hyperparameters recording
- Added gradient logging
- Note that `wandb.init(...)` must be called be... | WandbCallback |
python | wandb__wandb | wandb/apis/public/integrations.py | {
"start": 2389,
"end": 2695
} | class ____(Integrations):
"""A lazy iterator of `WebhookIntegration` objects.
<!-- lazydoc-ignore-class: internal -->
"""
def _convert(self, node: IntegrationFields) -> WebhookIntegration:
return node if (node.typename__ == "GenericWebhookIntegration") else None
| WebhookIntegrations |
python | Textualize__textual | src/textual/lazy.py | {
"start": 1966,
"end": 4329
} | class ____(Widget):
"""Similar to [Lazy][textual.lazy.Lazy], but mounts children sequentially.
This is useful when you have so many child widgets that there is a noticeable delay before
you see anything. By mounting the children over several frames, the user will feel that
something is happening.
... | Reveal |
python | pytorch__pytorch | torch/distributed/fsdp/_exec_order_utils.py | {
"start": 668,
"end": 16168
} | class ____:
"""
This contains the data structures to track the execution order. We track
the pre-forward order on the *first* iteration for forward prefetching
(which thus assumes static graph) and the post-forward order on *every*
iteration for backward prefetching (which thus does not assume stati... | _ExecOrderData |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_column_values_to_be_equal_to_or_greater_than_profile_min.py | {
"start": 864,
"end": 2735
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.greater_than_or_equal_to_profile_min"
condition_value_keys = ("profile",)
# This method implements the core logic for the PandasExecutionEngine
@column_co... | ColumnValuesGreaterThanOrEqualToProfileMin |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec11.py | {
"start": 198,
"end": 731
} | class ____(Generic[_P, _R]):
def __init__(self, function: Callable[_P, _R]):
self.function = function
def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
print("Inside Function Call")
return self.function(*args, **kwargs)
def do_stuff(self, name: str, *args: _P.args, **k... | MyDecorator |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 274858,
"end": 276027
} | class ____(
ConditionalValueDefstringnullExprRef
):
"""
ConditionalParameterValueDefstringnullExprRef schema wrapper.
Parameters
----------
param : str, :class:`ParameterName`
Filter using a parameter name.
value : str, dict, :class:`ExprRef`, None
A constant value in visual... | ConditionalParameterValueDefstringnullExprRef |
python | getsentry__sentry | tests/sentry/grouping/test_grouphash_metadata.py | {
"start": 7017,
"end": 8635
} | class ____(TestCase):
def test_check_grouphashes_for_positive_fingerprint_match(self) -> None:
grouphash1 = GroupHash.objects.create(hash="dogs", project_id=self.project.id)
grouphash2 = GroupHash.objects.create(hash="are great", project_id=self.project.id)
for fingerprint1, fingerprint2, e... | GroupHashMetadataTest |
python | tensorflow__tensorflow | tensorflow/python/autograph/core/config_lib.py | {
"start": 1085,
"end": 1158
} | class ____(enum.Enum):
NONE = 0
CONVERT = 1
DO_NOT_CONVERT = 2
| Action |
python | facelessuser__pymdown-extensions | pymdownx/saneheaders.py | {
"start": 541,
"end": 965
} | class ____(Extension):
"""Adds the sane headers extension."""
def extendMarkdown(self, md):
"""Extend the inline and block processor objects."""
md.parser.blockprocessors.register(SaneHeadersProcessor(md.parser), 'hashheader', 70)
md.registerExtension(self)
def makeExtension(*args, *... | SaneHeadersExtension |
python | google__pytype | pytype/rewrite/abstract/functions_test.py | {
"start": 2875,
"end": 4883
} | class ____(test_utils.ContextfulTestBase):
def test_init(self):
func_code = _get_const("""
def f(x, /, *args, y, **kwargs):
pass
""")
f = functions.InterpreterFunction(
ctx=self.ctx, name='f', code=func_code, enclosing_scope=(),
parent_frame=FakeFrame(self.ctx))
self.ass... | InterpreterFunctionTest |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/git_sparsepaths_version/package.py | {
"start": 217,
"end": 503
} | class ____(Package):
"""Mock package with git_sparse_paths attribute"""
homepage = "http://www.git-fetch-example.com"
git = "https://a/really.com/big/repo.git"
version("1.0", tag="v1.0", git_sparse_paths=["foo", "bar"])
version("0.9", tag="v0.9")
| GitSparsepathsVersion |
python | PrefectHQ__prefect | src/prefect/concurrency/v1/context.py | {
"start": 229,
"end": 1107
} | class ____(ContextModel):
__var__: ClassVar[ContextVar[Self]] = ContextVar("concurrency_v1")
# Track the limits that have been acquired but were not able to be released
# due to cancellation or some other error. These limits are released when
# the context manager exits.
cleanup_slots: list[tuple[l... | ConcurrencyContext |
python | django__django | tests/admin_inlines/tests.py | {
"start": 70421,
"end": 74820
} | class ____(TestDataMixin, TestCase):
def setUp(self):
self.client.force_login(self.superuser)
@override_settings(DEBUG=True)
def test_fieldset_context_fully_set(self):
url = reverse("admin:admin_inlines_photographer_add")
with self.assertRaisesMessage(AssertionError, "no logs"):
... | TestInlineWithFieldsets |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_be_valid_github_username.py | {
"start": 560,
"end": 1898
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_github_username"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _p... | ColumnValuesToBeValidGithubUsername |
python | scikit-learn__scikit-learn | examples/miscellaneous/plot_metadata_routing.py | {
"start": 23907,
"end": 24849
} | class ____(MetaEstimatorMixin, RegressorMixin, BaseEstimator):
def __init__(self, estimator):
self.estimator = estimator
def fit(self, X, y, **fit_params):
routed_params = process_routing(self, "fit", **fit_params)
self.estimator_ = clone(self.estimator).fit(X, y, **routed_params.estima... | MetaRegressor |
python | kamyu104__LeetCode-Solutions | Python/n-repeated-element-in-size-2n-array.py | {
"start": 29,
"end": 290
} | class ____(object):
def repeatedNTimes(self, A):
"""
:type A: List[int]
:rtype: int
"""
for i in xrange(2, len(A)):
if A[i-1] == A[i] or A[i-2] == A[i]:
return A[i]
return A[0]
| Solution |
python | realpython__materials | python-property/circle_v1.py | {
"start": 0,
"end": 480
} | class ____:
def __init__(self, radius):
self._radius = radius
def _get_radius(self):
print("Get radius")
return self._radius
def _set_radius(self, value):
print("Set radius")
self._radius = value
def _del_radius(self):
print("Delete radius")
del... | Circle |
python | fluentpython__example-code | attic/sequences/slice_viewer.py | {
"start": 531,
"end": 603
} | class ____:
def __getitem__(self, position):
return position
| SliceViewer |
python | bokeh__bokeh | src/bokeh/models/glyphs.py | {
"start": 46554,
"end": 47842
} | class ____(XYGlyph, LineGlyph):
''' Render step lines.
Step levels can be draw before, after, or centered on each point, according
to the value of the ``mode`` property.
The x-coordinates are assumed to be (and must be) sorted in ascending order
for steps to be properly rendered.
'''
# e... | Step |
python | numpy__numpy | numpy/distutils/fcompiler/intel.py | {
"start": 996,
"end": 2654
} | class ____(BaseIntelFCompiler):
compiler_type = 'intel'
compiler_aliases = ('ifort',)
description = 'Intel Fortran Compiler for 32-bit apps'
version_match = intel_version_match('32-bit|IA-32')
possible_executables = ['ifort', 'ifc']
executables = {
'version_cmd' : None, # se... | IntelFCompiler |
python | kubernetes-client__python | kubernetes/client/api/admissionregistration_v1beta1_api.py | {
"start": 543,
"end": 190008
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | AdmissionregistrationV1beta1Api |
python | neetcode-gh__leetcode | python/0015-3sum.py | {
"start": 0,
"end": 803
} | class ____:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for i, a in enumerate(nums):
# Skip positive integers
if a > 0:
break
if i > 0 and a == nums[i - 1]:
continue
l, r = i +... | Solution |
python | getsentry__sentry | src/sentry/sentry_apps/api/serializers/platform_external_issue.py | {
"start": 360,
"end": 540
} | class ____(TypedDict):
id: str
issueId: str
serviceType: str
displayName: str
webUrl: str
@register(PlatformExternalIssue)
| PlatformExternalIssueSerializerResponse |
python | kamyu104__LeetCode-Solutions | Python/properties-graph.py | {
"start": 1166,
"end": 2474
} | class ____(object):
def numberOfComponents(self, properties, k):
"""
:type properties: List[List[int]]
:type k: int
:rtype: int
"""
class UnionFind(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = range(n)
... | Solution2 |
python | spyder-ide__spyder | spyder/plugins/shortcuts/plugin.py | {
"start": 1292,
"end": 1468
} | class ____:
ShortcutSummaryAction = "show_shortcut_summary_action"
# --- Plugin
# ----------------------------------------------------------------------------
| ShortcutActions |
python | h5py__h5py | h5py/tests/test_vds/test_highlevel_vds.py | {
"start": 468,
"end": 2341
} | class ____(ut.TestCase):
def setUp(self):
self.working_dir = tempfile.mkdtemp()
self.fname = ['raw_file_1.h5', 'raw_file_2.h5', 'raw_file_3.h5']
for k, outfile in enumerate(self.fname):
filename = osp.join(self.working_dir, outfile)
f = h5.File(filename, 'w')
... | TestEigerHighLevel |
python | kamyu104__LeetCode-Solutions | Python/print-foobar-alternately.py | {
"start": 48,
"end": 1065
} | class ____(object):
def __init__(self, n):
self.__n = n
self.__curr = False
self.__cv = threading.Condition()
def foo(self, printFoo):
"""
:type printFoo: method
:rtype: void
"""
for i in xrange(self.__n):
with self.__cv:
... | FooBar |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis36.py | {
"start": 315,
"end": 1397
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis36.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | py-pdf__pypdf | pypdf/constants.py | {
"start": 7814,
"end": 8011
} | class ____:
"""§8.9.7 of the 1.7 and 2.0 references."""
AHx = "/AHx"
A85 = "/A85"
LZW = "/LZW"
FL = "/Fl"
RL = "/RL"
CCF = "/CCF"
DCT = "/DCT"
| FilterTypeAbbreviations |
python | walkccc__LeetCode | solutions/1119. Remove Vowels from a String/1119.py | {
"start": 0,
"end": 95
} | class ____:
def removeVowels(self, s: str) -> str:
return re.sub('a|e|i|o|u', '', s)
| Solution |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/property_subclasses/my_models.py | {
"start": 2126,
"end": 2349
} | class ____(object):
def __init__(self, first, last=None):
assert isinstance(first, date)
assert last is None or isinstance(last, date)
self.first = first
self.last = last or first
| FuzzyDate |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.