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 | PyCQA__pylint | pylint/reporters/ureports/nodes.py | {
"start": 2925,
"end": 3167
} | class ____(Text):
"""A verbatim text, display the raw data.
attributes :
* data : the text value as an encoded or unicode string
"""
# container nodes #############################################################
| VerbatimText |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 67470,
"end": 70971
} | class ____(Request):
"""
Get a list of all hyper parameter sections and names used in tasks within the given project.
:param project: Project ID
:type project: str
:param page: Page number
:type page: int
:param page_size: Page size
:type page_size: int
:param include_subprojects: I... | GetHyperParametersRequest |
python | astropy__astropy | astropy/io/votable/tree.py | {
"start": 132958,
"end": 152653
} | class ____(Element, _IDProperty, _DescriptionProperty):
"""
VOTABLE_ element: represents an entire file.
The keyword arguments correspond to setting members of the same
name, documented below.
*version* is settable at construction time only, since conformance
tests for building the rest of the... | VOTableFile |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/self_ask_with_search/base.py | {
"start": 1284,
"end": 2755
} | class ____(Agent):
"""Agent for the self-ask-with-search paper."""
output_parser: AgentOutputParser = Field(default_factory=SelfAskOutputParser)
@classmethod
@override
def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:
return SelfAskOutputParser()
@property
d... | SelfAskWithSearchAgent |
python | huggingface__transformers | src/transformers/integrations/ggml.py | {
"start": 26641,
"end": 30330
} | class ____(GemmaConverter):
def __init__(self, tokenizer_dict):
# set dummy data to avoid unnecessary merges calculation
tokenizer_dict["merges"] = ["dummy text"]
self.proto = GGUFTokenizerSkeleton(tokenizer_dict)
self.original_tokenizer = self.proto
self.additional_kwargs =... | GGUFGemmaConverter |
python | getsentry__sentry | src/sentry/insights/models.py | {
"start": 350,
"end": 1021
} | class ____(DefaultFieldsModel):
"""
A starred transaction in Insights
"""
__relocation_scope__ = RelocationScope.Organization
project = FlexibleForeignKey("sentry.Project", on_delete=models.CASCADE)
organization = FlexibleForeignKey("sentry.Organization", on_delete=models.CASCADE)
user_id ... | InsightsStarredSegment |
python | apache__airflow | providers/fab/src/airflow/providers/fab/www/api_connexion/exceptions.py | {
"start": 4707,
"end": 5171
} | class ____(ProblemException):
"""Raise when there is some conflict."""
def __init__(
self,
title="Conflict",
detail: str | None = None,
headers: dict | None = None,
**kwargs: Any,
):
super().__init__(
status=HTTPStatus.CONFLICT,
type=E... | Conflict |
python | celery__celery | celery/backends/elasticsearch.py | {
"start": 601,
"end": 9582
} | class ____(KeyValueStoreBackend):
"""Elasticsearch Backend.
Raises:
celery.exceptions.ImproperlyConfigured:
if module :pypi:`elasticsearch` is not available.
"""
index = 'celery'
doc_type = None
scheme = 'http'
host = 'localhost'
port = 9200
username = None
... | ElasticsearchBackend |
python | jmcnamara__XlsxWriter | xlsxwriter/test/relationships/test_initialisation.py | {
"start": 309,
"end": 872
} | class ____(unittest.TestCase):
"""
Test initialisation of the Relationships class and call a method.
"""
def setUp(self):
self.fh = StringIO()
self.relationships = Relationships()
self.relationships._set_filehandle(self.fh)
def test_xml_declaration(self):
"""Test R... | TestInitialisation |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_legend06.py | {
"start": 315,
"end": 1416
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_legend06.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with legend options."""
workbook = Wo... | TestCompareXLSXFiles |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 48657,
"end": 48823
} | class ____:
xlExtractData = 2 # from enum XlCorruptLoad
xlNormalLoad = 0 # from enum XlCorruptLoad
xlRepairFile = 1 # from enum XlCorruptLoad
| CorruptLoad |
python | kamyu104__LeetCode-Solutions | Python/removing-minimum-and-maximum-from-array.py | {
"start": 29,
"end": 325
} | class ____(object):
def minimumDeletions(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i, j = nums.index(min(nums)), nums.index(max(nums))
if i > j:
i, j = j, i
return min((i+1)+(len(nums)-j), j+1, len(nums)-i)
| Solution |
python | wandb__wandb | wandb/automations/_generated/input_types.py | {
"start": 1315,
"end": 1421
} | class ____(GQLInput):
no_op: Optional[bool] = Field(alias="noOp", default=None)
| NoOpTriggeredActionInput |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 14729,
"end": 15268
} | class ____(sgqlc.types.Enum):
"""The possible reasons that a Dependabot alert was dismissed.
Enumeration Choices:
* `FIX_STARTED`: A fix has already been started
* `INACCURATE`: This alert is inaccurate or incorrect
* `NOT_USED`: Vulnerable code is not actually used
* `NO_BANDWIDTH`: No bandwi... | DismissReason |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 36390,
"end": 36546
} | class ____(Rank):
"""Constant rank value"""
value: float
def to_dict(self) -> Dict[str, Any]:
return {"$val": self.value}
@dataclass
| Val |
python | networkx__networkx | networkx/classes/tests/test_reportviews.py | {
"start": 29644,
"end": 31940
} | class ____:
GRAPH = nx.Graph
dview = nx.reportviews.DegreeView
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(6, cls.GRAPH())
cls.G.add_edge(1, 3, foo=2)
cls.G.add_edge(1, 3, foo=3)
def test_pickle(self):
import pickle
deg = self.G.degree
... | TestDegreeView |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc_metastore.py | {
"start": 3772,
"end": 9162
} | class ____(GoogleCloudBaseOperator):
"""
Create a new backup in a given project and location.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param service_id: Requ... | DataprocMetastoreCreateBackupOperator |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_task_run_subscriptions.py | {
"start": 8766,
"end": 11091
} | class ____:
async def test_task_queue_scheduled_size_limit(self):
task_key = "test_limit"
max_scheduled_size = 2
task_runs.TaskQueue.configure_task_key(
task_key, scheduled_size=max_scheduled_size, retry_size=1
)
queue = task_runs.TaskQueue.for_key(task_key)
... | TestQueueLimit |
python | cython__cython | docs/examples/userguide/language_basics/optional_subclassing.py | {
"start": 191,
"end": 291
} | class ____(B):
@cython.ccall
def foo(self, x=True, k:cython.int = 3):
print("C", x, k)
| C |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 18627,
"end": 18996
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear1 = torch.nn.Linear(10, 10)
self.scale = torch.nn.Parameter(torch.randn(1, 10))
def forward(self, x):
if not requires_grad1(self):
return F.relu(self.linear1(x)) * self.scale
... | ParametersModule1 |
python | astropy__astropy | astropy/units/format/unicode_format.py | {
"start": 247,
"end": 1956
} | class ____(console.Console):
"""
Output-only format to display pretty formatting at the console
using Unicode characters.
For example::
>>> import astropy.units as u
>>> print(u.bar.decompose().to_string('unicode'))
100000 kg m⁻¹ s⁻²
>>> print(u.bar.decompose().to_string('unico... | Unicode |
python | spack__spack | lib/spack/spack/llnl/util/lang.py | {
"start": 29770,
"end": 30979
} | class ____:
"""A generic mechanism to coalesce multiple exceptions and preserve tracebacks."""
def __init__(self):
self.exceptions: List[Tuple[str, Exception, List[str]]] = []
def __bool__(self):
"""Whether any exceptions were handled."""
return bool(self.exceptions)
def forwa... | GroupedExceptionHandler |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 136799,
"end": 139855
} | class ____(fixtures.TestBase):
def teardown_test(self):
clear_mappers()
@testing.variation("arg_style", ["string", "table", "lambda_"])
def test_secondary_arg_styles(self, arg_style):
Base = declarative_base()
c = Table(
"c",
Base.metadata,
Colum... | SecondaryArgTest |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 59910,
"end": 62110
} | class ____(ASTBase):
def __init__(
self, args: list[ASTType | ASTTemplateArgConstant], packExpansion: bool
) -> None:
assert args is not None
self.args = args
self.packExpansion = packExpansion
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTTemp... | ASTTemplateArgs |
python | doocs__leetcode | lcof2/剑指 Offer II 099. 最小路径之和/Solution.py | {
"start": 0,
"end": 481
} | class ____:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dp = [[grid[0][0]] * n for _ in range(m)]
for i in range(1, m):
dp[i][0] = dp[i - 1][0] + grid[i][0]
for j in range(1, n):
dp[0][j] = dp[0][j - 1] + grid[0][j]
... | Solution |
python | huggingface__transformers | src/transformers/models/mvp/modeling_mvp.py | {
"start": 3446,
"end": 10588
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: Optional[float] = 0.0,
is_decoder: Optional[bool] = False,
bias: Optional[bool] = True,
layer_idx: Opti... | MvpAttention |
python | kamyu104__LeetCode-Solutions | Python/airplane-seat-assignment-probability.py | {
"start": 805,
"end": 1105
} | class ____(object):
def nthPersonGetsNthSeat(self, n):
"""
:type n: int
:rtype: float
"""
dp = [0.0]*2
dp[0] = 1.0 # zero-indexed
for i in xrange(2, n+1):
dp[(i-1)%2] = 1.0/i+dp[(i-2)%2]*(i-2)/i
return dp[(n-1)%2]
| Solution2 |
python | google__pytype | pytype/pytd/parse/node_test.py | {
"start": 989,
"end": 1282
} | class ____(Node):
"""A node with its own VisitNode function."""
x: Any
y: Any
def VisitNode(self, visitor):
"""Allow a visitor to modify our children. Returns modified node."""
# only visit x, not y
x = self.x.Visit(visitor)
return NodeWithVisit(x, self.y)
| NodeWithVisit |
python | huggingface__transformers | tests/models/aria/test_modeling_aria.py | {
"start": 6283,
"end": 7885
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
"""
Model tester for `AriaForConditionalGeneration`.
"""
all_model_classes = (AriaModel, AriaForConditionalGeneration) if is_torch_available() else ()
_is_composite = True
def setUp(self):
self.model_tester = Aria... | AriaForConditionalGenerationModelTest |
python | plotly__plotly.py | plotly/graph_objs/layout/polar/angularaxis/_tickformatstop.py | {
"start": 235,
"end": 8557
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.polar.angularaxis"
_path_str = "layout.polar.angularaxis.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*], where... | Tickformatstop |
python | apache__airflow | providers/dbt/cloud/src/airflow/providers/dbt/cloud/operators/dbt.py | {
"start": 16322,
"end": 18389
} | class ____(BaseOperator):
"""
List jobs in a dbt Cloud project.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DbtCloudListJobsOperator`
Retrieves metadata for all jobs tied to a specified dbt Cloud account. If a ``project_... | DbtCloudListJobsOperator |
python | zarr-developers__zarr-python | tests/test_store/test_memory.py | {
"start": 2546,
"end": 4555
} | class ____(StoreTests[GpuMemoryStore, gpu.Buffer]):
store_cls = GpuMemoryStore
buffer_cls = gpu.Buffer
async def set(self, store: GpuMemoryStore, key: str, value: gpu.Buffer) -> None: # type: ignore[override]
store._store_dict[key] = value
async def get(self, store: MemoryStore, key: str) -> ... | TestGpuMemoryStore |
python | doocs__leetcode | solution/2000-2099/2009.Minimum Number of Operations to Make Array Continuous/Solution2.py | {
"start": 0,
"end": 323
} | class ____:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
nums = sorted(set(nums))
ans, j = n, 0
for i, v in enumerate(nums):
while j < len(nums) and nums[j] - v <= n - 1:
j += 1
ans = min(ans, n - (j - i))
return ans
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1013911,
"end": 1014346
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UnpinIssue"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "issue")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
... | UnpinIssuePayload |
python | ansible__ansible | lib/ansible/plugins/shell/__init__.py | {
"start": 1351,
"end": 10975
} | class ____(AnsiblePlugin):
def __init__(self):
super(ShellBase, self).__init__()
# Not used but here for backwards compatibility.
# ansible.posix.fish uses (but does not actually use) this value.
# https://github.com/ansible-collections/ansible.posix/blob/f41f08e9e3d3129e709e122540... | ShellBase |
python | coleifer__peewee | tests/regressions.py | {
"start": 4097,
"end": 6411
} | class ____(ModelTestCase):
database = get_in_memory_db()
requires = [DiA, DiB, DiC, DiD, DiBA]
def test_delete_instance_regression(self):
with self.database.atomic():
a1, a2, a3 = [DiA.create(a=a) for a in ('a1', 'a2', 'a3')]
for a in (a1, a2, a3):
for j in (... | TestDeleteInstanceRegression |
python | doocs__leetcode | solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/Solution2.py | {
"start": 0,
"end": 957
} | class ____:
def longestSubarray(self, nums: List[int], limit: int) -> int:
def check(k: int) -> bool:
min_q = deque()
max_q = deque()
for i, x in enumerate(nums):
if min_q and i - min_q[0] + 1 > k:
min_q.popleft()
if max... | Solution |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/control.py | {
"start": 1695,
"end": 6657
} | class ____:
"""A renderable that inserts a control code (non printable but may move cursor).
Args:
*codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a
tuple of ControlType and an integer parameter
"""
__slots__ = ["segment"]
def __init_... | Control |
python | kamyu104__LeetCode-Solutions | Python/strobogrammatic-number-ii.py | {
"start": 39,
"end": 491
} | class ____(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
result = ['0', '1', '8'] if n%2 else ['']
for i in xrange(n%2, n, 2):
result = [a + num + b for a, b... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_hash.py | {
"start": 462,
"end": 606
} | class ____:
def __hash__(self):
return return_int() # [invalid-hash-return]
# These testcases should NOT raise errors
| ComplexReturn |
python | google__jax | jax/_src/pjit.py | {
"start": 30391,
"end": 35700
} | class ____(stages.Wrapped):
def eval_shape(self, *args, **kwargs):
"""See ``jax.eval_shape``."""
raise NotImplementedError
def trace(self, *args, **kwargs) -> stages.Traced:
raise NotImplementedError
# in_shardings and out_shardings can't be None as the default value
# because `None` means that the ... | JitWrapped |
python | django__django | tests/admin_views/models.py | {
"start": 21690,
"end": 22088
} | class ____(models.Model):
name = models.CharField(max_length=100)
pubdate = models.DateField()
status = models.CharField(
max_length=20,
choices=(("option one", "Option One"), ("option two", "Option Two")),
)
slug1 = models.SlugField(blank=True)
slug2 = models.SlugField(blank=Tru... | MainPrepopulated |
python | sphinx-doc__sphinx | sphinx/transforms/__init__.py | {
"start": 6712,
"end": 7267
} | class ____(SphinxTransform):
"""Register IDs of tables, figures and literal_blocks to assign numbers."""
default_priority = 210
def apply(self, **kwargs: Any) -> None:
domain: StandardDomain = self.env.domains.standard_domain
for node in self.document.findall(nodes.Element):
i... | AutoNumbering |
python | doocs__leetcode | solution/1900-1999/1945.Sum of Digits of String After Convert/Solution.py | {
"start": 0,
"end": 233
} | class ____:
def getLucky(self, s: str, k: int) -> int:
s = ''.join(str(ord(c) - ord('a') + 1) for c in s)
for _ in range(k):
t = sum(int(c) for c in s)
s = str(t)
return int(s)
| Solution |
python | wandb__wandb | wandb/automations/events.py | {
"start": 6140,
"end": 6980
} | class ____(FilterEventFields): # from: FilterEventTriggeringCondition
"""A triggering event from a saved automation."""
event_type: Annotated[EventType, Field(frozen=True)] # type: ignore[assignment]
# We override the type of the `filter` field in order to enforce the expected
# structure for the JS... | SavedEvent |
python | walkccc__LeetCode | solutions/448. Find All Numbers Disappeared in an Array/448.py | {
"start": 0,
"end": 229
} | class ____:
def findDisappearedNumbers(self, nums: list[int]) -> list[int]:
for num in nums:
index = abs(num) - 1
nums[index] = -abs(nums[index])
return [i + 1 for i, num in enumerate(nums) if num > 0]
| Solution |
python | spyder-ide__spyder | spyder/plugins/switcher/container.py | {
"start": 620,
"end": 3544
} | class ____(PluginMainContainer):
# ---- PluginMainContainer API
# -------------------------------------------------------------------------
def setup(self):
self.switcher = Switcher(self._plugin.get_main())
# Switcher shortcuts
self.create_action(
SwitcherActions.FileSw... | SwitcherContainer |
python | redis__redis-py | tests/ssl_utils.py | {
"start": 208,
"end": 1408
} | class ____(str, enum.Enum):
client = "client"
server = "server"
TLSFiles = namedtuple("TLSFiles", ["certfile", "keyfile", "ca_certfile"])
def get_tls_certificates(
subdir: str = "standalone",
cert_type: CertificateType = CertificateType.client,
):
root = os.path.join(os.path.dirname(__file__), "... | CertificateType |
python | huggingface__transformers | src/transformers/models/xlm_roberta/modular_xlm_roberta.py | {
"start": 20001,
"end": 23436
} | class ____(RobertaForQuestionAnswering):
def __init__(self, config):
super().__init__(config)
del self.xlm_roberta
self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Long... | XLMRobertaForQuestionAnswering |
python | openai__openai-python | examples/parsing_tools_stream.py | {
"start": 122,
"end": 948
} | class ____(BaseModel):
city: str
country: str
client = OpenAI()
with client.chat.completions.stream(
model="gpt-4o-2024-08-06",
messages=[
{
"role": "user",
"content": "What's the weather like in SF and New York?",
},
],
tools=[
# because we're... | GetWeather |
python | scikit-learn__scikit-learn | sklearn/ensemble/_forest.py | {
"start": 41346,
"end": 58108
} | class ____(ForestClassifier):
"""
A random forest classifier.
A random forest is a meta estimator that fits a number of decision tree
classifiers on various sub-samples of the dataset and uses averaging to
improve the predictive accuracy and control over-fitting.
Trees in the forest use the bes... | RandomForestClassifier |
python | kubernetes-client__python | kubernetes/client/models/v1_csi_node_driver.py | {
"start": 383,
"end": 8698
} | 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... | V1CSINodeDriver |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-seller-partner/components.py | {
"start": 10787,
"end": 13302
} | class ____(TypeTransformer):
config: Dict[str, Any] = None
MARKETPLACE_DATE_FORMAT_MAP = dict(
# eu
A2VIGQ35RCS4UG="%d/%m/%y", # AE
A1PA6795UKMFR9="%d.%m.%y", # DE
A1C3SOZRARQ6R3="%d/%m/%y", # PL
ARBP9OOSHTCHU="%d/%m/%y", # EG
A1RKKUPIHCS9HS="%d/%m/%y", # ES... | SellerFeedbackReportsTypeTransformer |
python | pypa__pip | src/pip/_vendor/urllib3/exceptions.py | {
"start": 2618,
"end": 2863
} | class ____(HTTPError):
"""Raised when a socket timeout error occurs.
Catching this error will catch both :exc:`ReadTimeoutErrors
<ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.
"""
pass
| TimeoutError |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 227145,
"end": 228714
} | class ____(Operation):
def __init__(self, axis=None, keepdims=False, *, name=None):
super().__init__(name=name)
if isinstance(axis, int):
axis = [axis]
self.axis = axis
self.keepdims = keepdims
def call(self, x):
return backend.numpy.mean(x, axis=self.axis, k... | Mean |
python | streamlit__streamlit | lib/streamlit/components/v2/component_manifest_handler.py | {
"start": 864,
"end": 4187
} | class ____:
"""Handles component registration from parsed ComponentManifest objects."""
def __init__(self) -> None:
# Component metadata from pyproject.toml
self._metadata: MutableMapping[str, ComponentManifest] = {}
# Resolved asset roots keyed by fully-qualified component name
... | ComponentManifestHandler |
python | PrefectHQ__prefect | tests/test_tasks.py | {
"start": 17505,
"end": 19055
} | class ____:
async def test_sync_task_run_inside_sync_flow(self):
@task
def foo(x):
return x
@flow
def bar():
return foo(1, return_state=True)
task_state = bar()
assert isinstance(task_state, State)
assert await task_state.result() == ... | TestTaskRun |
python | pandas-dev__pandas | pandas/tests/series/methods/test_pct_change.py | {
"start": 116,
"end": 2602
} | class ____:
def test_pct_change(self, datetime_series):
rs = datetime_series.pct_change()
tm.assert_series_equal(rs, datetime_series / datetime_series.shift(1) - 1)
rs = datetime_series.pct_change(2)
filled = datetime_series.ffill()
tm.assert_series_equal(rs, filled / filled... | TestSeriesPctChange |
python | django__django | tests/admin_inlines/models.py | {
"start": 8235,
"end": 8316
} | class ____(models.Model):
name = models.CharField(max_length=1)
| SomeParentModel |
python | pypa__setuptools | setuptools/namespaces.py | {
"start": 124,
"end": 3014
} | class ____:
nspkg_ext = '-nspkg.pth'
def install_namespaces(self) -> None:
nsp = self._get_all_ns_packages()
if not nsp:
return
filename = self._get_nspkg_file()
self.outputs.append(filename)
log.info("Installing %s", filename)
lines = map(self._gen_n... | Installer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 22931,
"end": 23554
} | class ____(SemiIncrementalMixin, GithubStream):
"""
API docs: https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#list-releases
"""
cursor_field = "created_at"
def transform(self, record: MutableMapping[str, Any], stream_slice: Mapping[str, Any]) -> MutableMapping[str, Any]:
... | Releases |
python | walkccc__LeetCode | solutions/1868. Product of Two Run-Length Encoded Arrays/1868.py | {
"start": 0,
"end": 641
} | class ____:
def findRLEArray(self, encoded1: list[list[int]],
encoded2: list[list[int]]) -> list[list[int]]:
ans = []
i = 0 # encoded1's index
j = 0 # encoded2's index
while i < len(encoded1) and j < len(encoded2):
mult = encoded1[i][0] * encoded2[j][0]
minFreq = min(... | Solution |
python | pandas-dev__pandas | pandas/core/reshape/merge.py | {
"start": 82366,
"end": 84422
} | class ____(_MergeOperation):
_merge_type = "ordered_merge"
def __init__(
self,
left: DataFrame | Series,
right: DataFrame | Series,
on: IndexLabel | None = None,
left_on: IndexLabel | None = None,
right_on: IndexLabel | None = None,
left_index: bool = Fal... | _OrderedMerge |
python | great-expectations__great_expectations | great_expectations/metrics/batch/sample_values.py | {
"start": 153,
"end": 213
} | class ____(MetricResult[pd.DataFrame]): ...
| SampleValuesResult |
python | neetcode-gh__leetcode | python/0876-middle-of-the-linked-list.py | {
"start": 0,
"end": 286
} | class ____:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
return slow
| Solution |
python | lepture__authlib | authlib/jose/drafts/_jwe_enc_cryptodome.py | {
"start": 315,
"end": 1848
} | class ____(JWEEncAlgorithm):
# Use of an IV of size 192 bits is REQUIRED with this algorithm.
# https://datatracker.ietf.org/doc/html/draft-amringer-jose-chacha-02#section-4.1
IV_SIZE = 192
def __init__(self, key_size):
self.name = "XC20P"
self.description = "XChaCha20-Poly1305"
... | XC20PEncAlgorithm |
python | pandas-dev__pandas | pandas/tests/groupby/test_timegrouper.py | {
"start": 1735,
"end": 34276
} | class ____:
def test_groupby_with_timegrouper(self, using_infer_string):
# GH 4161
# TimeGrouper requires a sorted index
# also verifies that the resultant index has the correct name
df_original = DataFrame(
{
"Buyer": "Carl Carl Carl Carl Joe Carl".split(... | TestGroupBy |
python | facebook__pyre-check | client/language_server/code_navigation_request.py | {
"start": 2321,
"end": 2686
} | class ____:
path: Path
content: Optional[str]
client_id: str
def to_json(self) -> List[object]:
return [
"FileOpened",
{
"path": f"{self.path}",
"content": self.content,
"client_id": self.client_id,
},
]... | FileOpened |
python | Textualize__textual | examples/five_by_five.py | {
"start": 4028,
"end": 4392
} | class ____(Widget):
"""The main playable grid of game cells."""
def compose(self) -> ComposeResult:
"""Compose the game grid.
Returns:
ComposeResult: The result of composing the game grid.
"""
for row in range(Game.SIZE):
for col in range(Game.SIZE):
... | GameGrid |
python | scipy__scipy | scipy/special/_sf_error.py | {
"start": 266,
"end": 375
} | class ____(Exception):
"""Exception that can be raised by special functions."""
pass
| SpecialFunctionError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 36964,
"end": 37238
} | class ____(_SelectIsNotFrom, _NoTextCoercion, RoleImpl):
__slots__ = ()
def _post_coercion(self, element, **kw):
if "dml_table" in element._annotations:
return element._annotations["dml_table"]
else:
return element
| DMLTableImpl |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 195136,
"end": 195625
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "invitation", "message")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
invitation = sgqlc.types.Field(
"Enterpr... | AcceptEnterpriseAdministratorInvitationPayload |
python | pdm-project__pdm | src/pdm/models/project_info.py | {
"start": 276,
"end": 3523
} | class ____:
name: str
version: str
summary: str = ""
author: str = ""
email: str = ""
license: str = ""
requires_python: str = ""
platform: str = ""
keywords: str = ""
homepage: str = ""
project_urls: list[str] = field(default_factory=list)
latest_stable_version: str = ""... | ProjectInfo |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 26989,
"end": 28157
} | class ____(ASTBase):
def __init__(self, arg: ASTTypeWithInit | None, ellipsis: bool = False) -> None:
self.arg = arg
self.ellipsis = ellipsis
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTFunctionParameter):
return NotImplemented
return self.ar... | ASTFunctionParameter |
python | google__pytype | pytype/abstract/abstract_test.py | {
"start": 11194,
"end": 26490
} | class ____(AbstractTestBase):
def _make_pytd_function(self, params, name="f"):
pytd_params = []
for i, p in enumerate(params):
p_type = pytd.ClassType(p.name)
p_type.cls = p
pytd_params.append(
pytd.Parameter(
function.argname(i),
p_type,
... | FunctionTest |
python | tiangolo__fastapi | tests/test_pydantic_v1_v2_multifile/modelsv2b.py | {
"start": 115,
"end": 277
} | class ____(BaseModel):
dup_title: str
dup_size: int
dup_description: Union[str, None] = None
dup_sub: SubItem
dup_multi: List[SubItem] = []
| Item |
python | huggingface__transformers | src/transformers/models/cpmant/tokenization_cpmant.py | {
"start": 1378,
"end": 2345
} | class ____:
def __init__(self, vocab, unk_token="<unk>", max_input_chars_per_word=200):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, token):
chars = list(token)
if len(chars) > self.max_input_ch... | WordpieceTokenizer |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 1159357,
"end": 1169230
} | class ____(DatumChannelMixin, core.ScaleDatumDef):
"""
YOffsetDatum schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to... | YOffsetDatum |
python | kamyu104__LeetCode-Solutions | Python/number-of-strings-that-appear-as-substrings-in-word.py | {
"start": 429,
"end": 2542
} | class ____(object):
def step(self, letter):
while self.__node and letter not in self.__node.children:
self.__node = self.__node.suffix
self.__node = self.__node.children[letter] if self.__node else self.__root
return self.__get_ac_node_outputs(self.__node)
def __init__(s... | AhoTrie |
python | ansible__ansible | test/units/module_utils/facts/test_collectors.py | {
"start": 6874,
"end": 7114
} | class ____(BaseFactsTest):
__test__ = True
gather_subset = ['!all', 'distribution']
valid_subsets = ['distribution']
fact_namespace = 'ansible_distribution'
collector_class = DistributionFactCollector
| TestDistributionFacts |
python | django__django | tests/field_subclassing/fields.py | {
"start": 738,
"end": 832
} | class ____(models.CharField):
descriptor_class = CustomDeferredAttribute
| CustomDescriptorField |
python | great-expectations__great_expectations | tests/actions/test_core_actions.py | {
"start": 32784,
"end": 37689
} | class ____:
@pytest.mark.unit
def test_equality(self):
"""I kow, this one seems silly. But this was a bug for other actions."""
a = UpdateDataDocsAction(name="my_action")
b = UpdateDataDocsAction(name="my_action")
assert a == b
@pytest.mark.unit
def test_run(self, mocke... | TestUpdateDataDocsAction |
python | facebook__pyre-check | tools/incremental_test/specification.py | {
"start": 2590,
"end": 4969
} | class ____(ABC):
@abstractmethod
def to_json(self) -> Dict[str, Any]:
raise NotImplementedError()
@abstractmethod
def update_steps(self) -> List["SingleUpdate"]:
raise NotImplementedError()
@staticmethod
def from_json(input_json: Dict[str, Any]) -> "RepositoryUpdate":
t... | RepositoryUpdate |
python | bokeh__bokeh | src/bokeh/models/widgets/pickers.py | {
"start": 2468,
"end": 3399
} | class ____(HasProps):
""" Common properties for time-like picker widgets. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
hour_increment = Positive(Int)(default=1, help="""
Defines the granularity o... | TimeCommon |
python | openai__openai-python | src/openai/types/beta/realtime/response_text_delta_event.py | {
"start": 200,
"end": 721
} | class ____(BaseModel):
content_index: int
"""The index of the content part in the item's content array."""
delta: str
"""The text delta."""
event_id: str
"""The unique ID of the server event."""
item_id: str
"""The ID of the item."""
output_index: int
"""The index of the outp... | ResponseTextDeltaEvent |
python | PrefectHQ__prefect | tests/infrastructure/provisioners/test_ecs.py | {
"start": 38050,
"end": 41254
} | class ____:
async def test_get_task_count_requires_provisioning(self, execution_role_resource):
count = await execution_role_resource.get_task_count()
assert count == 1
@pytest.mark.usefixtures("existing_execution_role")
async def test_get_task_count_does_not_require_provisioning(
... | TestExecutionRoleResource |
python | keras-team__keras | guides/custom_train_step_in_torch.py | {
"start": 2878,
"end": 5654
} | class ____(keras.Model):
def train_step(self, data):
# Unpack the data. Its structure depends on your model and
# on what you pass to `fit()`.
x, y = data
# Call torch.nn.Module.zero_grad() to clear the leftover gradients
# for the weights from the previous train step.
... | CustomModel |
python | falconry__falcon | examples/recipes/header_name_case_app.py | {
"start": 117,
"end": 431
} | class ____:
def on_get(self, req, resp):
resp.set_header('X-Funky-Header', 'test')
resp.media = {'message': 'Hello'}
app = falcon.App()
app.add_route('/test', FunkyResource())
app = CustomHeadersMiddleware(
app,
custom_capitalization={'x-funky-header': 'X-FuNkY-HeADeR'},
)
| FunkyResource |
python | huggingface__transformers | tests/models/owlv2/test_modeling_owlv2.py | {
"start": 7647,
"end": 11142
} | class ____:
def __init__(
self,
parent,
batch_size=12,
num_queries=4,
seq_length=16,
is_training=True,
use_input_mask=True,
use_labels=True,
vocab_size=99,
hidden_size=64,
num_hidden_layers=12,
num_attention_heads=4,
... | Owlv2TextModelTester |
python | plotly__plotly.py | plotly/graph_objs/sankey/node/_line.py | {
"start": 233,
"end": 4565
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "sankey.node"
_path_str = "sankey.node.line"
_valid_props = {"color", "colorsrc", "width", "widthsrc"}
@property
def color(self):
"""
Sets the color of the `line` around each `node`.
The 'color' property is a color and... | Line |
python | ray-project__ray | python/ray/autoscaler/v2/instance_manager/node_provider.py | {
"start": 2296,
"end": 2662
} | class ____(Exception):
"""
An base error class that represents an error that happened in the cloud instance
provider.
"""
# The timestamp of the error occurred in nanoseconds.
timestamp_ns: int
def __init__(self, msg, timestamp_ns) -> None:
super().__init__(msg)
self.timest... | CloudInstanceProviderError |
python | kamyu104__LeetCode-Solutions | Python/univalued-binary-tree.py | {
"start": 621,
"end": 953
} | class ____(object):
def isUnivalTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return (not root.left or (root.left.val == root.val and self.isUnivalTree(root.left))) and \
(not root.right or (root.right.val == root.val and self.isUnivalTree(root.ri... | Solution2 |
python | doocs__leetcode | solution/2200-2299/2218.Maximum Value of K Coins From Piles/Solution2.py | {
"start": 0,
"end": 401
} | class ____:
def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:
f = [0] * (k + 1)
for nums in piles:
s = list(accumulate(nums, initial=0))
for j in range(k, -1, -1):
for h, w in enumerate(s):
if j < h:
... | Solution |
python | Netflix__metaflow | test/core/tests/recursive_switch_inside_foreach.py | {
"start": 63,
"end": 1578
} | class ____(MetaflowTest):
PRIORITY = 2
ONLY_GRAPHS = ["recursive_switch_inside_foreach"]
@steps(0, ["start"], required=True)
def step_start(self):
self.items = [
{"id": "A", "iterations": 3},
{"id": "B", "iterations": 5},
{"id": "C", "iterations": 2},
... | RecursiveSwitchInsideForeachFlowTest |
python | pallets__werkzeug | src/werkzeug/sansio/multipart.py | {
"start": 562,
"end": 643
} | class ____(Event):
data: bytes
more_data: bool
@dataclass(frozen=True)
| Data |
python | Textualize__textual | src/textual/css/_style_properties.py | {
"start": 12031,
"end": 13075
} | class ____(NamedTuple):
"""Stores edges for border / outline."""
top: tuple[EdgeType, Color]
right: tuple[EdgeType, Color]
bottom: tuple[EdgeType, Color]
left: tuple[EdgeType, Color]
def __bool__(self) -> bool:
(top, _), (right, _), (bottom, _), (left, _) = self
return bool(top... | Edges |
python | numpy__numpy | numpy/typing/tests/data/pass/scalars.py | {
"start": 335,
"end": 393
} | class ____:
def __int__(self) -> int:
return 4
| B |
python | numpy__numpy | numpy/lib/_index_tricks_impl.py | {
"start": 19834,
"end": 20816
} | class ____:
"""
Multidimensional index iterator.
Return an iterator yielding pairs of array coordinates and values.
Parameters
----------
arr : ndarray
Input array.
See Also
--------
ndindex, flatiter
Examples
--------
>>> import numpy as np
>>> a = np.array... | ndenumerate |
python | django__django | tests/migrations/test_migrations_squashed_double/0005_squashed_0003_and_0004.py | {
"start": 43,
"end": 680
} | class ____(migrations.Migration):
replaces = [
("migrations", "0003_squashed_0001_and_0002"),
("migrations", "0004_auto"),
]
operations = [
migrations.CreateModel(
name="A",
fields=[
(
"id",
models.BigAut... | Migration |
python | pandas-dev__pandas | pandas/tests/indexes/datetimelike_/test_equals.py | {
"start": 4976,
"end": 6582
} | class ____(EqualsTests):
@pytest.fixture
def index(self):
"""Fixture for creating a TimedeltaIndex for use in equality tests."""
return timedelta_range("1 day", periods=10)
def test_equals2(self):
# GH#13107
idx = TimedeltaIndex(["1 days", "2 days", "NaT"])
assert id... | TestTimedeltaIndexEquals |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.