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 | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 366279,
"end": 367597
} | class ____(invgauss_gen):
r"""A Wald continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `wald` is:
.. math::
f(x) = \frac{1}{\sqrt{2\pi x^3}} \exp(- \frac{ (x-1)^2 }{ 2x })
for :math:`x >= 0`.
`wald` is a special case of `invgauss`... | wald_gen |
python | aimacode__aima-python | probability4e.py | {
"start": 24957,
"end": 26117
} | class ____:
"""compiled version of burglary network"""
def Burglary(self, sample):
if sample['Alarm']:
if sample['Earthquake']:
return probability(0.00327)
else:
return probability(0.485)
else:
if sample['Earthquake']:
... | complied_burglary |
python | ray-project__ray | python/ray/dag/class_node.py | {
"start": 4961,
"end": 11265
} | class ____(DAGNode):
"""Represents an actor method invocation in a Ray function DAG."""
def __init__(
self,
method_name: str,
method_args: Tuple[Any],
method_kwargs: Dict[str, Any],
method_options: Dict[str, Any],
other_args_to_resolve: Dict[str, Any],
):
... | ClassMethodNode |
python | numpy__numpy | numpy/lib/tests/test_type_check.py | {
"start": 4815,
"end": 5095
} | class ____:
def test_fail(self):
z = np.array([-1, 0, 1])
res = iscomplex(z)
assert_(not np.any(res, axis=0))
def test_pass(self):
z = np.array([-1j, 1, 0])
res = iscomplex(z)
assert_array_equal(res, [1, 0, 0])
| TestIscomplex |
python | django__django | django/contrib/staticfiles/storage.py | {
"start": 17993,
"end": 20966
} | class ____(HashedFilesMixin):
manifest_version = "1.1" # the manifest format standard
manifest_name = "staticfiles.json"
manifest_strict = True
keep_intermediate_files = False
def __init__(self, *args, manifest_storage=None, **kwargs):
super().__init__(*args, **kwargs)
if manifest_... | ManifestFilesMixin |
python | readthedocs__readthedocs.org | readthedocs/api/v2/utils.py | {
"start": 9330,
"end": 9404
} | class ____(PageNumberPagination):
page_size = 15
| RemoteProjectPagination |
python | django__django | tests/template_tests/filter_tests/test_center.py | {
"start": 868,
"end": 1439
} | class ____(SimpleTestCase):
def test_center(self):
self.assertEqual(center("test", 6), " test ")
def test_non_string_input(self):
self.assertEqual(center(123, 5), " 123 ")
def test_odd_input(self):
self.assertEqual(center("odd", 6), " odd ")
def test_even_input(self):
... | FunctionTests |
python | getsentry__sentry | src/sentry/constants.py | {
"start": 16029,
"end": 18193
} | class ____:
UNPUBLISHED = 0
PUBLISHED = 1
INTERNAL = 2
PUBLISH_REQUEST_INPROGRESS = 3
DELETION_IN_PROGRESS = 4
UNPUBLISHED_STR = "unpublished"
PUBLISHED_STR = "published"
INTERNAL_STR = "internal"
PUBLISH_REQUEST_INPROGRESS_STR = "publish_request_inprogress"
DELETION_IN_PROGRESS_... | SentryAppStatus |
python | walkccc__LeetCode | solutions/1582. Special Positions in a Binary Matrix/1582.py | {
"start": 0,
"end": 441
} | class ____:
def numSpecial(self, mat: list[list[int]]) -> int:
m = len(mat)
n = len(mat[0])
ans = 0
rowOnes = [0] * m
colOnes = [0] * n
for i in range(m):
for j in range(n):
if mat[i][j] == 1:
rowOnes[i] += 1
colOnes[j] += 1
for i in range(m):
for ... | Solution |
python | numpy__numpy | numpy/lib/tests/test_recfunctions.py | {
"start": 39991,
"end": 43278
} | class ____:
@classmethod
def setup_method(cls):
cls.a = np.array(list(zip(np.arange(10), np.arange(50, 60),
np.arange(100, 110))),
dtype=[('a', int), ('b', int), ('c', int)])
cls.b = np.array(list(zip(np.arange(10), np.arange(65, 75),
... | TestJoinBy2 |
python | huggingface__transformers | src/transformers/models/roc_bert/modeling_roc_bert.py | {
"start": 34662,
"end": 45377
} | class ____(RoCBertPreTrainedModel):
_tied_weights_keys = {
"cls.predictions.decoder.bias": "cls.predictions.bias",
"cls.predictions.decoder.weight": "roc_bert.embeddings.word_embeddings.weight",
}
def __init__(self, config):
super().__init__(config)
self.roc_bert = RoCBertM... | RoCBertForPreTraining |
python | getsentry__sentry | src/sentry/relay/projectconfig_cache/redis.py | {
"start": 415,
"end": 3870
} | class ____(ProjectConfigCache):
def __init__(self, **options):
cluster_key = options.get("cluster", "default")
self.cluster = redis.redis_clusters.get_binary(cluster_key)
read_cluster_key = options.get("read_cluster", cluster_key)
self.cluster_read = redis.redis_clusters.get_binary(... | RedisProjectConfigCache |
python | getsentry__sentry | src/sentry/api/endpoints/oauth_userinfo.py | {
"start": 764,
"end": 2196
} | class ____(Endpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.ENTERPRISE
authentication_classes = ()
permission_classes = ()
def get(self, request: Request) -> Response:
try:
access_token = get_authorization_header(request).split()[1].d... | OAuthUserInfoEndpoint |
python | neetcode-gh__leetcode | python/0146-lru-cache.py | {
"start": 123,
"end": 1300
} | class ____:
def __init__(self, capacity: int):
self.cap = capacity
self.cache = {} # map key to node
self.left, self.right = Node(0, 0), Node(0, 0)
self.left.next, self.right.prev = self.right, self.left
# remove node from list
def remove(self, node):
prev, nxt = n... | LRUCache |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/vector/vectorize_reward.py | {
"start": 1676,
"end": 3094
} | class ____(VectorRewardWrapper):
"""Vectorizes a single-agent transform reward wrapper for vector environments.
An example such that applies a ReLU to the reward:
>>> import gymnasium as gym
>>> from gymnasium.wrappers import TransformReward
>>> envs = gym.make_vec("MountainCarContinuou... | VectorizeTransformReward |
python | huggingface__transformers | src/transformers/models/dbrx/configuration_dbrx.py | {
"start": 896,
"end": 2083
} | class ____(PreTrainedConfig):
"""Configuration class for Dbrx Attention.
[`DbrxAttention`] class. It is used to instantiate attention layers
according to the specified arguments, defining the layers architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the mo... | DbrxAttentionConfig |
python | django__django | tests/custom_lookups/tests.py | {
"start": 26647,
"end": 27442
} | class ____(SimpleTestCase):
def test_overridden_get_lookup(self):
q = CustomModel.objects.filter(field__lookupfunc_monkeys=3)
self.assertIn("monkeys()", str(q.query))
def test_overridden_get_transform(self):
q = CustomModel.objects.filter(field__transformfunc_banana=3)
self.asse... | CustomizedMethodsTests |
python | spyder-ide__spyder | spyder/plugins/completion/providers/snippets/widgets/snippetsconfig.py | {
"start": 26074,
"end": 31320
} | class ____(QTableView):
def __init__(self, parent, proxy, language=None):
super().__init__()
self._parent = parent
self.language = language
self.proxy = proxy
self.source_model = proxy.get_model(self, language.lower())
self.setModel(self.source_model)
self.set... | SnippetTable |
python | huggingface__transformers | src/transformers/models/bit/modeling_bit.py | {
"start": 18610,
"end": 21012
} | class ____(nn.Module):
def __init__(self, config: BitConfig):
super().__init__()
self.stages = nn.ModuleList([])
prev_chs = config.embedding_size
# These needs to stay hardcoded
current_stride = 4
dilation = 1
layer_dropouts = [
x.tolist()
... | BitEncoder |
python | ray-project__ray | python/ray/tune/schedulers/async_hyperband.py | {
"start": 6964,
"end": 10201
} | class ____:
"""Bookkeeping system to track the cutoffs.
Rungs are created in reversed order so that we can more easily find
the correct rung corresponding to the current iteration of the result.
Example:
>>> trial1, trial2, trial3 = ... # doctest: +SKIP
>>> b = _Bracket(1, 10, 2, 0) # ... | _Bracket |
python | scipy__scipy | scipy/stats/tests/test_multivariate.py | {
"start": 155040,
"end": 167354
} | class ____:
def get_rng(self):
return np.random.default_rng(628174795866951638)
def test_process_parameters(self):
message = "`row` must be one-dimensional"
with pytest.raises(ValueError, match=message):
random_table([[1, 2]], [1, 2])
message = "`col` must be one-di... | TestRandomTable |
python | getsentry__sentry | src/sentry/issues/endpoints/project_user_issue.py | {
"start": 1472,
"end": 2477
} | class ____(BaseUserIssueFormatter):
def get_issue_type(self) -> type[GroupType]:
return ErrorGroupType
def get_issue_title(self) -> str:
return f"{self.data.get('transaction')}"
def get_issue_subtitle(self) -> str:
return f"User flagged issue on {self.data.get('transaction')}"
... | DefaultUserIssueFormatter |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_ipv6.py | {
"start": 1652,
"end": 4451
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid IPv6 addresses."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"well_formed_ipv6": [
... | ExpectColumnValuesToBeValidIpv6 |
python | dagster-io__dagster | python_modules/libraries/dagster-dbt/dagster_dbt/cloud_v2/sensor_builder.py | {
"start": 1307,
"end": 1467
} | class ____:
idx: int
asset_events: Sequence[AssetMaterialization]
all_asset_keys_materialized: set[AssetKey]
@whitelist_for_serdes
@record
| BatchResult |
python | sqlalchemy__sqlalchemy | test/ext/test_associationproxy.py | {
"start": 29543,
"end": 31461
} | class ____(ListTest):
@classmethod
def define_tables(cls, metadata):
Table(
"Parent",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(128)),
)
Table(
... | ProxyFactoryTest |
python | walkccc__LeetCode | solutions/2602. Minimum Operations to Make All Array Elements Equal/2602.py | {
"start": 0,
"end": 391
} | class ____:
def minOperations(self, nums: list[int], queries: list[int]) -> list[int]:
n = len(nums)
nums.sort()
prefix = list(itertools.accumulate(nums, initial=0))
splits = [(query, bisect.bisect_right(nums, query)) for query in queries]
return [(query * i - prefix[i]) +
(prefix[-1] ... | Solution |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/events.py | {
"start": 3344,
"end": 3631
} | class ____(Event):
__slots__ = ('encoding',)
def __init__(self, start_mark=None, end_mark=None, encoding=None, comment=None):
# type: (Any, Any, Any, Any) -> None
Event.__init__(self, start_mark, end_mark, comment)
self.encoding = encoding
| StreamStartEvent |
python | getsentry__sentry | src/sentry/preprod/analytics.py | {
"start": 3478,
"end": 3686
} | class ____(analytics.Event):
organization_id: int
user_id: int | None = None
artifact_id: str
@analytics.eventclass("preprod_artifact.api.pr_page.comments")
| PreprodApiPrPageSizeAnalysisDownloadEvent |
python | coleifer__peewee | tests/psycopg3_ext.py | {
"start": 10679,
"end": 11414
} | class ____(ModelTestCase):
database = db
requires = [UUIDList]
def test_array_of_uuids(self):
u1, u2, u3, u4 = [uuid.uuid4() for _ in range(4)]
a = UUIDList.create(key='a', id_list=[u1, u2, u3],
id_list_native=[u1, u2, u3])
b = UUIDList.create(key='b', id... | TestPsycopg3ArrayUUIDField |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/namedTuple7.py | {
"start": 191,
"end": 446
} | class ____(NamedTuple, Generic[_T1]):
a: _T1
b: int
c: list[_T1]
reveal_type(NT1(3, 4, []), expected_text="NT1[int]")
reveal_type(NT1(3.4, 4, [1, 2]), expected_text="NT1[float]")
reveal_type(NT1(3.4, 4, [2j]), expected_text="NT1[complex]")
| NT1 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/writeonly.py | {
"start": 4827,
"end": 14913
} | class ____(
attributes._HasCollectionAdapter, attributes._AttributeImpl
):
uses_objects: bool = True
default_accepts_scalar_loader: bool = False
supports_population: bool = False
_supports_dynamic_iteration: bool = False
collection: bool = False
dynamic: bool = True
order_by: _Relationsh... | _WriteOnlyAttributeImpl |
python | huggingface__transformers | tests/models/deepseek_vl_hybrid/test_modeling_deepseek_vl_hybrid.py | {
"start": 1311,
"end": 5299
} | class ____:
def __init__(
self,
parent,
batch_size=2,
seq_length=25,
num_channels=3,
initializer_range=0.02,
is_training=True,
use_cache=False,
text_config={
"num_hidden_layers": 2,
"vocab_size": 99,
"hidden_... | DeepseekVLHybridModelTester |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 18078,
"end": 18552
} | class ____(GroupType):
type_id = 1020
slug = "db_query_injection_vulnerability"
description = "Potential Database Query Injection Vulnerability"
category = GroupCategory.PERFORMANCE.value
category_v2 = GroupCategory.DB_QUERY.value
enable_auto_resolve = False
enable_escalation_detection = Fal... | DBQueryInjectionVulnerabilityGroupType |
python | palantir__python-language-server | pyls/lsp.py | {
"start": 173,
"end": 621
} | class ____(object):
Text = 1
Method = 2
Function = 3
Constructor = 4
Field = 5
Variable = 6
Class = 7
Interface = 8
Module = 9
Property = 10
Unit = 11
Value = 12
Enum = 13
Keyword = 14
Snippet = 15
Color = 16
File = 17
Reference = 18
Folder = 1... | CompletionItemKind |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 8284,
"end": 8505
} | class ____(models.Model):
poll = CustomAttrNameOneToOneField(Poll, models.CASCADE, attr_name="custom_poll")
history = HistoricalRecords(excluded_field_kwargs={"poll": {"attr_name"}})
| ModelWithCustomAttrOneToOneField |
python | getsentry__sentry | src/sentry/api/endpoints/relay/details.py | {
"start": 422,
"end": 1020
} | class ____(Endpoint):
publish_status = {
"DELETE": ApiPublishStatus.PRIVATE,
}
permission_classes = (SuperuserPermission,)
owner = ApiOwner.OWNERS_INGEST
def delete(self, request: Request, relay_id) -> Response:
"""
Delete one Relay
````````````````
:auth: re... | RelayDetailsEndpoint |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 19052,
"end": 19919
} | class ____(MixinSequenceOfValues):
"""
Colorbar text
Parameters
----------
theme_element : element_text
Notes
-----
Horizontal alignment `ha` has no effect when the text is to the
left or to the right. Likewise vertical alignment `va` has no
effect when the text at the top or t... | legend_text_colorbar |
python | run-llama__llama_index | llama-index-utils/llama-index-utils-azure/llama_index/utils/azure/table.py | {
"start": 920,
"end": 8536
} | class ____(str, Enum):
"""
Whether the AzureKVStore operates on an Azure Table Storage or Cosmos DB.
"""
COSMOS = "cosmos"
STORAGE = "storage"
def sanitize_table_name(table_name: str) -> str:
"""
Sanitize the table name to ensure it is valid for use in Azure Table Storage
or Cosmos DB... | ServiceMode |
python | ray-project__ray | python/ray/data/namespace_expressions/list_namespace.py | {
"start": 394,
"end": 4049
} | class ____:
"""Namespace for list operations on expression columns.
This namespace provides methods for operating on list-typed columns using
PyArrow compute functions.
Example:
>>> from ray.data.expressions import col
>>> # Get length of list column
>>> expr = col("items").lis... | _ListNamespace |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 18656,
"end": 18745
} | class ____(IterableExportEventsStreamAdjustableRange):
data_field = "purchase"
| Purchase |
python | tensorflow__tensorflow | tensorflow/python/distribute/distribute_lib.py | {
"start": 176286,
"end": 178729
} | class ____(ReplicaContext):
"""ReplicaContext for _DefaultDistributionStrategy."""
@property
def replica_id_in_sync_group(self):
# Return 0 instead of a constant tensor to avoid creating a new node for
# users who don't use distribution strategy.
return 0
# -----------------------------------------... | _DefaultReplicaContext |
python | django__django | tests/max_lengths/tests.py | {
"start": 987,
"end": 1604
} | class ____(TestCase):
def test_custom_max_lengths(self):
args = {
"email": "someone@example.com",
"vcard": "vcard",
"homepage": "http://example.com/",
"avatar": "me.jpg",
}
for field in ("email", "vcard", "homepage", "avatar"):
new... | MaxLengthORMTests |
python | langchain-ai__langchain | libs/langchain/langchain_classic/evaluation/parsing/base.py | {
"start": 2678,
"end": 5601
} | class ____(StringEvaluator):
"""Json Equality Evaluator.
Evaluate whether the prediction is equal to the reference after
parsing both as JSON.
This evaluator checks if the prediction, after parsing as JSON, is equal
to the reference,
which is also parsed as JSON. It does not require an inp... | JsonEqualityEvaluator |
python | Lightning-AI__lightning | tests/tests_pytorch/models/test_hparams.py | {
"start": 23498,
"end": 24817
} | class ____(CustomBoringModel):
def __init__(self):
super().__init__()
@pytest.mark.parametrize("cls", [BoringModel, NoArgsSubClassBoringModel])
def test_model_nohparams_train_test(tmp_path, cls):
"""Test models that do not take any argument in init."""
model = cls()
trainer = Trainer(max_epoch... | NoArgsSubClassBoringModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-pgvector/destination_pgvector/common/destinations/record_processor.py | {
"start": 1145,
"end": 10460
} | class ____(abc.ABC):
"""Abstract base class for classes which can process Airbyte messages from a source.
This class is responsible for all aspects of handling Airbyte protocol.
The class should be passed a catalog manager and stream manager class to handle the
catalog and state aspects of the protoco... | RecordProcessorBase |
python | modin-project__modin | modin/pandas/window.py | {
"start": 11442,
"end": 17537
} | class ____(ClassLogger):
def __init__(self, dataframe, min_periods=1, axis=0, method="single"):
self._dataframe = dataframe
self._query_compiler = dataframe._query_compiler
self.expanding_args = [min_periods, axis, method]
self.axis = axis
def aggregate(self, func, *args, **kwar... | Expanding |
python | bokeh__bokeh | examples/advanced/extensions/font-awesome/fontawesome_icon.py | {
"start": 131,
"end": 758
} | class ____(Icon):
""" A "stock" icon based on FontAwesome. """
__implementation__ = "fontawesome_icon.ts"
__dependencies__ = {"font-awesome": "^4.6.3"}
icon_name = Required(Enum(NamedIcon), help="""
What icon to use. See http://fortawesome.github.io/Font-Awesome/icons/
for the list of availabl... | FontAwesomeIcon |
python | PrefectHQ__prefect | tests/test_background_tasks.py | {
"start": 9255,
"end": 13182
} | class ____:
async def test_map(self, async_foo_task: Task[Any, int]):
task_runs = async_foo_task.map([1, 2, 3], deferred=True)
assert len(task_runs) == 3
result_store = await result_store_from_task(async_foo_task)
for i, task_run in enumerate(task_runs):
assert task_ru... | TestMap |
python | astropy__astropy | astropy/table/tests/test_init_table.py | {
"start": 17406,
"end": 18345
} | class ____:
# Note table_table.TestEmptyData tests initializing a completely empty
# table and adding data.
def test_data_none_with_cols(self, table_type):
"""
Test different ways of initing an empty table
"""
np_t = np.empty(0, dtype=[("a", "f4", (2,)), ("b", "i4")])
... | TestInitFromNone |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_scatter03.py | {
"start": 315,
"end": 1476
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_scatter03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.g... | TestCompareXLSXFiles |
python | tensorflow__tensorflow | tensorflow/python/framework/test_util_test.py | {
"start": 43110,
"end": 44935
} | class ____(test_util.TensorFlowTestCase):
def tearDown(self):
super().tearDown()
config.set_synchronous_execution(True)
def test_sync_device_cpu(self):
with context.eager_mode(), ops.device("/CPU:0"):
config.set_synchronous_execution(False)
start = time.time()
test_ops.sleep_op(sleep... | SyncDevicesTest |
python | boto__boto3 | boto3/docs/base.py | {
"start": 1496,
"end": 2103
} | class ____(BaseDocumenter):
def __init__(self, resource, root_docs_path):
super().__init__(resource)
self._root_docs_path = root_docs_path
self._resource_sub_path = self._resource_name.lower()
if self._resource_name == self._service_name:
self._resource_sub_path = 'servic... | NestedDocumenter |
python | google__pytype | build_scripts/test_module.py | {
"start": 2188,
"end": 8764
} | class ____:
"""A class which reports results of test runs."""
def __init__(self, options, stats_collector):
self._options = options
self._stats_collector = stats_collector
def _method_info(self, prefix, fq_method_name, group):
common_msg = f"{prefix}: {fq_method_name}"
log_message = f"{common_ms... | ResultReporter |
python | tensorflow__tensorflow | tensorflow/python/ops/nccl_ops_test.py | {
"start": 6381,
"end": 6931
} | class ____(NcclTestCase):
"""Test all-reduce vs. single-reduce plus broadcast in one session.run."""
def _Combined(self, tensors, devices):
all_reduce_tensors = _NcclAllReduce(nccl_ops.all_sum, tensors, devices)
single_reduce_tensors = _NcclReduce(nccl_ops.reduce_sum, tensors, devices)
broadcast_tensor... | CombinedTest |
python | kubernetes-client__python | kubernetes/client/models/v1_exempt_priority_level_configuration.py | {
"start": 383,
"end": 7084
} | 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... | V1ExemptPriorityLevelConfiguration |
python | scikit-learn__scikit-learn | sklearn/model_selection/_classification_threshold.py | {
"start": 17363,
"end": 32666
} | class ____(BaseThresholdClassifier):
"""Classifier that post-tunes the decision threshold using cross-validation.
This estimator post-tunes the decision threshold (cut-off point) that is
used for converting posterior probability estimates (i.e. output of
`predict_proba`) or decision scores (i.e. output... | TunedThresholdClassifierCV |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/event_log/base.py | {
"start": 2317,
"end": 5025
} | class ____:
asset_key: AssetKey
last_materialization_record: Optional[EventLogRecord] = None
last_run_id: Optional[str] = None
asset_details: Optional[AssetDetails] = None
cached_status: Optional[
Annotated[
"AssetStatusCacheValue", ImportFrom("dagster._core.storage.partition_sta... | AssetEntry |
python | PrefectHQ__prefect | tests/_internal/pydantic/test_validated_func.py | {
"start": 11657,
"end": 12356
} | class ____:
"""Test handling of forward references and `from __future__ import annotations`."""
def test_pydantic_model_with_future_annotations(self):
"""Test that Pydantic models work with forward reference annotations.
This is a regression test for issue #19288.
When using `from __fu... | TestForwardReferences |
python | huggingface__transformers | src/transformers/models/layoutlm/modeling_layoutlm.py | {
"start": 22630,
"end": 27782
} | class ____(LayoutLMPreTrainedModel):
_tied_weights_keys = {
"cls.predictions.decoder.bias": "cls.predictions.bias",
"cls.predictions.decoder.weight": "layoutlm.embeddings.word_embeddings.weight",
}
def __init__(self, config):
super().__init__(config)
self.layoutlm = LayoutL... | LayoutLMForMaskedLM |
python | scrapy__scrapy | tests/test_spidermiddleware.py | {
"start": 845,
"end": 1765
} | class ____:
def setup_method(self):
self.request = Request("http://example.com/index.html")
self.response = Response(self.request.url, request=self.request)
self.crawler = get_crawler(Spider, {"SPIDER_MIDDLEWARES_BASE": {}})
self.crawler.spider = self.crawler._create_spider("foo")
... | TestSpiderMiddleware |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/benchmarks_test.py | {
"start": 1876,
"end": 3463
} | class ____(test.Benchmark):
def _run(self, func, num_iters, execution_mode=None):
func()
start = time.time()
for _ in range(num_iters):
func()
end = time.time()
mean_us = (end - start) * 1e6 / num_iters
self.report_benchmark(
iters=num_iters,
wall_time=mean_us,
e... | SavingBenchmarks |
python | kamyu104__LeetCode-Solutions | Python/stream-of-characters2.py | {
"start": 657,
"end": 816
} | class ____(object):
def __init__(self):
self.children = collections.defaultdict(AhoNode)
self.suffix = None
self.outputs = []
| AhoNode |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 28411,
"end": 34144
} | class ____(PyObjectPtr):
_typename = 'PyFrameObject'
def __init__(self, gdbval, cast_to=None):
PyObjectPtr.__init__(self, gdbval, cast_to)
if not self.is_optimized_out():
self.co = PyCodeObjectPtr.from_pyobject_ptr(self.field('f_code'))
self.co_name = self.co.pyop_field... | PyFrameObjectPtr |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol41.py | {
"start": 348,
"end": 472
} | class ____:
def __buffer__(self, __flags: int) -> memoryview: ...
MyAnyStr = TypeVar("MyAnyStr", MyStr, MyBytes)
| MyBytes |
python | gevent__gevent | src/greentest/3.9/test_ftplib.py | {
"start": 42238,
"end": 42747
} | class ____(TestCase):
def test__all__(self):
blacklist = {'MSG_OOB', 'FTP_PORT', 'MAXLINE', 'CRLF', 'B_CRLF',
'Error', 'parse150', 'parse227', 'parse229', 'parse257',
'print_line', 'ftpcp', 'test'}
support.check__all__(self, ftplib, blacklist=blacklist)
de... | MiscTestCase |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_S.py | {
"start": 31120,
"end": 32511
} | class ____(Benchmark):
r"""
Six Hump Camel objective function.
This class defines the Six Hump Camel [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{SixHumpCamel}}(x) = 4x_1^2+x_1x_2-4x_2^2-2.1x_1^4+
... | SixHumpCamel |
python | ansible__ansible | test/units/module_utils/basic/test_exit_json.py | {
"start": 501,
"end": 3933
} | class ____:
"""
Test that various means of calling exitJson and FailJson return the messages they've been given
"""
DATA: tuple[tuple[dict[str, t.Any]], ...] = (
({}, {'invocation': EMPTY_INVOCATION}),
({'msg': 'message'}, {'msg': 'message', 'invocation': EMPTY_INVOCATION}),
({'m... | TestAnsibleModuleExitJson |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/readline_ui.py | {
"start": 892,
"end": 4020
} | class ____(base_ui.BaseUI):
"""Readline-based Command-line UI."""
def __init__(self, on_ui_exit=None, config=None):
base_ui.BaseUI.__init__(self, on_ui_exit=on_ui_exit, config=config)
self._init_input()
def _init_input(self):
readline.parse_and_bind("set editing-mode emacs")
# Disable default r... | ReadlineUI |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 120435,
"end": 120824
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(
sgqlc.types.non_null(ProjectOrderField), graphql_name="field"
)
direction = sgqlc.types.Field(
sgqlc.type... | ProjectOrder |
python | sphinx-doc__sphinx | sphinx/util/cfamily.py | {
"start": 8401,
"end": 8536
} | class ____(ASTBaseBase):
pass
################################################################################
| ASTBaseParenExprList |
python | PrefectHQ__prefect | src/prefect/server/database/configurations.py | {
"start": 13054,
"end": 21550
} | class ____(BaseDatabaseConfiguration):
MIN_SQLITE_VERSION = (3, 24, 0)
async def engine(self) -> AsyncEngine:
"""Retrieves an async SQLAlchemy engine.
Args:
connection_url (str, optional): The database connection string.
Defaults to self.connection_url
e... | AioSqliteConfiguration |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 4786,
"end": 5197
} | class ____(StreamlitAPIWarning):
"""Print a pretty message when a Streamlit command requires a dependency
that is not one of our core dependencies.
"""
def __init__(self, module_name: str, *args: Any) -> None:
message = (
f'This Streamlit command requires module "{module_name}" to b... | StreamlitModuleNotFoundError |
python | huggingface__transformers | tests/models/sew/test_modeling_sew.py | {
"start": 10378,
"end": 15121
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (SEWForCTC, SEWModel, SEWForSequenceClassification) if is_torch_available() else ()
pipeline_model_mapping = (
{
"audio-classification": SEWForSequenceClassification,
"automatic-speech-recog... | SEWModelTest |
python | PyCQA__pylint | doc/data/messages/n/no-staticmethod-decorator/good.py | {
"start": 0,
"end": 63
} | class ____:
@staticmethod
def bore(self):
pass
| Worm |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes5.py | {
"start": 5997,
"end": 6060
} | class ____(PeerClass1, PeerClass2):
pass
| MultipleInheritance1 |
python | django__django | django/views/generic/dates.py | {
"start": 16537,
"end": 18384
} | class ____(YearMixin, WeekMixin, BaseDateListView):
"""
Base view for a list of objects published in a given week.
This requires subclassing to provide a response mixin.
"""
def get_dated_items(self):
"""Return (date_list, items, extra_context) for this request."""
year = self.get_... | BaseWeekArchiveView |
python | PrefectHQ__prefect | tests/test_settings.py | {
"start": 48191,
"end": 59000
} | class ____:
def test_database_connection_url_templates_password(self):
with temporary_settings(
{
PREFECT_SERVER_DATABASE_CONNECTION_URL: (
"${PREFECT_API_DATABASE_PASSWORD}/test"
),
PREFECT_API_DATABASE_PASSWORD: "password",
... | TestDatabaseSettings |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 115407,
"end": 118246
} | class ____(rv_continuous):
r"""A generalized gamma continuous random variable.
%(before_notes)s
See Also
--------
gamma, invgamma, weibull_min
Notes
-----
The probability density function for `gengamma` is ([1]_):
.. math::
f(x, a, c) = \frac{|c| x^{c a-1} \exp(-x^c)}{\G... | gengamma_gen |
python | ansible__ansible | lib/ansible/playbook/base.py | {
"start": 3394,
"end": 3578
} | class ____:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
return getattr(objtype, f'_{self.name}')()
| _ClassProperty |
python | huggingface__transformers | src/transformers/models/voxtral/modular_voxtral.py | {
"start": 1876,
"end": 4531
} | class ____(Qwen2AudioEncoder):
_can_record_outputs = {
"attentions": VoxtralAttention,
"hidden_states": VoxtralEncoderLayer,
}
@check_model_inputs()
def forward(
self,
input_features,
attention_mask=None,
**kwargs: Unpack[TransformersKwargs],
):
... | VoxtralEncoder |
python | graphql-python__graphene | graphene/relay/tests/test_mutation.py | {
"start": 647,
"end": 764
} | class ____:
__slots__ = ("phrase",)
def __init__(self, phrase):
self.phrase = phrase
| FixedSaySomething |
python | scipy__scipy | scipy/linalg/tests/test_basic.py | {
"start": 86145,
"end": 86944
} | class ____:
def test_solve(self):
assert_no_overwrite(solve, [(3, 3), (3,)])
def test_solve_triangular(self):
assert_no_overwrite(solve_triangular, [(3, 3), (3,)])
def test_solve_banded(self):
assert_no_overwrite(lambda ab, b: solve_banded((2, 1), ab, b),
... | TestOverwrite |
python | pytorch__pytorch | torchgen/api/python.py | {
"start": 9063,
"end": 12566
} | class ____:
name: str
type: Type
default: str | None
# Used to generate the default init expr for some PythonArgParser outputs, e.g.:
#
# _r.layoutWithDefault(3, layout_from_backend(self.options().backend())))
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
... | PythonArgument |
python | getsentry__sentry | src/sentry/api/endpoints/event_apple_crash_report.py | {
"start": 580,
"end": 2522
} | class ____(ProjectEndpoint):
owner = ApiOwner.OWNERS_INGEST
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def get(self, request: Request, project, event_id) -> HttpResponseBase:
"""
Retrieve an Apple Crash Report from an event
````````````````````````````````````... | EventAppleCrashReportEndpoint |
python | django__django | tests/admin_views/tests.py | {
"start": 342610,
"end": 344058
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
def test_logout(self):
self.client.force_login(self.superuser)
response = self.client.post(r... | AdminViewLogoutTests |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/daemon_cursor.py | {
"start": 69,
"end": 421
} | class ____:
@abstractmethod
def get_cursor_values(self, keys: set[str]) -> Mapping[str, str]:
"""Retrieve the value for a given key in the current deployment."""
@abstractmethod
def set_cursor_values(self, pairs: Mapping[str, str]) -> None:
"""Set the value for a given key in the curren... | DaemonCursorStorage |
python | bokeh__bokeh | tests/unit/bokeh/application/handlers/test_notebook__handlers.py | {
"start": 1821,
"end": 3917
} | class ____:
# Public methods ----------------------------------------------------------
def test_runner_strips_line_magics(self, ipython) -> None:
doc = Document()
source = nbformat.v4.new_notebook()
source.cells.append(nbformat.v4.new_code_cell('%time'))
def load(filename):
... | Test_NotebookHandler |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_mixed_precision.py | {
"start": 43631,
"end": 50038
} | class ____(FSDPTest):
@property
def world_size(self):
return 2
@skip_if_lt_x_gpu(2)
def test_float16_on_one_submodule(self):
forward_inputs: dict[str, nn.Module] = {}
float16 = MixedPrecision(param_dtype=torch.float16, cast_forward_inputs=True)
model = SaveForwardInputs... | TestFSDPDifferentSubmodulePrecision |
python | huggingface__transformers | src/transformers/models/cohere2/modular_cohere2.py | {
"start": 1622,
"end": 10126
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`CohereModel`]. It is used to instantiate an Cohere
model according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to... | Cohere2Config |
python | PrefectHQ__prefect | src/prefect/server/events/filters.py | {
"start": 5700,
"end": 6947
} | class ____(EventDataFilter):
since: DateTime = Field(
default_factory=lambda: prefect.types._datetime.start_of_day(
prefect.types._datetime.now("UTC")
)
- timedelta(days=180),
description="Only include events after this time (inclusive)",
)
until: DateTime = Field... | EventOccurredFilter |
python | django__django | tests/modeladmin/test_checks.py | {
"start": 46673,
"end": 48275
} | class ____(CheckTestCase):
def test_invalid_type(self):
class FakeFormSet:
pass
class ValidationTestInline(TabularInline):
model = ValidationTestInlineModel
formset = FakeFormSet
class TestModelAdmin(ModelAdmin):
inlines = [ValidationTestInli... | FormsetCheckTests |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc.py | {
"start": 68974,
"end": 76071
} | class ____(GoogleCloudBaseOperator):
"""
Instantiate a WorkflowTemplate on Google Cloud Dataproc.
The operator will wait until the WorkflowTemplate is finished executing.
.. seealso::
Please refer to:
https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.workflowTem... | DataprocInstantiateWorkflowTemplateOperator |
python | django__django | tests/forms_tests/tests/tests.py | {
"start": 599,
"end": 732
} | class ____(ModelForm):
class Meta:
model = OptionalMultiChoiceModel
fields = "__all__"
| OptionalMultiChoiceModelForm |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_Z.py | {
"start": 5643,
"end": 6758
} | class ____(Benchmark):
r"""
Zettl objective function.
This class defines the Zirilli [1]_ global optimization problem. This is a
unimodal minimization problem defined as follows:
.. math::
f_{\text{Zirilli}}(x) = 0.25x_1^4 - 0.5x_1^2 + 0.1x_1 + 0.5x_2^2
Here, :math:`n` represents th... | Zirilli |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 59344,
"end": 60270
} | class ____(Request):
"""
get task scalar metrics and variants
:param task: task ID
:type task: str
"""
_service = "events"
_action = "get_scalar_metrics_and_variants"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {"task": {"description": "task ID", "... | GetScalarMetricsAndVariantsRequest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_annotations/simple_magic_methods.py | {
"start": 0,
"end": 562
} | class ____:
def __str__(self):
...
def __repr__(self):
...
def __len__(self):
...
def __length_hint__(self):
...
def __init__(self):
...
def __del__(self):
...
def __bool__(self):
...
def __bytes__(self):
...
def... | Foo |
python | MongoEngine__mongoengine | tests/fields/test_datetime_field.py | {
"start": 223,
"end": 6498
} | class ____(MongoDBTestCase):
def test_datetime_from_empty_string(self):
"""
Ensure an exception is raised when trying to
cast an empty string to datetime.
"""
class MyDoc(Document):
dt = DateTimeField()
md = MyDoc(dt="")
with pytest.raises(Valida... | TestDateTimeField |
python | huggingface__transformers | src/transformers/models/gpt_oss/modular_gpt_oss.py | {
"start": 1812,
"end": 2219
} | class ____(LlamaRMSNorm):
def forward(self, hidden_states):
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
r... | GptOssRMSNorm |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1118171,
"end": 1118840
} | class ____(sgqlc.types.Type, Node, UniformResourceLocatable):
"""Represents a 'convert_to_draft' event on a given pull request."""
__schema__ = github_schema
__field_names__ = ("actor", "created_at", "pull_request")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who ... | ConvertToDraftEvent |
python | pydata__xarray | xarray/core/treenode.py | {
"start": 27028,
"end": 29383
} | class ____(ValueError):
"""Error raised if two tree objects do not share the same node structure."""
def group_subtrees(
*trees: AnyNamedNode,
) -> Iterator[tuple[str, tuple[AnyNamedNode, ...]]]:
"""Iterate over subtrees grouped by relative paths in breadth-first order.
`group_subtrees` allows for ap... | TreeIsomorphismError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.