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 | readthedocs__readthedocs.org | readthedocs/projects/migrations/0055_change_help_text_description.py | {
"start": 149,
"end": 610
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0054_urlconf_blank"),
]
operations = [
migrations.AlterField(
model_name="project",
name="description",
field=models.TextField(
blank=True,
... | Migration |
python | encode__django-rest-framework | tests/test_pagination.py | {
"start": 4785,
"end": 5477
} | class ____:
"""
Integration tests for disabled pagination.
"""
def setup_method(self):
class PassThroughSerializer(serializers.BaseSerializer):
def to_representation(self, item):
return item
self.view = generics.ListAPIView.as_view(
serializer_cl... | TestPaginationDisabledIntegration |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external_data.py | {
"start": 8433,
"end": 12040
} | class ____(IHaveNew):
name: str
cron_schedule: Union[str, Sequence[str]]
job_name: str
op_selection: Optional[Sequence[str]]
mode: Optional[str]
environment_vars: Mapping[str, str]
partition_set_name: Optional[str]
execution_timezone: Optional[str]
description: Optional[str]
defa... | ScheduleSnap |
python | scikit-learn__scikit-learn | sklearn/manifold/_mds.py | {
"start": 16149,
"end": 30926
} | class ____(BaseEstimator):
"""Multidimensional scaling.
Read more in the :ref:`User Guide <multidimensional_scaling>`.
Parameters
----------
n_components : int, default=2
Number of dimensions in which to immerse the dissimilarities.
metric_mds : bool, default=True
If ``True``,... | MDS |
python | pypa__pip | src/pip/_vendor/urllib3/connectionpool.py | {
"start": 2909,
"end": 33197
} | class ____(ConnectionPool, RequestMethods):
"""
Thread-safe connection pool for one host.
:param host:
Host used for this HTTP Connection (e.g. "localhost"), passed into
:class:`http.client.HTTPConnection`.
:param port:
Port used for this HTTP Connection (None is equivalent to ... | HTTPConnectionPool |
python | kamyu104__LeetCode-Solutions | Python/visit-array-positions-to-maximize-score.py | {
"start": 34,
"end": 387
} | class ____(object):
def maxScore(self, nums, x):
"""
:type nums: List[int]
:type x: int
:rtype: int
"""
dp = [float("-inf")]*2
dp[nums[0]%2] = nums[0]
for i in xrange(1, len(nums)):
dp[nums[i]%2] = max(dp[nums[i]%2], dp[(nums[i]+1)%2]-x)+nu... | Solution |
python | wandb__wandb | wandb/vendor/pygments/lexers/jvm.py | {
"start": 54630,
"end": 66792
} | class ____(RegexLexer):
"""
For `Jasmin <http://jasmin.sourceforge.net/>`_ assembly code.
.. versionadded:: 2.0
"""
name = 'Jasmin'
aliases = ['jasmin', 'jasminxt']
filenames = ['*.j']
_whitespace = r' \n\t\r'
_ws = r'(?:[%s]+)' % _whitespace
_separator = r'%s:=' % _whitespace... | JasminLexer |
python | pyodide__pyodide | src/py/_pyodide/_core_docs.py | {
"start": 3103,
"end": 3423
} | class ____(_JsProxyMetaClass, ABCMeta):
pass
# We want to raise an error if someone tries to instantiate JsProxy directly
# since it doesn't mean anything. But we have a few reasons to do so internally.
# So we raise an error unless this private token is passed as an argument.
_instantiate_token = object()
| _ABCMeta |
python | scipy__scipy | scipy/special/tests/test_orthogonal.py | {
"start": 10971,
"end": 32878
} | class ____:
def test_regression(self):
assert_equal(orth.genlaguerre(1, 1, monic=False)(0), 2.)
assert_equal(orth.genlaguerre(1, 1, monic=True)(0), -2.)
assert_equal(orth.genlaguerre(1, 1, monic=False), np.poly1d([-1, 2]))
assert_equal(orth.genlaguerre(1, 1, monic=True), np.poly1d([1... | TestGenlaguerre |
python | eventlet__eventlet | eventlet/green/http/server.py | {
"start": 35216,
"end": 46596
} | class ____(SimpleHTTPRequestHandler):
"""Complete HTTP server with GET, HEAD and POST commands.
GET and HEAD also support running CGI scripts.
The POST command is *only* implemented for CGI scripts.
"""
# Determine platform specifics
have_fork = hasattr(os, 'fork')
# Make rfile unbuffe... | CGIHTTPRequestHandler |
python | scikit-learn__scikit-learn | sklearn/cluster/_kmeans.py | {
"start": 58140,
"end": 81912
} | class ____(_BaseKMeans):
"""
Mini-Batch K-Means clustering.
Read more in the :ref:`User Guide <mini_batch_kmeans>`.
Parameters
----------
n_clusters : int, default=8
The number of clusters to form as well as the number of
centroids to generate.
init : {'k-means++', 'rando... | MiniBatchKMeans |
python | django-import-export__django-import-export | tests/core/migrations/0007_auto_20180628_0411.py | {
"start": 109,
"end": 1622
} | class ____(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("core", "0006_auto_20171130_0147"),
]
operations = [
migrations.CreateModel(
name="Person",
fields=[
(
"id",
... | Migration |
python | dagster-io__dagster | python_modules/dagster/dagster/_vendored/dateutil/rrule.py | {
"start": 9109,
"end": 42829
} | class ____(rrulebase):
"""
That's the base of the rrule operation. It accepts all the keywords
defined in the RFC as its constructor parameters (except byday,
which was renamed to byweekday) and more. The constructor prototype is::
rrule(freq)
Where freq must be one of YEARLY, MONTHLY,... | rrule |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/subscription.py | {
"start": 793,
"end": 1067
} | class ____(graphene.Union):
class Meta:
types = (
GraphenePipelineRunLogsSubscriptionSuccess,
GraphenePipelineRunLogsSubscriptionFailure,
)
name = "PipelineRunLogsSubscriptionPayload"
| GraphenePipelineRunLogsSubscriptionPayload |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/src/connectors_qa/models.py | {
"start": 1009,
"end": 1530
} | class ____:
"""The result of a QA check
Attributes:
check (Check): The QA check that was run
connector (Connector): The connector that was checked
status (CheckStatus): The status of the check
message (str): A message explaining the result of the check
"""
check: Check
... | CheckResult |
python | zarr-developers__zarr-python | src/zarr/codecs/numcodecs/_codecs.py | {
"start": 11478,
"end": 11549
} | class ____(_NumcodecsChecksumCodec, codec_name="crc32c"):
pass
| CRC32C |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 35713,
"end": 36107
} | class ____(torch.utils.data.Sampler):
def __init__(self, dataset, batch_size):
self.dataset = dataset
self.batch_size = batch_size
def __iter__(self):
for x in torch.randperm(len(self.dataset)).split(self.batch_size):
yield x.tolist()
def __len__(self):
return i... | BulkLoadingSampler |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 36119,
"end": 36565
} | class ____(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
action: Annotated[
Literal["create"], Field(description="The action to be performed on the entities.", title="Action")
]
entities: Annotated[
list[ConnectionBody], Field(description="A list of entities to be ... | BulkCreateActionConnectionBody |
python | walkccc__LeetCode | solutions/2167. Minimum Time to Remove All Cars Containing Illegal Goods/2167-2.py | {
"start": 0,
"end": 279
} | class ____:
def minimumTime(self, s: str) -> int:
n = len(s)
ans = n
left = 0 # the minimum time to remove the illegal cars so far
for i, c in enumerate(s):
left = min(left + int(c) * 2, i + 1)
ans = min(ans, left + n - 1 - i)
return ans
| Solution |
python | pallets__flask | tests/test_helpers.py | {
"start": 9596,
"end": 11224
} | class ____:
@pytest.mark.parametrize(
("debug", "expect"),
[
("", False),
("0", False),
("False", False),
("No", False),
("True", True),
],
)
def test_get_debug_flag(self, monkeypatch, debug, expect):
monkeypatch.set... | TestHelpers |
python | spack__spack | var/spack/test_repos/spack_repo/find/packages/a0/package.py | {
"start": 217,
"end": 317
} | class ____(Package):
version("1.2")
version("1.1")
depends_on("b0")
depends_on("c0")
| A0 |
python | allegroai__clearml | examples/hyperdatasets/create_qa_entries.py | {
"start": 1134,
"end": 1574
} | class ____(DataSubEntry):
def __init__(self, name: str, text: str, role: str, preview_source: Optional[str] = None):
super().__init__(
name=name,
source=f"text://{uuid.uuid4().hex}", # or hash of text sha256(text)
preview_source=preview_source,
metadata={"tex... | QADataSubEntry |
python | sympy__sympy | sympy/plotting/backends/matplotlibbackend/matplotlib.py | {
"start": 1423,
"end": 12548
} | class ____(base_backend.Plot):
""" This class implements the functionalities to use Matplotlib with SymPy
plotting functions.
"""
def __init__(self, *series, **kwargs):
super().__init__(*series, **kwargs)
self.matplotlib = import_module('matplotlib',
import_kwargs={'fromlist... | MatplotlibBackend |
python | Textualize__textual | tests/input/test_input_messages.py | {
"start": 171,
"end": 2706
} | class ____(App[None]):
def __init__(self, initial: str | None = None) -> None:
super().__init__()
self.messages: list[str] = []
self._initial = initial
def compose(self) -> ComposeResult:
if self._initial:
yield Input(self._initial)
else:
yield In... | InputApp |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 808109,
"end": 808550
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("name", "type", "url")
name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name")
type = sgqlc.types.Field(
sgqlc.types.non_null(MigrationSource... | MigrationSource |
python | numba__numba | numba/parfors/parfor_lowering.py | {
"start": 17725,
"end": 87652
} | class ____(InternalError):
def __init__(self, inst):
super().__init__(f"Unknown reduce instruction node: {inst}")
def _lower_trivial_inplace_binops(parfor, lowerer, thread_count_var, reduce_info):
"""Lower trivial inplace-binop reduction.
"""
for inst in reduce_info.redvar_info.reduce_nodes:
... | ParforsUnexpectedReduceNodeError |
python | PyCQA__isort | tests/unit/test_io.py | {
"start": 131,
"end": 1475
} | class ____:
@pytest.mark.skipif(sys.platform == "win32", reason="Can't run file encoding test in AppVeyor")
def test_read(self, tmpdir):
test_file_content = """# -*- encoding: ascii -*-
import Ὡ
"""
test_file = tmpdir.join("file.py")
test_file.write(test_file_content)
with pytes... | TestFile |
python | pytorch__pytorch | torch/ao/quantization/quantizer/quantizer.py | {
"start": 4586,
"end": 6617
} | class ____(ABC):
def transform_for_annotation(
self, model: torch.fx.GraphModule
) -> torch.fx.GraphModule:
"""Allows for user defined transforms to run before annotating the graph.
This allows quantizer to allow quantizing part of the model that are otherwise not quantizable.
Fo... | Quantizer |
python | marshmallow-code__marshmallow | src/marshmallow/fields.py | {
"start": 64522,
"end": 67283
} | class ____(Field[_EnumT]):
"""An Enum field (de)serializing enum members by symbol (name) or by value.
:param enum: Enum class
:param by_value: Whether to (de)serialize by value or by name,
or Field class or instance to use to (de)serialize by value. Defaults to False.
If `by_value` is `False`... | Enum |
python | scipy__scipy | scipy/_build_utils/tempita/_tempita.py | {
"start": 1977,
"end": 2282
} | class ____(Exception):
pass
def get_file_template(name, from_template):
path = os.path.join(os.path.dirname(from_template.name), name)
return from_template.__class__.from_filename(
path, namespace=from_template.namespace,
get_template=from_template.get_template)
| _TemplateBreak |
python | cosmicpython__book | tests.py | {
"start": 4365,
"end": 7407
} | class ____:
filename: str
tag: str
contents: str
classes: list
is_diff: bool
callouts = re.compile(r' #?(\(\d\) ?)+$', flags=re.MULTILINE)
callouts_alone = re.compile(r'^\(\d\)$')
@property
def fixed_contents(self):
fixed = self.contents
fixed = self.callouts.sub('... | Listing |
python | coleifer__peewee | peewee.py | {
"start": 29688,
"end": 30252
} | class ____(BaseTable):
def __init__(self, lhs, rhs, join_type=JOIN.INNER, on=None, alias=None):
super(Join, self).__init__(alias=alias)
self.lhs = lhs
self.rhs = rhs
self.join_type = join_type
self._on = on
def on(self, predicate):
self._on = predicate
re... | Join |
python | spyder-ide__spyder | spyder/api/plugin_registration/registry.py | {
"start": 1076,
"end": 1493
} | class ____(SpyderConfigurationAccessor):
# Fake class constants used to register the configuration page
CONF_WIDGET_CLASS = PluginsConfigPage
NAME = 'plugin_registry'
CONF_VERSION = None
ADDITIONAL_CONF_OPTIONS = None
ADDITIONAL_CONF_TABS = None
CONF_SECTION = ""
def apply_plugin_settin... | PreferencesAdapter |
python | nedbat__coveragepy | coverage/files.py | {
"start": 12245,
"end": 19357
} | class ____:
"""A collection of aliases for paths.
When combining data files from remote machines, often the paths to source
code are different, for example, due to OS differences, or because of
serialized checkouts on continuous integration machines.
A `PathAliases` object tracks a list of pattern... | PathAliases |
python | pydantic__pydantic | pydantic-core/tests/benchmarks/test_serialization_micro.py | {
"start": 15654,
"end": 17689
} | class ____:
a: str
b: bytes
c: int
d: float
dataclass_schema = core_schema.dataclass_schema(
Foo,
core_schema.dataclass_args_schema(
'Foo',
[
core_schema.dataclass_field(name='a', schema=core_schema.str_schema()),
core_schema.dataclass_field(name='b', sc... | Foo |
python | ray-project__ray | rllib/utils/tf_run_builder.py | {
"start": 262,
"end": 3879
} | class ____:
"""Used to incrementally build up a TensorFlow run.
This is particularly useful for batching ops from multiple different
policies in the multi-agent setting.
"""
def __init__(self, session, debug_name):
self.session = session
self.debug_name = debug_name
self.fe... | _TFRunBuilder |
python | doocs__leetcode | solution/0100-0199/0153.Find Minimum in Rotated Sorted Array/Solution.py | {
"start": 0,
"end": 367
} | class ____:
def findMin(self, nums: List[int]) -> int:
if nums[0] <= nums[-1]:
return nums[0]
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) >> 1
if nums[0] <= nums[mid]:
left = mid + 1
else:
... | Solution |
python | vyperlang__vyper | vyper/semantics/types/function.py | {
"start": 33635,
"end": 35694
} | class ____(VyperType):
"""
Member function type definition.
This class has no corresponding primitive.
(examples for (x <DynArray[int128, 3]>).append(1))
Arguments:
underlying_type: the type this method is attached to. ex. DynArray[int128, 3]
name: the name of this method. ex. "ap... | MemberFunctionT |
python | davidhalter__jedi | jedi/inference/arguments.py | {
"start": 9944,
"end": 10289
} | class ____(AbstractArguments):
def __init__(self, values_list):
self._values_list = values_list
def unpack(self, funcdef=None):
for values in self._values_list:
yield None, LazyKnownValues(values)
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self._v... | ValuesArguments |
python | getsentry__sentry | src/sentry/integrations/jira/models/create_issue_metadata.py | {
"start": 4232,
"end": 5291
} | class ____:
id: str
description: str
name: str
subtask: bool
icon_url: str
url: str
fields: dict[str, JiraField]
@classmethod
def from_dict(cls, data: dict[str, Any]) -> JiraIssueTypeMetadata:
jira_id = data["id"]
description = data["description"]
name = data... | JiraIssueTypeMetadata |
python | getsentry__sentry | src/sentry/grouping/enhancer/matchers.py | {
"start": 14103,
"end": 14736
} | class ____(EnhancementMatch):
def __init__(self, inner: FrameMatch):
self.inner = inner
@property
def description(self) -> str:
return f"| [ {self.inner.description} ]"
def _to_config_structure(self, version: int) -> str:
return f"|[{self.inner._to_config_structure(version)}]"
... | CalleeMatch |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 4482,
"end": 4609
} | class ____(Web3ValidationError):
"""
Raised when an RPC call returns >32 bytes of extraData.
"""
| ExtraDataLengthError |
python | ray-project__ray | python/ray/autoscaler/_private/vsphere/cluster_operator_client.py | {
"start": 1231,
"end": 1336
} | class ____(Enum):
INITIALIZED = "initialized"
RUNNING = "running"
FAIL = "failure"
| VMNodeStatus |
python | ZoranPandovski__al-go-rithms | data_structures/Linked_list/Python/Palindrome_Linked_List.py | {
"start": 102,
"end": 1243
} | class ____:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
# single node case
if head.next is None:
return True
# two pointer to find the middle point of linked list
first_pointer = head
second_pointer = head.next
while second_... | Solution |
python | apache__airflow | task-sdk/src/airflow/sdk/api/datamodels/_generated.py | {
"start": 9581,
"end": 9981
} | class ____(BaseModel):
"""
Schema for Trigger DAG Run API request.
"""
model_config = ConfigDict(
extra="forbid",
)
logical_date: Annotated[AwareDatetime | None, Field(title="Logical Date")] = None
conf: Annotated[dict[str, Any] | None, Field(title="Conf")] = None
reset_dag_run:... | TriggerDAGRunPayload |
python | huggingface__transformers | src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py | {
"start": 19601,
"end": 21790
} | class ____(Dinov2WithRegistersPreTrainedModel):
def __init__(self, config: Dinov2WithRegistersConfig):
super().__init__(config)
self.config = config
self.embeddings = Dinov2WithRegistersEmbeddings(config)
self.encoder = Dinov2WithRegistersEncoder(config)
self.layernorm = nn... | Dinov2WithRegistersModel |
python | getsentry__sentry | src/sentry/utils/event_frames.py | {
"start": 397,
"end": 937
} | class ____:
lineno: int | None = None
in_app: bool | None = None
abs_path: str | None = None
filename: str | None = None
function: str | None = None
package: str | None = None
module: str | None = None
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> EventFrame:
r... | EventFrame |
python | doocs__leetcode | solution/1400-1499/1478.Allocate Mailboxes/Solution.py | {
"start": 0,
"end": 590
} | class ____:
def minDistance(self, houses: List[int], k: int) -> int:
houses.sort()
n = len(houses)
g = [[0] * n for _ in range(n)]
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
g[i][j] = g[i + 1][j - 1] + houses[j] - houses[i]
f = [[inf]... | Solution |
python | apache__airflow | providers/google/tests/unit/google/cloud/links/test_base_link.py | {
"start": 1749,
"end": 1902
} | class ____(BaseGoogleLink):
key = EXPECTED_GOOGLE_LINK_KEY
name = EXPECTED_GOOGLE_LINK_NAME
format_str = EXPECTED_GOOGLE_LINK_FORMAT
| GoogleLink |
python | neetcode-gh__leetcode | python/0128-longest-consecutive-sequence.py | {
"start": 0,
"end": 411
} | class ____:
def longestConsecutive(self, nums: List[int]) -> int:
numSet = set(nums)
longest = 0
for n in numSet:
# check if its the start of a sequence
if (n - 1) not in numSet:
length = 1
while (n + length) in numSet:
... | Solution |
python | PyCQA__pylint | doc/data/messages/b/bad-mcs-classmethod-argument/good.py | {
"start": 0,
"end": 66
} | class ____(type):
@classmethod
def foo(mcs):
pass
| Meta |
python | tensorflow__tensorflow | tensorflow/python/autograph/converters/functions.py | {
"start": 1270,
"end": 5245
} | class ____(converter.Base):
"""Wraps function bodies around autograph-specific boilerplate."""
def _function_scope_options(self, fn_scope):
"""Returns the options with which to create function scopes."""
# Top-level function receive the options that were directly requested.
# All others receive the opt... | FunctionTransformer |
python | pandas-dev__pandas | pandas/tests/io/formats/test_to_string.py | {
"start": 16610,
"end": 31560
} | class ____:
def test_to_string_decimal(self):
# GH#23614
df = DataFrame({"A": [6.0, 3.1, 2.2]})
expected = " A\n0 6,0\n1 3,1\n2 2,2"
assert df.to_string(decimal=",") == expected
def test_to_string_left_justify_cols(self):
df = DataFrame({"x": [3234, 0.253]})
... | TestDataFrameToString |
python | run-llama__llama_index | llama-index-integrations/indices/llama-index-indices-managed-lancedb/llama_index/indices/managed/lancedb/utils.py | {
"start": 5276,
"end": 11734
} | class ____(BaseModel):
embedding_model: Union[
Literal["open-clip", "colpali", "jina", "imagebind"], EmbeddingFunction
]
kwargs: dict = Field(
default_factory=dict,
)
@model_validator(mode="after")
def validate_embedding_model(self) -> Self:
if isinstance(self.embedding_... | LanceDBMultiModalModel |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/triggers/cloud_composer.py | {
"start": 6189,
"end": 13386
} | class ____(BaseTrigger):
"""The trigger wait for the DAG run completion."""
def __init__(
self,
project_id: str,
region: str,
environment_id: str,
composer_dag_id: str,
start_date: datetime,
end_date: datetime,
allowed_states: list[str],
c... | CloudComposerDAGRunTrigger |
python | allegroai__clearml | clearml/backend_api/services/v2_23/dataviews.py | {
"start": 33119,
"end": 35021
} | class ____(NonStrictDataModel):
"""
:param sets: List of augmentation sets
:type sets: Sequence[AugmentationSet]
:param crop_around_rois: Crop image data around all frame ROIs
:type crop_around_rois: bool
"""
_schema = {
"properties": {
"crop_around_rois": {
... | Augmentation |
python | tensorflow__tensorflow | tensorflow/python/framework/function_test.py | {
"start": 58360,
"end": 60022
} | class ____(test.TestCase):
@test_util.run_v1_only("make_template not supported in TF2")
def testBasic(self):
self.assertTemplateVariableSharing(use_resource=True, defun_first=False)
@test_util.run_v1_only("make_template not supported in TF2")
def testBasicRef(self):
self.assertTemplateVariableSharing(... | TemplateTest |
python | PrefectHQ__prefect | src/prefect/client/schemas/actions.py | {
"start": 22826,
"end": 23657
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to create a block type."""
name: str = Field(default=..., description="A block type's name")
slug: BlockTypeSlug = Field(default=..., description="A block type's slug")
logo_url: Optional[objects.HttpUrl] = Field(
default=None, d... | BlockTypeCreate |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 322339,
"end": 324460
} | class ____(LoopNode, StatNode):
# while statement
#
# condition ExprNode
# body StatNode
# else_clause StatNode
child_attrs = ["condition", "body", "else_clause"]
def analyse_declarations(self, env):
self.body.analyse_declarations(env)
if self.else_clause:
... | WhileStatNode |
python | dask__distributed | distributed/shuffle/_core.py | {
"start": 1848,
"end": 1939
} | class ____(OKMessage):
run_spec: ShuffleRunSpec | ToPickle[ShuffleRunSpec]
| RunSpecMessage |
python | allegroai__clearml | clearml/utilities/pyhocon/config_tree.py | {
"start": 419,
"end": 16474
} | class ____(OrderedDict):
KEY_SEP = '.'
def __init__(self, *args, **kwds):
self.root = kwds.pop('root') if 'root' in kwds else False
if self.root:
self.history = {}
super(ConfigTree, self).__init__(*args, **kwds)
for key, value in self.items():
if isinstan... | ConfigTree |
python | sympy__sympy | sympy/physics/quantum/gate.py | {
"start": 26743,
"end": 30464
} | class ____(HermitianOperator, CGate, TwoQubitGate):
"""Two qubit controlled-NOT.
This gate performs the NOT or X gate on the target qubit if the control
qubits all have the value 1.
Parameters
----------
label : tuple
A tuple of the form (control, target).
Examples
========
... | CNotGate |
python | python-excel__xlrd | tests/test_xldate_to_datetime.py | {
"start": 250,
"end": 6129
} | class ____(unittest.TestCase):
"""
Testcases to test the _xldate_to_datetime() function against dates
extracted from Excel files, with 1900/1904 epochs.
"""
def test_dates_and_times_1900_epoch(self):
"""
Test the _xldate_to_datetime() function for dates and times in
the Exc... | TestConvertToDateTime |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-service-now/llama_index/readers/service_now/event.py | {
"start": 2336,
"end": 2888
} | class ____(BaseEvent):
"""Event fired when attachment processing completes successfully."""
page_id: str = Field(description="ID of the parent page")
attachment_id: str = Field(description="ID of the attachment")
attachment_name: str = Field(description="Name of the attachment")
attachment_type: st... | SNOWKBAttachmentProcessedEvent |
python | Pylons__pyramid | tests/test_predicates.py | {
"start": 3102,
"end": 5517
} | class ____(unittest.TestCase):
def _makeOne(self, val):
from pyramid.predicates import RequestParamPredicate
return RequestParamPredicate(val, None)
def test___call___true_exists(self):
inst = self._makeOne('abc')
request = Dummy()
request.params = {'abc': 1}
re... | TestRequestParamPredicate |
python | geekcomputers__Python | BrowserHistory/backend.py | {
"start": 272,
"end": 2870
} | class ____:
"""
This class designs the operations of a browser history
It works by using a doubly linked list to hold the urls with optimized
navigation using step counters and memory management
"""
def __init__(self, homepage: str):
"""
Returns - None
Input - str
... | BrowserHistory |
python | getsentry__sentry | tests/sentry/deletions/tasks/test_hybrid_cloud.py | {
"start": 16459,
"end": 22365
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
Monitor.objects.all().delete()
with assume_test_silo_mode_of(User):
User.objects.all().delete()
def test_get_ids_for_tombstone_cascade_cross_db(self) -> None:
data = setup_cross_db_deletion_data()
... | TestGetIdsForTombstoneCascadeCrossDbTombstoneWatermarking |
python | sqlalchemy__sqlalchemy | test/orm/test_deferred.py | {
"start": 83894,
"end": 89121
} | class ____(fixtures.DeclarativeMappedTest):
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(ComparableEntity, Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
x = Column(Integer)
y = deferred(Column(Intege... | RaiseLoadTest |
python | kamyu104__LeetCode-Solutions | Python/task-scheduler-ii.py | {
"start": 63,
"end": 428
} | class ____(object):
def taskSchedulerII(self, tasks, space):
"""
:type tasks: List[int]
:type space: int
:rtype: int
"""
lookup = collections.defaultdict(int)
result = 0
for t in tasks:
result = max(lookup[t], result+1)
lookup[t... | Solution |
python | ray-project__ray | python/ray/_private/runtime_env/rocprof_sys.py | {
"start": 1885,
"end": 6485
} | class ____(RuntimeEnvPlugin):
name = "_rocprof_sys"
def __init__(self, resources_dir: str):
self.rocprof_sys_cmd = []
self.rocprof_sys_env = {}
# replace this with better way to get logs dir
session_dir, runtime_dir = os.path.split(resources_dir)
self._rocprof_sys_dir =... | RocProfSysPlugin |
python | django-debug-toolbar__django-debug-toolbar | tests/base.py | {
"start": 3840,
"end": 4204
} | class ____(TestCase):
"""Base TestCase for tests involving clients making requests."""
def setUp(self):
# The HistoryPanel keeps track of previous stores in memory.
# This bleeds into other tests and violates their idempotency.
# Clear the store before each test.
get_store().cle... | IntegrationTestCase |
python | tiangolo__fastapi | docs_src/body_multiple_params/tutorial001_py310.py | {
"start": 84,
"end": 546
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.put("/items/{item_id}")
async def update_item(
*,
item_id: int = Path(title="The ID of the item to get", ge=0, le=1000),
q: str | None = None,
item: Item | None = None,
):
res... | Item |
python | scipy__scipy | scipy/optimize/_shgo_lib/_vertex.py | {
"start": 5715,
"end": 6236
} | class ____(VertexBase):
"""Vertex class to be used for a pure simplicial complex with no associated
differential geometry (single level domain that exists in R^n)"""
def __init__(self, x, nn=None, index=None):
super().__init__(x, nn=nn, index=index)
def connect(self, v):
if v is not sel... | VertexCube |
python | pallets__click | src/click/_winconsole.py | {
"start": 5699,
"end": 8464
} | class ____:
def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None:
self._text_stream = text_stream
self.buffer = byte_stream
@property
def name(self) -> str:
return self.buffer.name
def write(self, x: t.AnyStr) -> int:
if isinstance(x, str):
... | ConsoleStream |
python | coleifer__peewee | peewee.py | {
"start": 45484,
"end": 45665
} | class ____(Expression):
def __add__(self, rhs):
return self.concat(rhs)
def __radd__(self, lhs):
return StringExpression(lhs, OP.CONCAT, self)
| StringExpression |
python | Textualize__textual | src/textual/_immutable_sequence_view.py | {
"start": 211,
"end": 1859
} | class ____(Generic[T]):
"""Class to wrap a sequence of some sort, but not allow modification."""
def __init__(self, wrap: Sequence[T]) -> None:
"""Initialise the immutable sequence.
Args:
wrap: The sequence being wrapped.
"""
self._wrap = wrap
if TYPE_CHECKING:... | ImmutableSequenceView |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 497576,
"end": 506480
} | class ____(ExprNode):
# operator string
# operand1 ExprNode
# operand2 ExprNode
#
# Processing during analyse_expressions phase:
#
# analyse_c_operation
# Called when neither operand is a pyobject.
# - Check operand types and coerce if needed.
# ... | BinopNode |
python | django__django | tests/model_fields/models.py | {
"start": 15060,
"end": 15153
} | class ____(models.Model):
field = models.UUIDField(blank=True, null=True)
| NullableUUIDModel |
python | pytorch__pytorch | test/test_dynamic_shapes.py | {
"start": 109734,
"end": 118069
} | class ____(TestCase):
"""
Tests the guards-related methods used by the inductor FX graph cache.
"""
def test_guards_gt_lt(self):
shape_env = ShapeEnv()
s0 = create_symint(shape_env, 6)
s1 = create_symint(shape_env, 7)
s2 = create_symint(shape_env, 5)
guard_int(s... | TestGuardsExpressions |
python | python__mypy | mypy/test/test_find_sources.py | {
"start": 1921,
"end": 13693
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.tempdir = tempfile.mkdtemp()
self.oldcwd = os.getcwd()
os.chdir(self.tempdir)
def tearDown(self) -> None:
os.chdir(self.oldcwd)
shutil.rmtree(self.tempdir)
def test_crawl_no_namespace(self) -> None:
... | SourceFinderSuite |
python | huggingface__transformers | src/transformers/models/deepseek_vl/modular_deepseek_vl.py | {
"start": 1482,
"end": 4390
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DeepseekVLModel`]. It is used to instantiate a
DeepseekVL model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar... | DeepseekVLConfig |
python | streamlit__streamlit | lib/streamlit/elements/write.py | {
"start": 1550,
"end": 23035
} | class ____:
@gather_metrics("write_stream")
def write_stream(
self,
stream: Callable[..., Any]
| Generator[Any, Any, Any]
| Iterable[Any]
| AsyncGenerator[Any, Any],
*,
cursor: str | None = None,
) -> list[Any] | str:
r"""Stream a generator, it... | WriteMixin |
python | spack__spack | lib/spack/spack/repo.py | {
"start": 78472,
"end": 78576
} | class ____(RepoError):
"""Raised when we encounter a package spack doesn't have."""
| UnknownEntityError |
python | tornadoweb__tornado | tornado/iostream.py | {
"start": 2553,
"end": 3218
} | class ____(IOError):
"""Exception raised by `IOStream` methods when the stream is closed.
Note that the close callback is scheduled to run *after* other
callbacks on the stream (to allow for buffered data to be processed),
so you may see this error before you see the close callback.
The ``real_err... | StreamClosedError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 268831,
"end": 269342
} | class ____(sgqlc.types.Input):
"""Ways in which lists of reactions can be ordered upon return."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(ReactionOrderField), graphql_name="field")
"""The field in which to order reactions by... | ReactionOrder |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/axes_grid.py | {
"start": 679,
"end": 10468
} | class ____:
"""
A grid of Axes.
In Matplotlib, the Axes location (and size) is specified in normalized
figure coordinates. This may not be ideal for images that needs to be
displayed with a given aspect ratio; for example, it is difficult to
display multiple images of a same size with some fixe... | Grid |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 192510,
"end": 193067
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("repository_id", "topic_names", "client_mutation_id")
repository_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="repositoryId"
)
topic_names = sgq... | UpdateTopicsInput |
python | huggingface__transformers | src/transformers/models/roformer/modeling_roformer.py | {
"start": 21144,
"end": 26187
} | class ____(nn.Module):
r"""
Compute a single vector summary of a sequence hidden states.
Args:
config ([`RoFormerConfig`]):
The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
config class of your model for the default v... | RoFormerSequenceSummary |
python | PyCQA__pylint | tests/regrtest_data/wrong_import_position.py | {
"start": 147,
"end": 220
} | class ____(object):
"""A class before an import."""
import os
| Something |
python | ansible__ansible | test/units/module_utils/common/test_collections.py | {
"start": 2693,
"end": 4618
} | class ____:
def test_scalar(self):
imdict = ImmutableDict({1: 2})
assert imdict[1] == 2
def test_string(self):
imdict = ImmutableDict({u'café': u'くらとみ'})
assert imdict[u'café'] == u'くらとみ'
def test_container(self):
imdict = ImmutableDict({(1, 2): ['1', '2']})
... | TestImmutableDict |
python | celery__celery | t/unit/backends/test_asynchronous.py | {
"start": 8066,
"end": 8851
} | class ____(GreenletDrainerTests):
@pytest.fixture(autouse=True)
def setup_drainer(self):
self.drainer = self.get_drainer('gevent')
@cached_property
def sleep(self):
from gevent import sleep
return sleep
def result_consumer_drain_events(self, timeout=None):
import ge... | test_GeventDrainer |
python | sqlalchemy__sqlalchemy | test/ext/test_extendedattr.py | {
"start": 4457,
"end": 17131
} | class ____(_ExtBase, fixtures.ORMTest):
@classmethod
def setup_test_class(cls):
global MyBaseClass, MyClass
class MyBaseClass:
__sa_instrumentation_manager__ = (
instrumentation.InstrumentationManager
)
class MyClass:
# This proves th... | UserDefinedExtensionTest |
python | getsentry__sentry | src/social_auth/backends/__init__.py | {
"start": 8528,
"end": 13175
} | class ____:
"""Base authentication class, new authenticators should subclass
and implement needed methods.
AUTH_BACKEND Authorization backend related with this service
"""
AUTH_BACKEND: type[SocialAuthBackend]
def __init__(self, request, redirect):
self.request = request
... | BaseAuth |
python | pydata__xarray | xarray/tests/test_treenode.py | {
"start": 4448,
"end": 6057
} | class ____:
def test_get_child(self) -> None:
john: TreeNode = TreeNode(
children={
"Mary": TreeNode(
children={"Sue": TreeNode(children={"Steven": TreeNode()})}
)
}
)
mary = john.children["Mary"]
sue = mary.... | TestGetNodes |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_combined03.py | {
"start": 315,
"end": 1474
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_combined03.xlsx")
self.ignore_elements = {"xl/charts/chart1.xml": ["<c:dispBlanksAs"]}
def test_create_file(self):
"""Test t... | TestCompareXLSXFiles |
python | scrapy__scrapy | tests/test_engine.py | {
"start": 17530,
"end": 21086
} | class ____:
"""Test cases for ExecutionEngine.download_async()."""
@pytest.fixture
def engine(self) -> ExecutionEngine:
crawler = get_crawler(MySpider)
engine = ExecutionEngine(crawler, lambda _: None)
engine.downloader.close()
engine.downloader = Mock()
engine._slot... | TestEngineDownloadAsync |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 165959,
"end": 166177
} | class ____(RecvmsgTests, SendrecvmsgUDPLITETestBase):
pass
@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
@requireAttrs(socket.socket, "recvmsg_into")
| RecvmsgUDPLITETest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_bank_accounts.py | {
"start": 15393,
"end": 22043
} | class ____(TestCase):
@HttpMocker()
def test_given_no_state_and_successful_sync_when_read_then_set_state_to_now(self, http_mocker: HttpMocker) -> None:
# If stripe takes some time to ingest the data, we should recommend to use a lookback window when syncing the bank_accounts stream
# to make sur... | IncrementalTest |
python | ray-project__ray | rllib/examples/envs/classes/mock_env.py | {
"start": 2012,
"end": 2709
} | class ____(gym.Env):
"""Mock environment for testing purposes.
Observation=ts (discrete space!), reward=100.0, episode-len is
configurable. Actions are ignored.
"""
def __init__(self, episode_length):
self.episode_length = episode_length
self.i = 0
self.observation_space = ... | MockEnv3 |
python | ipython__ipython | tests/test_zzz_autoreload.py | {
"start": 25692,
"end": 25862
} | class ____(object):
def __init__(self, x):
self.x = x
def bar(self, y):
return self.x + y + 1
@property
def quux(self):
return 43
| Baz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.