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 | tensorflow__tensorflow | tensorflow/python/tpu/tpu_test.py | {
"start": 1624,
"end": 3136
} | class ____(test.TestCase):
def testIsInContext(self):
"""Test that control_flow_util can check that we're in a TPU context."""
with ops.Graph().as_default():
z1 = array_ops.identity(1)
pivot = control_flow_ops.no_op()
context = tpu_replication.TPUReplicateContext(
b"context", 1, p... | TPUContextTest |
python | Textualize__textual | tests/test_command.py | {
"start": 791,
"end": 1886
} | class ____(App):
"""An app with a modal dialog."""
BINDINGS = [("q", "request_quit", "Quit")]
def __init__(self) -> None:
self.check_quit_called = False
super().__init__()
def get_system_commands(self, screen: Screen) -> Iterable[SystemCommand]:
yield from super().get_system_c... | ModalApp |
python | getsentry__sentry | src/sentry/plugins/sentry_urls/apps.py | {
"start": 36,
"end": 250
} | class ____(AppConfig):
name = "sentry.plugins.sentry_urls"
def ready(self) -> None:
from sentry.plugins.base import register
from .models import UrlsPlugin
register(UrlsPlugin)
| Config |
python | pytorch__pytorch | torch/_dynamo/variables/builder.py | {
"start": 8901,
"end": 11782
} | class ____:
source: Source
# TODO: storing a SymInt here but not a FakeTensor is a pretty strange
# thing to do. Probably should have example (which stores an int) and
# fake_example
_example: Union[TensorWeakRef, torch.SymInt]
# When True, this indicates that this GraphArg is a Python quantity... | GraphArg |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 94407,
"end": 94525
} | class ____(BaseModel, extra="forbid"):
searches: List["QueryRequest"] = Field(..., description="")
| QueryRequestBatch |
python | pytorch__pytorch | torch/_export/serde/serialize.py | {
"start": 76861,
"end": 79442
} | class ____(metaclass=Final):
def __init__(
self,
opset_version: Optional[dict[str, int]] = None,
pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL,
):
self.opset_version: dict[str, int] = {}
if opset_version:
self.opset_version.update(opset_version)
if "a... | ExportedProgramSerializer |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/examples/parameter_server_test.py | {
"start": 2350,
"end": 3764
} | class ____:
def __init__(self, ps_rref):
self.ps_rref = ps_rref
self.loss_fn = nn.L1Loss()
def get_next_batch(self):
for _ in range(num_batches):
inputs = torch.randn(batch_size, in_features)
labels = torch.zeros(batch_size, out_features)
yield inputs... | Trainer |
python | PyCQA__pylint | tests/functional/r/regression/regression_infer_call_result_3690.py | {
"start": 107,
"end": 209
} | class ____:
@property
@classmethod
def func(cls):
pass
if Class.func:
pass
| Class |
python | python__mypy | mypy/types.py | {
"start": 21960,
"end": 25875
} | class ____(TypeVarLikeType):
"""Type that refers to a type variable."""
__slots__ = ("values", "variance")
values: list[Type] # Value restriction, empty list if no restriction
variance: int
def __init__(
self,
name: str,
fullname: str,
id: TypeVarId,
value... | TypeVarType |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-wordlift/llama_index/vector_stores/wordlift/base.py | {
"start": 1801,
"end": 8877
} | class ____(BasePydanticVectorStore):
stores_text: bool = True
_account: Optional[AccountInfo] = PrivateAttr(default=None)
_configuration: Configuration = PrivateAttr()
_fields: Optional[List[str]] = PrivateAttr()
def __init__(
self,
key: Optional[str] = None,
configuration:... | WordliftVectorStore |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_glue_catalog_partition.py | {
"start": 1130,
"end": 5967
} | class ____:
task_id = "test_glue_catalog_partition_sensor"
@mock_aws
@mock.patch.object(GlueCatalogHook, "check_for_partition")
def test_poke(self, mock_check_for_partition):
mock_check_for_partition.return_value = True
op = GlueCatalogPartitionSensor(task_id=self.task_id, table_name="t... | TestGlueCatalogPartitionSensor |
python | doocs__leetcode | solution/2100-2199/2172.Maximum AND Sum of Array/Solution.py | {
"start": 0,
"end": 443
} | class ____:
def maximumANDSum(self, nums: List[int], numSlots: int) -> int:
n = len(nums)
m = numSlots << 1
f = [0] * (1 << m)
for i in range(1 << m):
cnt = i.bit_count()
if cnt > n:
continue
for j in range(m):
if i ... | Solution |
python | getsentry__sentry | src/sentry/relay/types/rule_condition.py | {
"start": 609,
"end": 776
} | class ____(TypedDict):
"""Equality condition"""
op: Literal["eq"]
name: str
value: Value | None
options: NotRequired[EqConditionOptions]
| EqCondition |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-alephalpha/llama_index/embeddings/alephalpha/base.py | {
"start": 718,
"end": 8614
} | class ____(BaseEmbedding):
"""AlephAlphaEmbedding uses the Aleph Alpha API to generate embeddings for text."""
model: str = Field(
default=DEFAULT_ALEPHALPHA_MODEL, description="The Aleph Alpha model to use."
)
token: str = Field(default=None, description="The Aleph Alpha API token.")
repre... | AlephAlphaEmbedding |
python | PrefectHQ__prefect | src/prefect/logging/formatters.py | {
"start": 2203,
"end": 4167
} | class ____(logging.Formatter):
def __init__(
self,
format: str | None = None,
datefmt: str | None = None,
style: Literal["%", "{", "$"] = "%",
validate: bool = True,
*,
defaults: dict[str, Any] | None = None,
task_run_fmt: str | None = None,
fl... | PrefectFormatter |
python | django__django | tests/lookup/models.py | {
"start": 148,
"end": 325
} | class ____(models.Model):
desc = models.CharField(max_length=100)
time = models.TimeField()
def __str__(self):
return "%s (%s)" % (self.time, self.desc)
| Alarm |
python | numba__numba | numba/tests/test_listobject.py | {
"start": 25252,
"end": 26128
} | class ____(MemoryLeakMixin, TestCase):
"""Test list count. """
def test_list_count_empty(self):
@njit
def foo(i):
l = listobject.new_list(int32)
return l.count(i)
self.assertEqual(foo(10), 0)
def test_list_count_singleton(self):
@njit
def fo... | TestCount |
python | nedbat__coveragepy | coverage/misc.py | {
"start": 1760,
"end": 4481
} | class ____:
"""Saves the contents of sys.modules, and removes new modules later."""
def __init__(self) -> None:
self.old_modules = set(sys.modules)
def restore(self) -> None:
"""Remove any modules imported since this object started."""
new_modules = set(sys.modules) - self.old_modu... | SysModuleSaver |
python | ray-project__ray | rllib/examples/algorithms/bc/benchmark_rlunplugged_atari_pong_bc.py | {
"start": 1112,
"end": 12653
} | class ____(ConnectorV2):
def __init__(
self,
input_observation_space: Optional[gym.Space] = None,
input_action_space: Optional[gym.Space] = None,
*,
multi_agent: bool = False,
as_learner_connector: bool = True,
**kwargs,
):
"""Decodes observation f... | DecodeObservations |
python | mahmoud__boltons | boltons/tbutils.py | {
"start": 20872,
"end": 25012
} | class ____(ExceptionInfo):
"""The ContextualTracebackInfo type is a :class:`TracebackInfo`
subtype that uses the :class:`ContextualCallpoint` as its
frame-representing primitive.
It carries with it most of the exception information required to
recreate the widely recognizable "500" page for debuggi... | ContextualExceptionInfo |
python | keras-team__keras | keras/src/quantizers/quantizers_test.py | {
"start": 638,
"end": 23369
} | class ____(testing.TestCase):
def test_get_method(self):
quantizer = quantizers.get("abs_max_quantizer", axis=-1)
self.assertTrue(quantizer, quantizers.AbsMaxQuantizer)
quantizer = quantizers.get(None)
self.assertEqual(quantizer, None)
with self.assertRaises(ValueError):
... | QuantizersTest |
python | pypa__setuptools | setuptools/_vendor/backports/tarfile/__init__.py | {
"start": 23763,
"end": 23802
} | class ____(TarError):
pass
| FilterError |
python | apache__airflow | dev/breeze/src/airflow_breeze/params/shell_params.py | {
"start": 5023,
"end": 38577
} | class ____:
"""
Shell parameters. Those parameters are used to determine command issued to run shell command.
"""
airflow_branch: str = AIRFLOW_BRANCH
airflow_constraints_location: str = ""
airflow_constraints_mode: str = ALLOWED_CONSTRAINTS_MODES_CI[0]
airflow_constraints_reference: str = ... | ShellParams |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1038425,
"end": 1038924
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UpdateProjectV2ItemFieldValue"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "project_v2_item")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client... | UpdateProjectV2ItemFieldValuePayload |
python | getsentry__sentry | src/sentry/tasks/assemble.py | {
"start": 10602,
"end": 27474
} | class ____:
def __init__(
self,
assemble_result: AssembleResult,
organization: Organization,
release: str | None,
dist: str | None,
project_ids: list[int],
is_release_bundle_migration: bool = False,
):
self.assemble_result = assemble_result
... | ArtifactBundlePostAssembler |
python | scikit-learn__scikit-learn | sklearn/discriminant_analysis.py | {
"start": 8494,
"end": 29777
} | class ____(
ClassNamePrefixFeaturesOutMixin,
LinearClassifierMixin,
TransformerMixin,
BaseEstimator,
):
"""Linear Discriminant Analysis.
A classifier with a linear decision boundary, generated by fitting class
conditional densities to the data and using Bayes' rule.
The model fits a Ga... | LinearDiscriminantAnalysis |
python | walkccc__LeetCode | solutions/1446. Consecutive Characters/1446.py | {
"start": 0,
"end": 206
} | class ____:
def maxPower(self, s: str) -> int:
ans = 1
count = 1
for i in range(1, len(s)):
count = count + 1 if s[i] == s[i - 1] else 1
ans = max(ans, count)
return ans
| Solution |
python | getsentry__sentry | src/sentry/users/services/user/impl.py | {
"start": 1860,
"end": 15193
} | class ____(UserService):
def serialize_many(
self,
*,
filter: UserFilterArgs,
as_user: RpcUser | None = None,
auth_context: AuthenticationContext | None = None,
serializer: UserSerializeType | None = None,
) -> list[OpaqueSerializedResponse]:
return self._... | DatabaseBackedUserService |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_text.py | {
"start": 15394,
"end": 16812
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
super().__init__()
self.is_cross_attention = is_cross_attention
attention_class = Data2VecTextCrossAttention if is_cross_attention else Data2VecTextSelfAttention
self.self = ... | Data2VecTextAttention |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 35133,
"end": 35247
} | class ____(BaseModel, extra="forbid"):
drop_replica: "Replica" = Field(..., description="")
| DropReplicaOperation |
python | doocs__leetcode | solution/1100-1199/1162.As Far from Land as Possible/Solution.py | {
"start": 0,
"end": 639
} | class ____:
def maxDistance(self, grid: List[List[int]]) -> int:
n = len(grid)
q = deque((i, j) for i in range(n) for j in range(n) if grid[i][j])
ans = -1
if len(q) in (0, n * n):
return ans
dirs = (-1, 0, 1, 0, -1)
while q:
for _ in range(len... | Solution |
python | getsentry__sentry | src/sentry/grouping/component.py | {
"start": 16520,
"end": 17080
} | class ____(
BaseGroupingComponent[ContextLineGroupingComponent | FilenameGroupingComponent]
):
id: str = "template"
ContributingComponent = (
ChainedExceptionGroupingComponent
| ExceptionGroupingComponent
| StacktraceGroupingComponent
| ThreadsGroupingComponent
| CSPGroupingComponent
|... | TemplateGroupingComponent |
python | huggingface__transformers | src/transformers/cache_utils.py | {
"start": 14942,
"end": 21237
} | class ____(StaticLayer):
"""
A static cache layer that stores the key and value states as static tensors of shape
`[batch_size, num_heads, min(max_cache_len, sliding_window), head_dim]`. It lazily allocates its full backing
tensors, and then mutates them in-place. Built for `torch.compile` support.
... | StaticSlidingWindowLayer |
python | rapidsai__cudf | python/cudf/cudf/pandas/fast_slow_proxy.py | {
"start": 33408,
"end": 33528
} | class ____(FallbackError):
"""Raises when cuDF produces a MemoryError or an rmm.RMMError"""
pass
| OOMFallbackError |
python | huggingface__transformers | src/transformers/models/prompt_depth_anything/modeling_prompt_depth_anything.py | {
"start": 14574,
"end": 20153
} | class ____(PromptDepthAnythingPreTrainedModel):
_no_split_modules = ["DPTViTEmbeddings"]
def __init__(self, config):
super().__init__(config)
self.backbone = load_backbone(config)
self.neck = PromptDepthAnythingNeck(config)
self.head = PromptDepthAnythingDepthEstimationHead(con... | PromptDepthAnythingForDepthEstimation |
python | walkccc__LeetCode | solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.py | {
"start": 0,
"end": 900
} | class ____:
def findTheCity(
self,
n: int,
edges: list[list[int]],
distanceThreshold: int,
) -> int:
ans = -1
minCitiesCount = n
dist = self._floydWarshall(n, edges, distanceThreshold)
for i in range(n):
citiesCount = sum(dist[i][j] <= distanceThreshold for j in range(... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol8.py | {
"start": 299,
"end": 369
} | class ____(_BaseClass):
def __init__(self, my_str: str): ...
| _Class1 |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 231864,
"end": 235171
} | class ____(Request):
"""
Adds a task into a queue.
Fails if task state is not 'created'.
Fails if the following parameters in the task were not filled:
* execution.script.repository
* execution.script.entrypoint
:param queue: Queue id. If not provided, task is added to the default queu... | EnqueueRequest |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_resource_pool.py | {
"start": 383,
"end": 7818
} | 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... | V1beta2ResourcePool |
python | kamyu104__LeetCode-Solutions | Python/n-ary-tree-postorder-traversal.py | {
"start": 146,
"end": 578
} | class ____(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
result, stack = [], [root]
while stack:
node = stack.pop()
result.append(node.val)
for child in nod... | Solution |
python | ray-project__ray | python/ray/_common/tests/test_wait_for_condition.py | {
"start": 136,
"end": 3505
} | class ____:
"""Tests for the synchronous wait_for_condition function."""
def test_immediate_true_condition(self):
"""Test that function returns immediately when condition is already true."""
def always_true():
return True
wait_for_condition(always_true, timeout=5)
def... | TestWaitForCondition |
python | skorch-dev__skorch | skorch/callbacks/training.py | {
"start": 720,
"end": 12880
} | class ____(Callback):
"""Save the model during training if the given metric improved.
This callback works by default in conjunction with the validation
scoring callback since it creates a ``valid_loss_best`` value
in the history which the callback uses to determine if this
epoch is save-worthy.
... | Checkpoint |
python | huggingface__transformers | src/transformers/models/udop/modeling_udop.py | {
"start": 37059,
"end": 38347
} | class ____(nn.Module):
def __init__(self, max_2d_position_embeddings=501, hidden_size=1024):
super().__init__()
self.max_2d_position_embeddings = max_2d_position_embeddings
self.x_position_embeddings = nn.Embedding(max_2d_position_embeddings, hidden_size)
self.y_position_embeddings ... | UdopCellEmbeddings |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/annotatedVar5.py | {
"start": 63,
"end": 796
} | class ____(object):
def __init__(self):
self.inst_var1 = 3
@property
def prop1(self):
return 1
@prop1.setter
def prop1(self, val):
pass
def foo(self):
# This should generate an error because the assigned
# type doesn't match the declared type.
s... | ClassC |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/ddl.py | {
"start": 15879,
"end": 16376
} | class ____(_DropBase[str]):
"""Represent a DROP SCHEMA statement.
The argument here is the string name of the schema.
"""
__visit_name__ = "drop_schema"
stringify_dialect = "default"
def __init__(
self,
name: str,
cascade: bool = False,
if_exists: bool = Fals... | DropSchema |
python | astropy__astropy | astropy/table/tests/conftest.py | {
"start": 1179,
"end": 1232
} | class ____(table.MaskedColumn):
pass
| MyMaskedColumn |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-sub-question-weaviate/llama_index/packs/sub_question_weaviate/base.py | {
"start": 532,
"end": 2694
} | class ____(BaseLlamaPack):
"""Weaviate Sub-Question query engine pack."""
def __init__(
self,
collection_name: str,
host: str,
auth_client_secret: str,
nodes: Optional[List[TextNode]] = None,
**kwargs: Any,
) -> None:
"""Init params."""
from w... | WeaviateSubQuestionPack |
python | PrefectHQ__prefect | tests/test_flows.py | {
"start": 126113,
"end": 139853
} | class ____:
class TestSync:
@property
def flow(self):
@flow
def test_flow():
pass
return test_flow
def test_to_deployment_returns_runner_deployment(self):
deployment = self.flow.to_deployment(
name="test",
... | TestFlowToDeployment |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_optimize14.py | {
"start": 315,
"end": 1265
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("optimize14.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with comments."""
workbook = Workbo... | TestCompareXLSXFiles |
python | urllib3__urllib3 | test/with_dummyserver/test_connectionpool.py | {
"start": 51691,
"end": 54558
} | class ____(HypercornDummyServerTestCase):
def test_retry_after(self) -> None:
# Request twice in a second to get a 429 response.
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request(
"GET",
"/retry_after",
fields={"status... | TestRetryAfter |
python | paramiko__paramiko | paramiko/agent.py | {
"start": 6000,
"end": 6658
} | class ____(AgentProxyThread):
"""
Class to be used when wanting to ask a local SSH Agent being
asked from a remote fake agent (so use a unix socket for ex.)
"""
def __init__(self, agent):
AgentProxyThread.__init__(self, agent)
def get_connection(self):
"""
Return a pair... | AgentLocalProxy |
python | kamyu104__LeetCode-Solutions | Python/delivering-boxes-from-storage-to-ports.py | {
"start": 29,
"end": 964
} | class ____(object):
def boxDelivering(self, boxes, portsCount, maxBoxes, maxWeight):
"""
:type boxes: List[List[int]]
:type portsCount: int
:type maxBoxes: int
:type maxWeight: int
:rtype: int
"""
dp = [0]*(len(boxes)+1)
left, cost, curr = 0, 1... | Solution |
python | jina-ai__jina | jina/enums.py | {
"start": 3788,
"end": 4688
} | class ____(BetterEnum):
"""The enum for representing the parallel type of pods in a deployment."""
ANY = 1 #: one of the shards will receive the message
ALL = 2 #: all shards will receive the message, blocked until all done with the message
ALL_ASYNC = 3 #: (reserved) all replica will receive the me... | PollingType |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 7225,
"end": 8886
} | class ____(WebTestCase):
final_return = None # type: Future
def get_handlers(self):
test = self
class FinishHandler(RequestHandler):
@gen.coroutine
def get(self):
test.final_return = self.finish()
yield test.final_return
@ge... | FinalReturnTest |
python | huggingface__transformers | tests/repo_utils/test_check_copies.py | {
"start": 5460,
"end": 8009
} | class ____:
attr_1 = 1
attr_2 = 2
def __init__(self, a=1, b=2):
self.a = a
self.b = b
# Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
def forward(self, c):
return 1
def only_in_bert(self, c):
return 7
def existing_co... | RobertaBertDummyModel |
python | doocs__leetcode | solution/2700-2799/2743.Count Substrings Without Repeating Character/Solution.py | {
"start": 0,
"end": 306
} | class ____:
def numberOfSpecialSubstrings(self, s: str) -> int:
cnt = Counter()
ans = j = 0
for i, c in enumerate(s):
cnt[c] += 1
while cnt[c] > 1:
cnt[s[j]] -= 1
j += 1
ans += i - j + 1
return ans
| Solution |
python | ray-project__ray | rllib/offline/tests/test_offline_prelearner.py | {
"start": 538,
"end": 12051
} | class ____(unittest.TestCase):
EXPECTED_KEYS = [
Columns.OBS,
Columns.NEXT_OBS,
Columns.ACTIONS,
Columns.REWARDS,
Columns.TERMINATEDS,
Columns.TRUNCATEDS,
"n_step",
]
@classmethod
def setUpClass(cls):
ray.init()
@classmethod
def ... | TestOfflinePreLearner |
python | huggingface__transformers | src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | {
"start": 38308,
"end": 43691
} | class ____(UniSpeechSatPreTrainedModel):
def __init__(self, config: UniSpeechSatConfig):
super().__init__(config)
self.config = config
self.feature_extractor = UniSpeechSatFeatureEncoder(config)
self.feature_projection = UniSpeechSatFeatureProjection(config)
self.masked_spec... | UniSpeechSatModel |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 170776,
"end": 179111
} | class ____:
def f(self, *args, **kwargs):
return stats.percentileofscore(*args, **kwargs)
@pytest.mark.parametrize("kind, result", [("rank", 40),
("mean", 35),
("strict", 30),
... | TestPercentileOfScore |
python | MongoEngine__mongoengine | tests/fields/test_complex_base_field.py | {
"start": 103,
"end": 310
} | class ____(MongoDBTestCase):
def test_field_validation(self):
with pytest.raises(TypeError, match="field argument must be a Field instance"):
ComplexBaseField("test")
| TestComplexBaseField |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/docs/base.py | {
"start": 525,
"end": 3001
} | class ____(BaseReader):
"""PDF parser."""
def __init__(self, return_full_document: Optional[bool] = False) -> None:
"""
Initialize PDFReader.
"""
self.return_full_document = return_full_document
@retry(
stop=stop_after_attempt(RETRY_TIMES),
)
def load_data(
... | PDFReader |
python | django-haystack__django-haystack | haystack/fields.py | {
"start": 15365,
"end": 15427
} | class ____(FacetField, DecimalField):
pass
| FacetDecimalField |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 51053,
"end": 54908
} | class ____(BiffRecord):
"""
This record stores the position of window panes. It is part of the Sheet
View Settings Block. If the sheet does not contain any splits, this
record will not occur.
A sheet can be split in two different ways, with unfrozen panes or with
frozen panes. A flag in the WIND... | PanesRecord |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/list/retrievers.py | {
"start": 939,
"end": 1839
} | class ____(BaseRetriever):
"""
Simple retriever for SummaryIndex that returns all nodes.
Args:
index (SummaryIndex): The index to retrieve from.
"""
def __init__(
self,
index: SummaryIndex,
callback_manager: Optional[CallbackManager] = None,
object_map: Opt... | SummaryIndexRetriever |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 74007,
"end": 74280
} | class ____:
xlListConflictDialog = 0 # from enum XlListConflict
xlListConflictDiscardAllConflicts = 2 # from enum XlListConflict
xlListConflictError = 3 # from enum XlListConflict
xlListConflictRetryAllConflicts = 1 # from enum XlListConflict
| ListConflict |
python | google__jax | jax/_src/pallas/mosaic/core.py | {
"start": 6345,
"end": 6929
} | class ____(enum.Enum):
ANY = "any" # TODO(b/368401328): Remove this and just use pl.ANY.
VMEM = "vmem"
VMEM_SHARED = "vmem_shared"
SMEM = "smem"
CMEM = "cmem"
SEMAPHORE = "semaphore_mem"
HBM = "hbm"
HOST = "host"
def __str__(self) -> str:
return self.value
def from_type(self, ty):
return ... | MemorySpace |
python | doocs__leetcode | solution/0900-0999/0978.Longest Turbulent Subarray/Solution.py | {
"start": 0,
"end": 287
} | class ____:
def maxTurbulenceSize(self, arr: List[int]) -> int:
ans = f = g = 1
for a, b in pairwise(arr):
ff = g + 1 if a < b else 1
gg = f + 1 if a > b else 1
f, g = ff, gg
ans = max(ans, f, g)
return ans
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_selection02.py | {
"start": 315,
"end": 1255
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("selection02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_f... | TestCompareXLSXFiles |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/quantum_espresso/package.py | {
"start": 216,
"end": 846
} | class ____(Package):
"""Used to test that a few problematic concretization
cases with the old concretizer have been solved by the
new ones.
"""
homepage = "http://www.example.com"
url = "http://www.example.com/qe-1.0.tar.gz"
version("1.0", md5="1234567890abcdef1234567890abcdef")
varia... | QuantumEspresso |
python | python-openxml__python-docx | tests/opc/test_part.py | {
"start": 6358,
"end": 11651
} | class ____:
def it_constructs_part_from_selector_if_defined(self, cls_selector_fixture):
# fixture ----------------------
(
cls_selector_fn_,
part_load_params,
CustomPartClass_,
part_of_custom_type_,
) = cls_selector_fixture
partname, c... | DescribePartFactory |
python | google__jax | tests/mosaic/gpu_test.py | {
"start": 100959,
"end": 123345
} | class ____(TestCase):
@parameterized.product(
swizzle=(None, 32, 64, 128),
shape=((64, None), (5, None), (2, 3, 5, None)),
dtype=(jnp.float32, jnp.float16, jnp.int4),
)
def test_tma_load_basic(self, swizzle, shape, dtype):
bw = bitwidth(dtype_to_ir_type(dtype))
minor_size = 64 if swizzl... | AsyncCopyTest |
python | huggingface__transformers | src/transformers/models/doge/modular_doge.py | {
"start": 11531,
"end": 13220
} | class ____(LlamaRotaryEmbedding):
pass
def flex_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Union[torch.Tensor, "BlockMask"],
scaling: Optional[float] = None,
softcap: Optional[float] = None,
**kwargs,
) -> tupl... | DogeRotaryEmbedding |
python | keras-team__keras | keras/src/losses/losses_test.py | {
"start": 37200,
"end": 41884
} | class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(
losses.BinaryCrossentropy(name="bce", axis=-1)
)
def test_all_correct_unweighted(self):
y_true = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype="float32")
bce_obj = losses.Bina... | BinaryCrossentropyTest |
python | bokeh__bokeh | tests/unit/bokeh/models/test_ranges.py | {
"start": 1413,
"end": 4230
} | class ____:
def test_basic(self) -> None:
r = Range1d()
check_properties_existence(r, [
"start",
"end",
"reset_start",
"reset_end",
"bounds",
"min_interval",
"max_interval",
])
def test_qualified(self) -... | Test_Range1d |
python | Pylons__pyramid | src/pyramid/predicates.py | {
"start": 1071,
"end": 1497
} | class ____:
def __init__(self, val, config):
self.orig = val
try:
val = re.compile(val)
except re.error as why:
raise ConfigurationError(why.args[0])
self.val = val
def text(self):
return f'path_info = {self.orig}'
phash = text
def __cal... | PathInfoPredicate |
python | walkccc__LeetCode | solutions/2765. Longest Alternating Subarray/2765.py | {
"start": 0,
"end": 548
} | class ____:
def alternatingSubarray(self, nums: list[int]) -> int:
ans = 1
dp = 1
for i in range(1, len(nums)):
targetDiff = -1 if dp % 2 == 0 else 1
# Append nums[i] to the current alternating subarray.
if nums[i] - nums[i - 1] == targetDiff:
dp += 1
# Reset the alternati... | Solution |
python | numba__numba | numba/tests/doc_examples/test_examples.py | {
"start": 701,
"end": 23610
} | class ____(TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._mpl_blocker = MatplotlibBlocker()
def setUp(self):
sys.meta_path.insert(0, self._mpl_blocker)
def tearDown(self):
sys.meta_path.remove(self._mpl_blocker)
def test_mandel... | DocsExamplesTest |
python | google__pytype | pytype/tools/xref/callgraph.py | {
"start": 577,
"end": 2127
} | class ____:
id: str
params: list[Any] = dataclasses.field(default_factory=list)
param_attrs: list[Any] = dataclasses.field(default_factory=list)
local_attrs: list[Any] = dataclasses.field(default_factory=list)
calls: list[Any] = dataclasses.field(default_factory=list)
ret: Any = dataclasses.field(default=No... | Function |
python | pydantic__pydantic | pydantic-core/tests/validators/test_union.py | {
"start": 29990,
"end": 31457
} | class ____:
class ModelA:
a: int
class ModelB(ModelA):
b: int
model_a_schema = core_schema.model_schema(
ModelA, core_schema.model_fields_schema(fields={'a': core_schema.model_field(core_schema.int_schema())})
)
model_b_schema = core_schema.model_schema(
ModelB,
... | TestSmartUnionWithSubclass |
python | getsentry__sentry | fixtures/safe_migrations_apps/bad_flow_add_column_with_notnull_app/models.py | {
"start": 31,
"end": 96
} | class ____(models.Model):
field = models.IntegerField()
| TestTable |
python | ray-project__ray | python/ray/_private/runtime_env/py_modules.py | {
"start": 6509,
"end": 9007
} | class ____(RuntimeEnvPlugin):
name = "py_modules"
def __init__(self, resources_dir: str, gcs_client: GcsClient):
self._resources_dir = os.path.join(resources_dir, "py_modules_files")
self._gcs_client = gcs_client
try_to_create_directory(self._resources_dir)
def _get_local_dir_from... | PyModulesPlugin |
python | sqlalchemy__sqlalchemy | test/orm/test_naturalpks.py | {
"start": 22482,
"end": 25177
} | class ____(fixtures.MappedTest):
"""reverse the primary keys of two entities and ensure bookkeeping
succeeds."""
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"user",
metadata,
Column("code", Integer, autoincremen... | ReversePKsTest |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_sync_versions.py | {
"start": 49686,
"end": 54067
} | class ____(TestCase):
fixtures = ["eric", "test_data"]
def setUp(self):
self.user = User.objects.get(username="eric")
self.client.force_login(self.user)
self.pip = Project.objects.get(slug="pip")
# Run tests for .com
if settings.ALLOW_PRIVATE_REPOS:
self.org... | TestLatestVersion |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_count.py | {
"start": 81,
"end": 1083
} | class ____:
def test_count(self):
# corner case
frame = DataFrame()
ct1 = frame.count(1)
assert isinstance(ct1, Series)
ct2 = frame.count(0)
assert isinstance(ct2, Series)
# GH#423
df = DataFrame(index=range(10))
result = df.count(1)
... | TestDataFrameCount |
python | apache__airflow | providers/redis/src/airflow/providers/redis/sensors/redis_pub_sub.py | {
"start": 1138,
"end": 2728
} | class ____(BaseSensorOperator):
"""
Redis sensor for reading a message from pub sub channels.
:param channels: The channels to be subscribed to (templated)
:param redis_conn_id: the redis connection id
"""
template_fields: Sequence[str] = ("channels",)
ui_color = "#f0eee4"
def __init_... | RedisPubSubSensor |
python | pytorch__pytorch | torch/utils/data/datapipes/_decorator.py | {
"start": 2347,
"end": 6515
} | class ____:
cls: type[IterDataPipe] | None = None
# TODO: Lambda for picking
deterministic_fn: Callable[..., bool]
def __init__(self, arg: type[IterDataPipe] | Callable[..., bool]) -> None:
# 1. Decorator doesn't have any argument
if isinstance(arg, type): # type: ignore[arg-type]
... | non_deterministic |
python | pypa__pip | tests/lib/__init__.py | {
"start": 43414,
"end": 44581
} | class ____(Protocol):
def __call__(
self,
tmpdir: pathlib.Path,
virtualenv: VirtualEnvironment | None = None,
environ: dict[AnyStr, AnyStr] | None = None,
) -> PipTestEnvironment: ...
CertFactory = Callable[[], str]
# -----------------------------------------------------------... | ScriptFactory |
python | PrefectHQ__prefect | src/prefect/server/schemas/states.py | {
"start": 1980,
"end": 3030
} | class ____(PrefectBaseModel):
flow_run_id: Optional[UUID] = None
task_run_id: Optional[UUID] = None
# for task runs that represent subflows, the subflow's run ID
child_flow_run_id: Optional[UUID] = None
scheduled_time: Optional[DateTime] = None
cache_key: Optional[str] = None
cache_expiratio... | StateDetails |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol1.py | {
"start": 114,
"end": 830
} | class ____(Protocol):
def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]:
return []
def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:
return []
def bad_cb1(*vals: bytes, maxlen: int | None, maxitems: int | None) -> list[bytes]:
return []
def bad_cb2(*... | TestClass1 |
python | joke2k__faker | faker/providers/company/fi_FI/__init__.py | {
"start": 45,
"end": 2067
} | class ____(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{last_name}}",
)
company_suffixes = (
"As Oy",
"Tmi",
"Oy",
"Oyj... | Provider |
python | pennersr__django-allauth | tests/apps/socialaccount/test_adapter.py | {
"start": 311,
"end": 2105
} | class ____(DefaultSocialAccountAdapter):
def generate_state_param(self, state: dict) -> str:
return f"prefix-{super().generate_state_param(state)}"
def test_generate_state_param(settings, client, db, google_provider_settings):
settings.SOCIALACCOUNT_ADAPTER = (
"tests.apps.socialaccount.test_a... | PrefixStateSocialAccountAdapter |
python | coleifer__peewee | tests/base_models.py | {
"start": 1523,
"end": 1606
} | class ____(TestModel):
b = ForeignKeyField(B, backref='cs')
c = TextField()
| C |
python | numba__numba | numba/core/serialize.py | {
"start": 4779,
"end": 5406
} | class ____(abc.ABC):
"""A mixin class for objects that should be reduced by the NumbaPickler
instead of the standard pickler.
"""
# Subclass MUST override the below methods
@abc.abstractmethod
def _reduce_states(self):
raise NotImplementedError
@classmethod
@abc.abstractmethod
... | ReduceMixin |
python | getsentry__sentry | src/sentry/releases/endpoints/organization_release_details.py | {
"start": 3690,
"end": 11741
} | class ____:
@staticmethod
def __get_prev_release_date_query_q_and_order_by(release):
"""
Method that takes a release and returns a dictionary containing a date query Q expression
and order by columns required to fetch previous release to that passed in release on date
sorting
... | OrganizationReleaseDetailsPaginationMixin |
python | plotly__plotly.py | plotly/graph_objs/densitymapbox/colorbar/title/_font.py | {
"start": 233,
"end": 9944
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "densitymapbox.colorbar.title"
_path_str = "densitymapbox.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Font |
python | django__django | tests/prefetch_related/models.py | {
"start": 2348,
"end": 2591
} | class ____(models.Model):
# Intentionally does not have a related name.
book = models.ForeignKey(BookWithYear, models.CASCADE, null=True)
notes = models.TextField(null=True, blank=True)
# Models for default manager tests
| BookReview |
python | doocs__leetcode | solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.py | {
"start": 0,
"end": 534
} | class ____:
def countNumbersWithUniqueDigits(self, n: int) -> int:
@cache
def dfs(i: int, mask: int, lead: bool) -> int:
if i < 0:
return 1
ans = 0
for j in range(10):
if mask >> j & 1:
continue
i... | Solution |
python | optuna__optuna | optuna/pruners/_median.py | {
"start": 58,
"end": 3384
} | class ____(PercentilePruner):
"""Pruner using the median stopping rule.
Prune if the trial's best intermediate result is worse than median of intermediate results of
previous trials at the same step. It stops unpromising trials early based on the
intermediate results compared against the median of prev... | MedianPruner |
python | django__django | django/contrib/admin/widgets.py | {
"start": 13260,
"end": 14079
} | class ____(forms.URLInput):
template_name = "admin/widgets/url.html"
def __init__(self, attrs=None, validator_class=URLValidator):
super().__init__(attrs={"class": "vURLField", **(attrs or {})})
self.validator = validator_class()
def get_context(self, name, value, attrs):
try:
... | AdminURLFieldWidget |
python | pandas-dev__pandas | asv_bench/benchmarks/timeseries.py | {
"start": 6986,
"end": 7439
} | class ____:
params = [True, False]
param_names = ["monotonic"]
def setup(self, monotonic):
N = 10**5
idx = date_range(start="1/1/2000", periods=N, freq="s")
self.s = Series(np.random.randn(N), index=idx)
if not monotonic:
self.s = self.s.sample(frac=1)
def t... | SortIndex |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.