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 | pytorch__pytorch | benchmarks/dynamo/pr_time_benchmarks/benchmarks/basic_modules_benchmarks.py | {
"start": 137,
"end": 505
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(20)])
def forward(self, x):
# ModuleList can act as an iterable, or be indexed using ints
for i, l in enumerate(self.linears):
x = self.linear... | ListOfLinears |
python | apache__airflow | airflow-core/src/airflow/models/taskmap.py | {
"start": 1730,
"end": 1950
} | class ____(enum.Enum):
"""
Task map variant.
Possible values are **dict** (for a key-value mapping) and **list** (for an
ordered value sequence).
"""
DICT = "dict"
LIST = "list"
| TaskMapVariant |
python | huggingface__transformers | src/transformers/models/granite/modular_granite.py | {
"start": 5051,
"end": 9168
} | class ____(LlamaModel):
def __init__(self, config: GraniteConfig):
super().__init__(config)
self.embedding_multiplier = config.embedding_multiplier
self.layers = nn.ModuleList(
[GraniteDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
... | GraniteModel |
python | Pylons__pyramid | tests/test_viewderivers.py | {
"start": 68209,
"end": 70369
} | class ____(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
self.config = None
testing.tearDown()
def _getViewCallable(
self, config, ctx_iface=None, request_iface=None, name=''
):
from zope.interface import Interface
... | TestDeriverIntegration |
python | bokeh__bokeh | src/bokeh/protocol/exceptions.py | {
"start": 1881,
"end": 2472
} | class ____(Exception):
''' Indicate an error validating wire protocol fragments.
This exception typically indicates that a binary message fragment was
received when a text fragment was expected, or vice-versa.
'''
pass
#-----------------------------------------------------------------------------... | ValidationError |
python | PrefectHQ__prefect | src/prefect/types/entrypoint.py | {
"start": 24,
"end": 328
} | class ____(Enum):
"""
Enum representing a entrypoint type.
File path entrypoints are in the format: `path/to/file.py:function_name`.
Module path entrypoints are in the format: `path.to.module.function_name`.
"""
FILE_PATH = "file_path"
MODULE_PATH = "module_path"
| EntrypointType |
python | pennersr__django-allauth | allauth/socialaccount/providers/pocket/provider.py | {
"start": 313,
"end": 896
} | class ____(OAuthProvider):
id = "pocket"
name = "Pocket"
account_class = PocketAccount
oauth_adapter_class = PocketOAuthAdapter
def extract_uid(self, data):
return data["username"]
def extract_common_fields(self, data):
return dict(
email=data["username"],
)... | PocketProvider |
python | RaRe-Technologies__gensim | gensim/models/doc2vec.py | {
"start": 6354,
"end": 51237
} | class ____(Word2Vec):
def __init__(
self, documents=None, corpus_file=None, vector_size=100, dm_mean=None, dm=1, dbow_words=0, dm_concat=0,
dm_tag_count=1, dv=None, dv_mapfile=None, comment=None, trim_rule=None, callbacks=(),
window=5, epochs=10, shrink_windows=True, **kwargs,
... | Doc2Vec |
python | huggingface__transformers | src/transformers/models/gemma3n/modular_gemma3n.py | {
"start": 71403,
"end": 74627
} | class ____(PreTrainedModel):
"""
An audio encoder based on the [Universal Speech Model](https://huggingface.co/papers/2303.01037) architecture.
"""
config: Gemma3nAudioConfig
main_input_name = "audio_mel"
input_modalities = "audio"
def __init__(self, config: Gemma3nAudioConfig):
s... | Gemma3nAudioEncoder |
python | jmcnamara__XlsxWriter | xlsxwriter/rich_value_structure.py | {
"start": 333,
"end": 2553
} | class ____(xmlwriter.XMLwriter):
"""
A class for writing the Excel XLSX rdrichvaluestructure.xml file.
"""
###########################################################################
#
# Public API.
#
###########################################################################
def... | RichValueStructure |
python | django-haystack__django-haystack | test_haystack/elasticsearch_tests/test_elasticsearch_backend.py | {
"start": 5696,
"end": 6298
} | class ____(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, default="")
name = indexes.CharField(faceted=True)
is_active = indexes.BooleanField(faceted=True)
post_count = indexes.IntegerField()
post_count_i = indexes.FacetIntegerField(facet_for="post_count")
avera... | ElasticsearchComplexFacetsMockSearchIndex |
python | python-pillow__Pillow | src/PIL/ImageTransform.py | {
"start": 3638,
"end": 3916
} | class ____(Transform):
"""
Define a mesh image transform. A mesh transform consists of one or more
individual quad transforms.
See :py:meth:`.Image.transform`
:param data: A list of (bbox, quad) tuples.
"""
method = Image.Transform.MESH
| MeshTransform |
python | ipython__ipython | IPython/core/history.py | {
"start": 19613,
"end": 36361
} | class ____(HistoryAccessor):
"""A class to organize all history-related functionality in one place."""
# Public interface
# An instance of the IPython shell we are attached to
shell = Instance(
"IPython.core.interactiveshell.InteractiveShellABC", allow_none=False
)
# Lists to hold proc... | HistoryManager |
python | doocs__leetcode | solution/1900-1999/1994.The Number of Good Subsets/Solution.py | {
"start": 0,
"end": 745
} | class ____:
def numberOfGoodSubsets(self, nums: List[int]) -> int:
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
cnt = Counter(nums)
mod = 10**9 + 7
n = len(primes)
f = [0] * (1 << n)
f[0] = pow(2, cnt[1])
for x in range(2, 31):
if cnt[x] == 0 or x... | Solution |
python | kamyu104__LeetCode-Solutions | Python/regular-expression-matching.py | {
"start": 2875,
"end": 3416
} | class ____(object):
# @return a boolean
def isMatch(self, s, p):
if not p:
return not s
if len(p) == 1 or p[1] != '*':
if len(s) > 0 and (p[0] == s[0] or p[0] == '.'):
return self.isMatch(s[1:], p[1:])
else:
return False
... | Solution4 |
python | django-extensions__django-extensions | django_extensions/db/models.py | {
"start": 2911,
"end": 3904
} | class ____(models.Model):
"""
ActivatorModel
An abstract base class model that provides activate and deactivate fields.
"""
INACTIVE_STATUS = 0
ACTIVE_STATUS = 1
STATUS_CHOICES = (
(INACTIVE_STATUS, _("Inactive")),
(ACTIVE_STATUS, _("Active")),
)
status = models.In... | ActivatorModel |
python | pandas-dev__pandas | pandas/tests/arithmetic/test_categorical.py | {
"start": 103,
"end": 742
} | class ____:
def test_categorical_nan_equality(self):
cat = Series(Categorical(["a", "b", "c", np.nan]))
expected = Series([True, True, True, False])
result = cat == cat
tm.assert_series_equal(result, expected)
def test_categorical_tuple_equality(self):
# GH 18050
... | TestCategoricalComparisons |
python | huggingface__transformers | src/transformers/models/swin/modeling_swin.py | {
"start": 7250,
"end": 11162
} | class ____(nn.Module):
"""
Construct the patch and position embeddings. Optionally, also the mask token.
"""
def __init__(self, config, use_mask_token=False):
super().__init__()
self.patch_embeddings = SwinPatchEmbeddings(config)
num_patches = self.patch_embeddings.num_patches
... | SwinEmbeddings |
python | great-expectations__great_expectations | great_expectations/expectations/regex_based_column_map_expectation.py | {
"start": 3719,
"end": 14570
} | class ____(ColumnMapExpectation, ABC):
"""Base class for RegexBasedColumnMapExpectations.
RegexBasedColumnMapExpectations facilitate regex parsing as the core logic for a Map Expectation.
Example Definition:
```python
ExpectColumnValuesToOnlyContainVowels(SetBasedColumnMapExpectation):
re... | RegexBasedColumnMapExpectation |
python | pytorch__pytorch | torch/_inductor/fx_passes/dedupe_symint_uses.py | {
"start": 240,
"end": 668
} | class ____:
"""
Hash for a py_sym_types that will use the underlying sympy expression
"""
sym_obj: SymInt | SymFloat | SymBool
def __hash__(self) -> int:
return hash((type(self.sym_obj), self.sym_obj.node.expr))
def __eq__(self, value) -> bool:
if not isinstance(value, _SymExp... | _SymExprHash |
python | kamyu104__LeetCode-Solutions | Python/student-attendance-record-ii.py | {
"start": 29,
"end": 427
} | class ____(object):
def checkRecord(self, n):
"""
:type n: int
:rtype: int
"""
M = 1000000007
a0l0, a0l1, a0l2, a1l0, a1l1, a1l2 = 1, 0, 0, 0, 0, 0
for i in xrange(n+1):
a0l2, a0l1, a0l0 = a0l1, a0l0, (a0l0 + a0l1 + a0l2) % M
a1l2, a1l1... | Solution |
python | python-pillow__Pillow | Tests/test_file_png.py | {
"start": 1372,
"end": 29644
} | class ____:
def get_chunks(self, filename: Path) -> list[bytes]:
chunks = []
with open(filename, "rb") as fp:
fp.read(8)
with PngImagePlugin.PngStream(fp) as png:
while True:
cid, pos, length = png.read()
chunks.append(c... | TestFilePng |
python | google__pytype | pytype/pytd/codegen/function.py | {
"start": 1354,
"end": 4846
} | class ____:
"""Internal representation of function signatures."""
name: str
signature: pytd.Signature
decorators: tuple[pytd.Alias, ...] = ()
is_abstract: bool = False
is_coroutine: bool = False
is_final: bool = False
is_overload: bool = False
@classmethod
def make(
cls, name: str, args: lis... | NameAndSig |
python | ethereum__web3.py | web3/utils/subscriptions.py | {
"start": 2389,
"end": 6016
} | class ____(Generic[TSubscriptionResult]):
_id: HexStr = None
manager: "SubscriptionManager" = None
def __init__(
self: TSubscription,
subscription_params: Sequence[Any] | None = None,
handler: EthSubscriptionHandler | None = None,
handler_context: dict[str, Any] | None = Non... | EthSubscription |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/test_organization_detector_details.py | {
"start": 6265,
"end": 29955
} | class ____(OrganizationDetectorDetailsBaseTest):
method = "PUT"
def setUp(self) -> None:
super().setUp()
self.valid_data = {
"id": self.detector.id,
"projectId": self.project.id,
"name": "Updated Detector",
"type": MetricIssue.slug,
"d... | OrganizationDetectorDetailsPutTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType34.py | {
"start": 381,
"end": 510
} | class ____(Generic[_T_co, _N]): ...
def func1(n: _N) -> ClassA[Literal[0], _N]: ...
v1: ClassA[int, Literal[1]] = func1(1)
| ClassA |
python | Textualize__textual | docs/examples/widgets/input_validation.py | {
"start": 1427,
"end": 1881
} | class ____(Validator): # (5)!
def validate(self, value: str) -> ValidationResult:
"""Check a string is equal to its reverse."""
if self.is_palindrome(value):
return self.success()
else:
return self.failure("That's not a palindrome :/")
@staticmethod
def is_p... | Palindrome |
python | wandb__wandb | wandb/sdk/integration_utils/auto_logging.py | {
"start": 876,
"end": 5426
} | class ____:
def __init__(
self,
name: str,
symbols: Sequence[str],
resolver: ArgumentResponseResolver,
) -> None:
"""Patches the API to log wandb Media or metrics."""
# name of the LLM provider, e.g. "Cohere" or "OpenAI" or package name like "Transformers"
... | PatchAPI |
python | walkccc__LeetCode | solutions/516. Longest Palindromic Subsequence/516-2.py | {
"start": 0,
"end": 441
} | class ____:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
# dp[i][j] := the length of LPS(s[i..j])
dp = [[0] * n for _ in range(n)]
for i in range(n):
dp[i][i] = 1
for d in range(1, n):
for i in range(n - d):
j = i + d
if s[i] == s[j]:
dp[i][j... | Solution |
python | ansible__ansible | test/units/module_utils/facts/test_facts.py | {
"start": 7142,
"end": 7314
} | class ____(BaseTestFactsPlatform):
platform_id = 'HP-UX'
fact_class = virtual.hpux.HPUXVirtual
collector_class = virtual.hpux.HPUXVirtualCollector
| TestHPUXVirtual |
python | tensorflow__tensorflow | tensorflow/tools/compatibility/ast_edits_test.py | {
"start": 3843,
"end": 4199
} | class ____(ast_edits.NoUpdateSpec):
"""A specification where both keyword aliases are removed from h.
The new API is
def h(a, kw1, kw2): ...
"""
def __init__(self):
ast_edits.NoUpdateSpec.__init__(self)
self.function_keyword_renames["h"] = {
"kw1_alias": "kw1",
"kw2_alias": "kw2"... | RemoveMultipleKeywordArguments |
python | plotly__plotly.py | _plotly_utils/basevalidators.py | {
"start": 84012,
"end": 86442
} | class ____(CompoundValidator):
def __init__(self, plotly_name, parent_name, data_class_str, data_docs, **kwargs):
super(BaseTemplateValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=data_class_str,
data_docs=data_docs,... | BaseTemplateValidator |
python | doocs__leetcode | solution/2000-2099/2033.Minimum Operations to Make a Uni-Value Grid/Solution.py | {
"start": 0,
"end": 382
} | class ____:
def minOperations(self, grid: List[List[int]], x: int) -> int:
nums = []
mod = grid[0][0] % x
for row in grid:
for v in row:
if v % x != mod:
return -1
nums.append(v)
nums.sort()
mid = nums[len(nums) ... | Solution |
python | apache__airflow | providers/apache/hive/tests/integration/apache/hive/transfers/test_mssql_to_hive.py | {
"start": 1189,
"end": 3465
} | class ____:
def setup_method(self, mocker):
os.environ["AIRFLOW_CONN_MSSQL_DEFAULT"] = AIRFLOW_CONN_MSSQL_DEFAULT
hook = MsSqlHook()
conn = hook.get_conn()
hook.set_autocommit(conn, True)
self.cursor = conn.cursor()
self.cursor.execute(f"""CREATE TABLE {TEST_TABLE_ID}... | TestMsSqlToHiveTransfer |
python | getsentry__sentry | tests/sentry/integrations/repository/issue_alert/test_issue_alert_notification_message_repository.py | {
"start": 6613,
"end": 12720
} | class ____(
BaseIssueAlertNotificationMessageRepositoryTest
):
def test_returns_all_when_no_filters(self) -> None:
# Create additional notification messages
additional_notification = NotificationMessage.objects.create(
rule_fire_history=self.rule_fire_history,
rule_action... | TestGetAllParentNotificationMessagesByFilters |
python | kubernetes-client__python | kubernetes/client/models/v1alpha1_volume_attributes_class_list.py | {
"start": 383,
"end": 7328
} | 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... | V1alpha1VolumeAttributesClassList |
python | apache__airflow | helm-tests/tests/helm_tests/other/test_flower.py | {
"start": 27507,
"end": 28197
} | class ____:
"""Tests flower secret."""
def test_should_add_annotations_to_flower_secret(self):
docs = render_chart(
values={
"flower": {
"enabled": True,
"username": "username",
"password": "password",
... | TestFlowerSecret |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_sns.py | {
"start": 1535,
"end": 3349
} | class ____:
@pytest.fixture(autouse=True)
def setup_moto(self):
with mock_aws():
yield
@pytest.fixture
def hook(self):
return SnsHook(aws_conn_id="aws_default")
@pytest.fixture
def target(self, hook):
return hook.get_conn().create_topic(Name=TOPIC_NAME).get(... | TestSnsHook |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 27881,
"end": 28104
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("APPROVED", "CHANGES_REQUESTED", "COMMENTED", "DISMISSED", "PENDING")
| PullRequestReviewState |
python | google__pytype | pytype/types/classes.py | {
"start": 168,
"end": 1047
} | class ____(base.BaseValue, abc.ABC):
"""Base class for representation of python classes."""
@property
@abc.abstractmethod
def name(self) -> str:
"""Class name."""
@property
@abc.abstractmethod
def bases(self) -> Sequence[base.BaseValue]:
"""Class bases."""
@property
@abc.abstractmethod
de... | Class |
python | django__django | django/db/migrations/operations/fields.py | {
"start": 7071,
"end": 9603
} | class ____(FieldOperation):
"""
Alter a field's database column (e.g. null, max_length) to the provided
new field.
"""
category = OperationCategory.ALTERATION
def __init__(self, model_name, name, field, preserve_default=True):
self.preserve_default = preserve_default
super().__... | AlterField |
python | kamyu104__LeetCode-Solutions | Python/shortest-string-that-contains-three-strings.py | {
"start": 1521,
"end": 2136
} | class ____(object):
def minimumString(self, a, b, c):
"""
:type a: str
:type b: str
:type c: str
:rtype: str
"""
def merge(a, b):
if a in b:
return b
l = next((l for l in reversed(xrange(1, min(len(a), len(b)))) if a[-l:... | Solution2 |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 4673,
"end": 4807
} | class ____:
real: Annotated[float, 10]
imag: Annotated[float, 20]
# This is actually a union type
@_union_dataclass
| ComplexValue |
python | python-markdown__markdown | markdown/postprocessors.py | {
"start": 4180,
"end": 4493
} | class ____(Postprocessor):
""" Restore escaped chars. """
RE = re.compile(r'{}(\d+){}'.format(util.STX, util.ETX))
def unescape(self, m: re.Match[str]) -> str:
return chr(int(m.group(1)))
def run(self, text: str) -> str:
return self.RE.sub(self.unescape, text)
| UnescapePostprocessor |
python | squidfunk__mkdocs-material | material/plugins/social/config.py | {
"start": 1493,
"end": 2845
} | class ____(Config):
enabled = Type(bool, default = True)
concurrency = Type(int, default = max(1, os.cpu_count() - 1))
# Settings for caching
cache = Type(bool, default = True)
cache_dir = Type(str, default = ".cache/plugin/social")
# Settings for logging
log = Type(bool, default = True)
... | SocialConfig |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels24.py | {
"start": 315,
"end": 1875
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_data_labels24.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/inset_locator.py | {
"start": 434,
"end": 1310
} | class ____(AnchoredOffsetbox):
def __init__(self, bbox_to_anchor, offsetbox, loc,
borderpad=0.5, bbox_transform=None):
super().__init__(
loc, pad=0., child=None, borderpad=borderpad,
bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform
)
def draw... | AnchoredLocatorBase |
python | pytest-dev__pytest | src/_pytest/_io/terminalwriter.py | {
"start": 1211,
"end": 8994
} | class ____:
_esctable = dict(
black=30,
red=31,
green=32,
yellow=33,
blue=34,
purple=35,
cyan=36,
white=37,
Black=40,
Red=41,
Green=42,
Yellow=43,
Blue=44,
Purple=45,
Cyan=46,
White=47,
... | TerminalWriter |
python | pypa__pip | src/pip/_internal/operations/install/wheel.py | {
"start": 1548,
"end": 12379
} | class ____(Protocol):
src_record_path: RecordPath
dest_path: str
changed: bool
def save(self) -> None:
pass
logger = logging.getLogger(__name__)
RecordPath = NewType("RecordPath", str)
InstalledCSVRow = tuple[RecordPath, str, Union[int, str]]
def rehash(path: str, blocksize: int = 1 << 20)... | File |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 42596,
"end": 42923
} | class ____(fftw_info):
section = 'fftw'
dir_env_var = 'FFTW'
ver_info = [{'name':'dfftw threads',
'libs':['drfftw_threads', 'dfftw_threads'],
'includes':['dfftw_threads.h', 'drfftw_threads.h'],
'macros':[('SCIPY_DFFTW_THREADS_H', None)]}]
| dfftw_threads_info |
python | doocs__leetcode | solution/0800-0899/0802.Find Eventual Safe States/Solution.py | {
"start": 0,
"end": 566
} | class ____:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
rg = defaultdict(list)
indeg = [0] * len(graph)
for i, vs in enumerate(graph):
for j in vs:
rg[j].append(i)
indeg[i] = len(vs)
q = deque([i for i, v in enumerate(inde... | Solution |
python | zarr-developers__zarr-python | src/zarr/storage/_local.py | {
"start": 2688,
"end": 10346
} | class ____(Store):
"""
Store for the local file system.
Parameters
----------
root : str or Path
Directory to use as root of store.
read_only : bool
Whether the store is read-only
Attributes
----------
supports_writes
supports_deletes
supports_listing
ro... | LocalStore |
python | doocs__leetcode | solution/0800-0899/0882.Reachable Nodes In Subdivided Graph/Solution.py | {
"start": 0,
"end": 722
} | class ____:
def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
g = defaultdict(list)
for u, v, cnt in edges:
g[u].append((v, cnt + 1))
g[v].append((u, cnt + 1))
q = [(0, 0)]
dist = [0] + [inf] * n
while q:
d, u ... | Solution |
python | walkccc__LeetCode | solutions/2380. Time Needed to Rearrange a Binary String/2380.py | {
"start": 0,
"end": 236
} | class ____:
def secondsToRemoveOccurrences(self, s: str) -> int:
ans = 0
zeros = 0
for c in s:
if c == '0':
zeros += 1
elif zeros > 0: # c == '1'
ans = max(ans + 1, zeros)
return ans
| Solution |
python | numba__numba | numba/tests/annotation_usecases.py | {
"start": 129,
"end": 316
} | class ____:
"""
A class with annotated methods.
"""
def __init__(self, v: int):
self.x = v
def add(self, v: int) -> int:
return self.x + v
| AnnotatedClass |
python | docker__docker-py | docker/credentials/errors.py | {
"start": 93,
"end": 440
} | class ____(StoreError):
pass
def process_store_error(cpe, program):
message = cpe.output.decode('utf-8')
if 'credentials not found in native keychain' in message:
return CredentialsNotFound(f'No matching credentials in {program}')
return StoreError(f'Credentials store {program} exited with "{m... | InitializationError |
python | pytoolz__toolz | toolz/functoolz.py | {
"start": 14156,
"end": 18815
} | class ____:
""" A composition of functions
See Also:
compose
"""
__slots__ = 'first', 'funcs'
def __init__(self, funcs):
funcs = tuple(reversed(funcs))
self.first = funcs[0]
self.funcs = funcs[1:]
def __call__(self, *args, **kwargs):
ret = self.first(*a... | Compose |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_logging_sink.py | {
"start": 4920,
"end": 11443
} | class ____:
def test_template_fields(self):
operator = CloudLoggingCreateSinkOperator(task_id=TASK_ID, project_id=PROJECT_ID, sink_config=sink)
assert "sink_config" in operator.template_fields
assert "unique_writer_identity" in operator.template_fields
_assert_common_template_fields(... | TestCloudLoggingCreateSinkOperator |
python | dateutil__dateutil | src/dateutil/tz/win.py | {
"start": 3793,
"end": 6640
} | class ____(tzrangebase):
"""tzinfo class based on win32's timezones available in the registry."""
def __init__(self):
raise NotImplementedError('tzwinbase is an abstract base class')
def __eq__(self, other):
# Compare on all relevant dimensions, including name.
if not isinstance(oth... | tzwinbase |
python | davidhalter__jedi | test/completion/django.py | {
"start": 227,
"end": 328
} | class ____(models.Manager):
def specially_filtered_tags(self):
return self.all()
| TagManager |
python | gevent__gevent | src/gevent/tests/test__example_udp_client.py | {
"start": 154,
"end": 884
} | class ____(util.TestServer):
start_kwargs = {'timeout': 10}
example = 'udp_client.py'
example_args = ['Test_udp_client']
def test(self):
log = []
def handle(message, address):
log.append(message)
server.sendto(b'reply-from-server', address)
server = Da... | Test_udp_client |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mixpanel/source_mixpanel/streams.py | {
"start": 1494,
"end": 6310
} | class ____(HttpStream, ABC):
"""
Formatted API Rate Limit (https://help.mixpanel.com/hc/en-us/articles/115004602563-Rate-Limits-for-API-Endpoints):
A maximum of 5 concurrent queries
60 queries per hour.
"""
DEFAULT_REQS_PER_HOUR_LIMIT = 60
@property
def state_checkpoint_interval(s... | MixpanelStream |
python | facebook__pyre-check | client/coverage_data.py | {
"start": 1145,
"end": 1619
} | class ____(json_mixins.SnakeCaseAndExcludeJsonMixin):
start_line: int
start_column: int
end_line: int
end_column: int
@staticmethod
def from_code_range(code_range: CodeRange) -> Location:
return Location(
start_line=code_range.start.line,
start_column=code_range.... | Location |
python | walkccc__LeetCode | solutions/1480. Running Sum of 1d Array/1480.py | {
"start": 0,
"end": 108
} | class ____:
def runningSum(self, nums: list[int]) -> list[int]:
return itertools.accumulate(nums)
| Solution |
python | PyCQA__pylint | tests/functional/m/membership_protocol_py3.py | {
"start": 603,
"end": 924
} | class ____(metaclass=MetaContainer):
pass
def test():
1 in IterableClass
1 in OldIterableClass
1 in ContainerClass
1 in IterableClass() # [unsupported-membership-test]
1 in OldIterableClass() # [unsupported-membership-test]
1 in ContainerClass() # [unsupported-membership-test]
| ContainerClass |
python | run-llama__llama_index | llama-index-core/llama_index/core/chat_engine/simple.py | {
"start": 511,
"end": 7207
} | class ____(BaseChatEngine):
"""
Simple Chat Engine.
Have a conversation with the LLM.
This does not make use of a knowledge base.
"""
def __init__(
self,
llm: LLM,
memory: BaseMemory,
prefix_messages: List[ChatMessage],
callback_manager: Optional[Callbac... | SimpleChatEngine |
python | mitmproxy__pdoc | test/testdata/misc_py310.py | {
"start": 140,
"end": 267
} | class ____:
pass
NewStyleDict = dict[str, str]
"""New-style dict."""
OldStyleDict = Dict[str, str]
"""Old-style dict."""
| Foo |
python | spack__spack | var/spack/test_repos/spack_repo/flags_test/packages/u/package.py | {
"start": 216,
"end": 326
} | class ____(Package):
version("6.0")
depends_on("y cflags='-e1 -e2'")
depends_on("c", type="build")
| U |
python | pytorch__pytorch | .github/scripts/test_gitutils.py | {
"start": 1002,
"end": 1464
} | class ____(TestCase):
def test_double_asterisks(self) -> None:
allowed_patterns = [
"aten/src/ATen/native/**LinearAlgebra*",
]
patterns_re = patterns_to_regex(allowed_patterns)
fnames = [
"aten/src/ATen/native/LinearAlgebra.cpp",
"aten/src/ATen/nat... | TestPattern |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 53857,
"end": 53957
} | class ____(BaseModel):
models: Dict[str, "ModelUsage"] = Field(..., description="")
| InferenceUsage |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/layer_fix.py | {
"start": 171,
"end": 345
} | class ____(Vertical):
def compose(self) -> ComposeResult:
"""Compose the child widgets."""
yield Label("This should not cause a scrollbar to appear")
| Dialog |
python | Lightning-AI__lightning | tests/tests_pytorch/helpers/datamodules.py | {
"start": 898,
"end": 1925
} | class ____(LightningDataModule):
def __init__(self, data_dir: str = "./", batch_size: int = 32, use_trials: bool = False) -> None:
super().__init__()
self.data_dir = data_dir
self.batch_size = batch_size
# TrialMNIST is a constrained MNIST dataset
self.dataset_cls = TrialMN... | MNISTDataModule |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/queue.py | {
"start": 1381,
"end": 2124
} | class ____(Generic[_T]):
maxsize: int
use_lifo: bool
def __init__(self, maxsize: int = 0, use_lifo: bool = False): ...
def empty(self) -> bool:
raise NotImplementedError()
def full(self) -> bool:
raise NotImplementedError()
def qsize(self) -> int:
raise NotImplemented... | QueueCommon |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1521553,
"end": 1522797
} | class ____(Transform):
"""
LookupTransform schema wrapper.
Parameters
----------
lookup : str
Key in primary data source.
default : Any
The default value to use if lookup fails.
**Default value:** ``null``
as : str, :class:`FieldName`, Sequence[str, :class:`FieldNam... | LookupTransform |
python | doocs__leetcode | solution/1800-1899/1884.Egg Drop With 2 Eggs and N Floors/Solution.py | {
"start": 0,
"end": 236
} | class ____:
def twoEggDrop(self, n: int) -> int:
f = [0] + [inf] * n
for i in range(1, n + 1):
for j in range(1, i + 1):
f[i] = min(f[i], 1 + max(j - 1, f[i - j]))
return f[n]
| Solution |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/optics/pyoptic.py | {
"start": 2810,
"end": 3787
} | class ____(object):
# Just a helper for tracking parameters and responding to changes
def __init__(self):
self.__params = {}
def __setitem__(self, item, val):
self.setParam(item, val)
def setParam(self, param, val):
self.setParams(**{param:val})
def set... | ParamObj |
python | tensorflow__tensorflow | tensorflow/python/framework/errors_impl.py | {
"start": 10527,
"end": 10964
} | class ____(OpError):
"""Raised when a deadline expires before an operation could complete.
This exception is not currently used.
"""
def __init__(self, node_def, op, message, *args):
"""Creates a `DeadlineExceededError`."""
super(DeadlineExceededError, self).__init__(node_def, op, message,
... | DeadlineExceededError |
python | tensorflow__tensorflow | tensorflow/python/distribute/experimental/dtensor_strategy_extended.py | {
"start": 1404,
"end": 11727
} | class ____(distribute_lib.StrategyExtendedV2):
"""Strategy extension that support both single and multi worker strategy."""
# Note that the unit test for this class is via the strategy interface.
def __init__(self, container_strategy, mesh):
super().__init__(container_strategy)
self._mesh = mesh
self... | DTensorStrategyExtended |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_eventbridge.py | {
"start": 7476,
"end": 9015
} | class ____:
def test_init(self):
op = EventBridgeDisableRuleOperator(
task_id="disable_rule_task",
name=RULE_NAME,
aws_conn_id="fake-conn-id",
region_name="ca-west-1",
verify=True,
botocore_config={"read_timeout": 42},
)
... | TestEventBridgeDisableRuleOperator |
python | getsentry__sentry | src/sentry/integrations/source_code_management/repo_trees.py | {
"start": 1019,
"end": 8973
} | class ____(ABC):
"""
Base class for integrations that can get trees for an organization's repositories.
It is used for finding files in repositories and deriving code mappings.
"""
CACHE_SECONDS = 3600 * 24
# This method must be implemented
@abstractmethod
def get_client(self) -> RepoT... | RepoTreesIntegration |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/deprecated6.py | {
"start": 215,
"end": 416
} | class ____:
@deprecated("Use ClassB instead")
def __call__(self) -> None: ...
a = A()
# This should generate an error if reportDeprecated is enabled.
a()
P = ParamSpec("P")
R = TypeVar("R")
| A |
python | huggingface__transformers | tests/models/hubert/test_modeling_hubert.py | {
"start": 1401,
"end": 11516
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=1024, # speech is longer
is_training=False,
hidden_size=16,
feat_extract_norm="group",
feat_extract_dropout=0.0,
feat_extract_activation="gelu",
conv_dim=(32, 32, 32),
... | HubertModelTester |
python | getsentry__sentry | src/sentry/core/endpoints/scim/teams.py | {
"start": 4585,
"end": 4750
} | class ____(SCIMListBaseResponse):
Resources: list[OrganizationTeamSCIMSerializerResponse]
@extend_schema(tags=["SCIM"])
@region_silo_endpoint
| SCIMListTeamsResponse |
python | aimacode__aima-python | learning.py | {
"start": 33988,
"end": 45678
} | class ____:
def __init__(self, clf, decision_function='ovr'):
self.clf = clf
self.decision_function = decision_function
self.n_class, self.classifiers = 0, []
def fit(self, X, y):
"""
Trains n_class or n_class * (n_class - 1) / 2 classifiers
according to the tra... | MultiClassLearner |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datacatalog.py | {
"start": 74051,
"end": 79307
} | class ____(GoogleCloudBaseOperator):
r"""
Searches Data Catalog for multiple resources like entries, tags that match a query.
This does not return the complete resource, only the resource identifier and high level fields.
Clients can subsequently call ``Get`` methods.
Note that searches do not hav... | CloudDataCatalogSearchCatalogOperator |
python | django__django | django/test/testcases.py | {
"start": 4979,
"end": 5305
} | class ____(_AssertTemplateUsedContext):
def test(self):
self.test_case.assertFalse(
self.template_name in self.rendered_template_names,
f"{self.msg_prefix}Template '{self.template_name}' was used "
f"unexpectedly in rendering the response",
)
| _AssertTemplateNotUsedContext |
python | PrefectHQ__prefect | src/prefect/server/concurrency/lease_storage/filesystem.py | {
"start": 695,
"end": 10350
} | class ____(_ConcurrencyLeaseStorage):
"""
A file-based concurrency lease storage implementation that stores leases on disk.
"""
def __init__(self, storage_path: Path | None = None):
prefect_home = get_current_settings().home
self.storage_path: Path = Path(
storage_path or pr... | ConcurrencyLeaseStorage |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 246347,
"end": 248946
} | class ____(TestCase):
"""
Verify that making a view of a non-contiguous array works as expected.
"""
def test_smaller_dtype_multiple(self):
# x is non-contiguous
x = np.arange(10, dtype="<i4")[::2]
with pytest.raises(ValueError, match="the last axis must be contiguous"):
... | TestViewDtype |
python | faif__python-patterns | tests/structural/test_decorator.py | {
"start": 97,
"end": 692
} | class ____(unittest.TestCase):
def setUp(self):
self.raw_string = TextTag("raw but not cruel")
def test_italic(self):
self.assertEqual(
ItalicWrapper(self.raw_string).render(), "<i>raw but not cruel</i>"
)
def test_bold(self):
self.assertEqual(
BoldW... | TestTextWrapping |
python | celery__celery | t/unit/tasks/test_states.py | {
"start": 43,
"end": 1085
} | class ____:
@pytest.mark.parametrize('r,l', [
(states.SUCCESS, states.PENDING),
(states.FAILURE, states.RECEIVED),
(states.REVOKED, states.STARTED),
(states.SUCCESS, 'CRASHED'),
(states.FAILURE, 'CRASHED'),
])
def test_gt(self, r, l):
assert states.state(r) >... | test_state_precedence |
python | pytorch__pytorch | test/quantization/ao_migration/test_ao_migration.py | {
"start": 6360,
"end": 10435
} | class ____(AOMigrationTestCase):
def test_modules_import_nn_intrinsic(self):
module_list = [
# Modules
"_FusedModule",
"ConvBn1d",
"ConvBn2d",
"ConvBn3d",
"ConvBnReLU1d",
"ConvBnReLU2d",
"ConvBnReLU3d",
... | TestAOMigrationNNIntrinsic |
python | scipy__scipy | scipy/sparse/tests/test_base.py | {
"start": 204303,
"end": 204426
} | class ____(_MatrixMixin, TestDIA):
spcreator = dia_matrix
TestDIA.init_class()
TestDIAMatrix.init_class()
| TestDIAMatrix |
python | huggingface__transformers | tests/models/llama/test_modeling_llama.py | {
"start": 1301,
"end": 1430
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = LlamaModel
@require_torch
| LlamaModelTester |
python | doocs__leetcode | solution/3100-3199/3194.Minimum Average of Smallest and Largest Elements/Solution.py | {
"start": 0,
"end": 184
} | class ____:
def minimumAverage(self, nums: List[int]) -> float:
nums.sort()
n = len(nums)
return min(nums[i] + nums[-i - 1] for i in range(n // 2)) / 2
| Solution |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 108770,
"end": 113313
} | class ____:
def test_ab(self):
# c >= 0: a, b = [0, inf]
for c in [1., 0.]:
c = np.asarray(c)
a, b = stats.genpareto._get_support(c)
assert_equal(a, 0.)
assert_(np.isposinf(b))
# c < 0: a=0, b=1/|c|
c = np.asarray(-2.)
a, b = s... | TestGenpareto |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/rapidsmpf/utils.py | {
"start": 1515,
"end": 2116
} | class ____:
"""Metadata payload for an individual ChannelPair."""
__slots__ = ("count", "duplicated", "partitioned_on")
count: int
"""Chunk-count estimate."""
partitioned_on: tuple[str, ...]
"""Partitioned-on columns."""
duplicated: bool
"""Whether the data is duplicated on all workers.... | Metadata |
python | sympy__sympy | sympy/parsing/maxima.py | {
"start": 201,
"end": 1835
} | class ____:
def maxima_expand(expr):
return expr.expand()
def maxima_float(expr):
return expr.evalf()
def maxima_trigexpand(expr):
return expr.expand(trig=True)
def maxima_sum(a1, a2, a3, a4):
return Sum(a1, (a2, a3, a4)).doit()
def maxima_product(a1, a2, a3, a4):... | MaximaHelpers |
python | django-haystack__django-haystack | test_haystack/test_discovery.py | {
"start": 832,
"end": 2119
} | class ____(TestCase):
def test_discovery(self):
old_ui = connections["default"].get_unified_index()
connections["default"]._index = UnifiedIndex()
ui = connections["default"].get_unified_index()
self.assertEqual(len(ui.get_indexed_models()), EXPECTED_INDEX_MODEL_COUNT)
# Tes... | AutomaticDiscoveryTestCase |
python | Textualize__textual | src/textual/worker.py | {
"start": 2541,
"end": 13799
} | class ____(Generic[ResultType]):
"""A class to manage concurrent work (either a task or a thread)."""
@rich.repr.auto
class StateChanged(Message, bubble=False, namespace="worker"):
"""The worker state changed."""
def __init__(self, worker: Worker, state: WorkerState) -> None:
"... | Worker |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_value_at_index.py | {
"start": 2207,
"end": 11242
} | class ____(ColumnMapExpectation):
"""Expect a specific value at a given index location within each element of the column."""
# These examples will be shown in the public gallery, and also executed as unit tests for your Expectation
examples = [
{
"data": {
"mostly_has_de... | ExpectValueAtIndex |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.