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 | PrefectHQ__prefect | tests/_internal/pydantic/test_validated_func.py | {
"start": 9235,
"end": 11657
} | class ____:
"""Test edge cases and corner scenarios."""
def test_no_parameters(self):
def func():
return "no params"
vf = ValidatedFunction(func)
result = vf.validate_call_args((), {})
assert result == {}
def test_only_defaults(self):
def func(a=1, b=2... | TestEdgeCases |
python | getsentry__sentry | src/sentry/integrations/jira_server/search.py | {
"start": 800,
"end": 3892
} | class ____(IntegrationEndpoint):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
provider = IntegrationProviderSlug.JIRA_SERVER.value
def _get_integration(self, organization, integration_id) -> Integration:
return Integration.objects.get(
... | JiraServerSearchEndpoint |
python | spack__spack | lib/spack/spack/package_base.py | {
"start": 106519,
"end": 107015
} | class ____(InstallError):
"""Raised when package is still needed by another on uninstall."""
def __init__(self, spec, dependents):
spec_fmt = spack.spec.DEFAULT_FORMAT + " /{hash:7}"
dep_fmt = "{name}{@versions} /{hash:7}"
super().__init__(
f"Cannot uninstall {spec.format(sp... | PackageStillNeededError |
python | kamyu104__LeetCode-Solutions | Python/most-expensive-item-that-can-not-be-bought.py | {
"start": 504,
"end": 978
} | class ____(object):
def mostExpensiveItem(self, primeOne, primeTwo):
"""
:type primeOne: int
:type primeTwo: int
:rtype: int
"""
dp = [False]*max(primeOne, primeTwo)
dp[0] = True
result = 1
for i in xrange(2, primeOne*primeTwo):
dp[... | Solution2 |
python | apache__airflow | shared/secrets_masker/tests/secrets_masker/test_secrets_masker.py | {
"start": 26118,
"end": 27478
} | class ____:
def test_circular_references(self):
circular_dict: dict[str, any] = {"key": "value", "password": "secret_password"}
circular_dict["self_ref"] = circular_dict
secrets_masker = SecretsMasker()
configure_secrets_masker_for_test(secrets_masker)
with patch(
... | TestEdgeCases |
python | huggingface__transformers | src/transformers/data/processors/xnli.py | {
"start": 889,
"end": 3481
} | class ____(DataProcessor):
"""
Processor for the XNLI dataset. Adapted from
https://github.com/google-research/bert/blob/f39e881b169b9d53bea03d2d341b31707a6c052b/run_classifier.py#L207
"""
def __init__(self, language, train_language=None):
self.language = language
self.train_languag... | XnliProcessor |
python | RaRe-Technologies__gensim | gensim/test/test_doc2vec.py | {
"start": 1757,
"end": 32720
} | class ____(unittest.TestCase):
def test_persistence(self):
"""Test storing/loading the entire model."""
tmpf = get_tmpfile('gensim_doc2vec.tst')
model = doc2vec.Doc2Vec(DocsLeeCorpus(), min_count=1)
model.save(tmpf)
self.models_equal(model, doc2vec.Doc2Vec.load(tmpf))
de... | TestDoc2VecModel |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 180655,
"end": 184065
} | class ____:
def test_vector(self, backend):
cert = _load_cert(
os.path.join("x509", "custom", "freshestcrl.pem"),
x509.load_pem_x509_certificate,
)
fcrl = cert.extensions.get_extension_for_class(x509.FreshestCRL).value
assert fcrl == x509.FreshestCRL(
... | TestFreshestCRLExtension |
python | great-expectations__great_expectations | docs/logging.py | {
"start": 0,
"end": 478
} | class ____:
"""Simple logger for printing to console during docs build"""
@staticmethod
def print_header(string: str) -> None:
LINE = "================================================================================"
Logger.print(LINE)
Logger.print(string)
Logger.print(LINE)... | Logger |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/map_test.py | {
"start": 64011,
"end": 66395
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(test_base.v2_only_combinations(),
combinations.combine(index=[-1, 4, 5])))
def testInvalidIndex(self, index):
dataset = dataset_ops.Dataset.from_tensor_slices([-1, 0, 1,
... | MapRandomAccessTest |
python | doocs__leetcode | lcp/LCP 61. 气温变化趋势/Solution.py | {
"start": 0,
"end": 395
} | class ____:
def temperatureTrend(self, temperatureA: List[int], temperatureB: List[int]) -> int:
ans = f = 0
for (a1, b1), (a2, b2) in pairwise(zip(temperatureA, temperatureB)):
x, y = a2 - a1, b2 - b1
if x == y == 0 or x * y > 0:
f += 1
ans = ... | Solution |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_lease_candidate_spec.py | {
"start": 383,
"end": 11356
} | 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... | V1beta1LeaseCandidateSpec |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_structured_output_retry.py | {
"start": 587,
"end": 2262
} | class ____(AgentMiddleware):
"""Retries model calls when structured output parsing fails."""
def __init__(self, max_retries: int) -> None:
"""Initialize the structured output retry middleware.
Args:
max_retries: Maximum number of retry attempts.
"""
self.max_retries... | StructuredOutputRetryMiddleware |
python | doocs__leetcode | solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution2.py | {
"start": 0,
"end": 220
} | class ____:
def minimumCoins(self, prices: List[int]) -> int:
n = len(prices)
for i in range((n - 1) // 2, 0, -1):
prices[i - 1] += min(prices[i : i * 2 + 1])
return prices[0]
| Solution |
python | pypa__warehouse | tests/unit/subscriptions/test_services.py | {
"start": 14763,
"end": 15703
} | class ____:
def test_basic_init(self):
api = pretend.stub()
billing_service = GenericBillingService(
api=api,
publishable_key="secret_to_everybody",
webhook_secret="keep_it_secret_keep_it_safe",
domain="tests",
)
assert billing_servic... | TestGenericBillingService |
python | joke2k__faker | faker/providers/automotive/fil_PH/__init__.py | {
"start": 57,
"end": 238
} | class ____(EnPhAutomotiveProvider):
"""Implement automotive provider for ``fil_PH`` locale.
There is no difference from the ``en_PH`` implementation.
"""
pass
| Provider |
python | pypa__pip | src/pip/_vendor/pygments/util.py | {
"start": 9892,
"end": 10031
} | class ____(TextIOWrapper):
# Don't close underlying buffer on destruction.
def close(self):
self.flush()
| UnclosingTextIOWrapper |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/pandas_datasource.py | {
"start": 23092,
"end": 68714
} | class ____(_PandasDatasource):
"""Adds a single-batch pandas datasource to the data context.
Args:
name: The name of this datasource.
assets: An optional dictionary whose keys are Pandas DataAsset names and whose values
are Pandas DataAsset objects.
"""
# class directive to... | PandasDatasource |
python | kubernetes-client__python | kubernetes/client/models/v1_resource_claim_template_spec.py | {
"start": 383,
"end": 4334
} | 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... | V1ResourceClaimTemplateSpec |
python | mwaskom__seaborn | seaborn/_core/typing.py | {
"start": 1413,
"end": 1481
} | class ____:
def __repr__(self):
return "<default>"
| Default |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec26.py | {
"start": 223,
"end": 535
} | class ____(Generic[P]):
def __init__(self, func: Callable[P, Any]) -> None: ...
def func1(a: A[Concatenate[int, P]]) -> A[P]: ...
def func2(a: int, b: str) -> str: ...
val1 = A(func2)
reveal_type(val1, expected_text="A[(a: int, b: str)]")
val2 = func1(val1)
reveal_type(val2, expected_text="A[(b: str)]")
| A |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 24535,
"end": 25066
} | class ____(Expr):
"""Calls an expression. `args` is a list of arguments, `kwargs` a list
of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
and `dyn_kwargs` has to be either `None` or a node that is used as
node for dynamic positional (``*args``) or keyword (``**kwargs``)
argumen... | Call |
python | kamyu104__LeetCode-Solutions | Python/report-spam-message.py | {
"start": 46,
"end": 351
} | class ____(object):
def reportSpam(self, message, bannedWords):
"""
:type message: List[str]
:type bannedWords: List[str]
:rtype: bool
"""
THRESHOLD = 2
lookup = set(bannedWords)
return sum(m in lookup for m in message) >= THRESHOLD
| Solution |
python | py-pdf__pypdf | pypdf/generic/_files.py | {
"start": 758,
"end": 16238
} | class ____:
"""
Container holding the information on an embedded file.
Attributes are evaluated lazily if possible.
Further information on embedded files can be found in section 7.11 of the PDF 2.0 specification.
"""
def __init__(self, name: str, pdf_object: DictionaryObject, parent: ArrayObje... | EmbeddedFile |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_flows.py | {
"start": 306,
"end": 419
} | class ____:
tainted_attribute: List[int] = []
tainted_class_attribute: List[int] = []
not_tainted = 2
| C |
python | charliermarsh__ruff | python/ruff-ecosystem/ruff_ecosystem/check.py | {
"start": 10157,
"end": 13489
} | class ____:
"""
The number of additions and removals by rule code.
While the attributes are frozen to avoid accidentally changing the value of an attribute,
the counters themselves are mutable and this class can be mutated with `+` and `update`.
"""
added_violations: Counter = field(default_fa... | RuleChanges |
python | kamyu104__LeetCode-Solutions | Python/number-of-subarrays-having-even-product.py | {
"start": 381,
"end": 674
} | class ____(object):
def evenProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = cnt = 0
for i, x in enumerate(nums):
if x%2 == 0:
cnt = i+1
result += cnt
return result
| Solution2 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/resource_requirement.py | {
"start": 4424,
"end": 5034
} | class ____(ResourceKeyRequirement):
key: str # pyright: ignore[reportIncompatibleMethodOverride]
asset_key: Optional[str]
@property
def expected_type(self) -> type:
from dagster._core.storage.io_manager import IOManagerDefinition
return IOManagerDefinition
def describe_requiremen... | ExternalAssetIOManagerRequirement |
python | python-pillow__Pillow | src/PIL/ImageFilter.py | {
"start": 3913,
"end": 4226
} | class ____(RankFilter):
"""
Create a max filter. Picks the largest pixel value in a window with the
given size.
:param size: The kernel size, in pixels.
"""
name = "Max"
def __init__(self, size: int = 3) -> None:
self.size = size
self.rank = size * size - 1
| MaxFilter |
python | tensorflow__tensorflow | tensorflow/dtensor/python/layout.py | {
"start": 1834,
"end": 13333
} | class ____(_pywrap_dtensor_device.Mesh):
"""Represents a Mesh configuration over a certain list of Mesh Dimensions.
A mesh consists of named dimensions with sizes, which describe how a set of
devices are arranged. Defining tensor layouts in terms of mesh dimensions
allows us to efficiently determine the commun... | Mesh |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/axes_divider.py | {
"start": 11575,
"end": 18221
} | class ____(Divider):
"""
Divider based on the preexisting axes.
"""
def __init__(self, axes, xref=None, yref=None):
"""
Parameters
----------
axes : :class:`~matplotlib.axes.Axes`
xref
yref
"""
self._axes = axes
if xref is None:
... | AxesDivider |
python | walkccc__LeetCode | solutions/1872. Stone Game VIII/1872.py | {
"start": 0,
"end": 516
} | class ____:
def stoneGameVIII(self, stones: list[int]) -> int:
n = len(stones)
prefix = list(itertools.accumulate(stones))
# dp[i] := the maximum score difference the current player can get when the
# game starts at i, i.e. stones[0..i] are merged into the value prefix[i]
dp = [-math.inf] * n
... | Solution |
python | ansible__ansible | lib/ansible/module_utils/facts/system/lsb.py | {
"start": 903,
"end": 3454
} | class ____(BaseFactCollector):
name = 'lsb'
_fact_ids = set() # type: t.Set[str]
STRIP_QUOTES = r'\'\"\\'
def _lsb_release_bin(self, lsb_path, module):
lsb_facts = {}
if not lsb_path:
return lsb_facts
rc, out, err = module.run_command([lsb_path, "-a"], errors='sur... | LSBFactCollector |
python | pytorch__pytorch | torch/cpu/__init__.py | {
"start": 2124,
"end": 2451
} | class ____:
"""
N.B. This class only exists to facilitate device-agnostic code
"""
def __init__(self, priority: int = -1) -> None:
pass
def wait_stream(self, stream) -> None:
pass
def record_event(self) -> None:
pass
def wait_event(self, event) -> None:
pa... | Stream |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_sp500_ticker.py | {
"start": 677,
"end": 1681
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_sp500_ticker"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pand... | ColumnValuesToBeValidSp500Ticker |
python | pallets__flask | src/flask/cli.py | {
"start": 29098,
"end": 36808
} | class ____(click.Path):
"""Click option type that accepts a list of values separated by the
OS's path separator (``:``, ``;`` on Windows). Each value is
validated as a :class:`click.Path` type.
"""
def convert(
self, value: t.Any, param: click.Parameter | None, ctx: click.Context | None
... | SeparatedPathType |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/databricks_sql_datasource.py | {
"start": 4342,
"end": 5830
} | class ____(SqlTableAsset):
@pydantic.validator("table_name")
@override
def _resolve_quoted_name(cls, table_name: str) -> str | quoted_name:
table_name_is_quoted: bool = cls._is_bracketed_by_quotes(table_name)
from great_expectations.compatibility import sqlalchemy
if sqlalchemy.quo... | DatabricksTableAsset |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 28157,
"end": 30759
} | class ____(ASTBase):
def __init__(
self, args: list[ASTFunctionParameter], attrs: ASTAttributeList
) -> None:
self.args = args
self.attrs = attrs
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTParameters):
return NotImplemented
retur... | ASTParameters |
python | huggingface__transformers | src/transformers/models/metaclip_2/modeling_metaclip_2.py | {
"start": 48831,
"end": 50957
} | class ____(MetaClip2PreTrainedModel):
main_input_name = "pixel_values"
input_modalities = ("image",)
def __init__(self, config: MetaClip2Config) -> None:
super().__init__(config)
self.num_labels = config.num_labels
vision_model = MetaClip2VisionModel._from_config(config.vision_conf... | MetaClip2ForImageClassification |
python | mlflow__mlflow | mlflow/tracking/_model_registry/client.py | {
"start": 1389,
"end": 32533
} | class ____:
"""
Client of an MLflow Model Registry Server that creates and manages registered
models and model versions.
"""
def __init__(self, registry_uri, tracking_uri):
"""
Args:
registry_uri: Address of local or remote model registry server.
tracking_uri... | ModelRegistryClient |
python | doocs__leetcode | solution/3300-3399/3394.Check if Grid can be Cut into Sections/Solution.py | {
"start": 0,
"end": 1080
} | class ____:
def countLineIntersections(self, coordinates: List[tuple[int, int]]) -> bool:
lines = 0
overlap = 0
for value, marker in coordinates:
if marker == 0:
overlap -= 1
else:
overlap += 1
if overlap == 0:
... | Solution |
python | crytic__slither | slither/slithir/operations/length.py | {
"start": 632,
"end": 1401
} | class ____(OperationWithLValue):
def __init__(
self,
value: Union[StateVariable, LocalIRVariable, LocalVariable, StateIRVariable],
lvalue: Union[ReferenceVariable, ReferenceVariableSSA],
) -> None:
super().__init__()
assert is_valid_rvalue(value)
assert is_valid_l... | Length |
python | doocs__leetcode | solution/1800-1899/1877.Minimize Maximum Pair Sum in Array/Solution.py | {
"start": 0,
"end": 169
} | class ____:
def minPairSum(self, nums: List[int]) -> int:
nums.sort()
return max(x + nums[-i - 1] for i, x in enumerate(nums[: len(nums) >> 1]))
| Solution |
python | django__django | tests/i18n/test_management.py | {
"start": 126,
"end": 1046
} | class ____(SimpleTestCase):
def test_repr(self):
dirpath = "dir"
file_name = "example"
trans_file = TranslatableFile(
dirpath=dirpath, file_name=file_name, locale_dir=None
)
self.assertEqual(
repr(trans_file),
"<TranslatableFile: %s>" % os.... | TranslatableFileTests |
python | redis__redis-py | redis/commands/core.py | {
"start": 188499,
"end": 213557
} | class ____(CommandsProtocol):
"""
Redis commands for Hash data type.
see: https://redis.io/topics/data-types-intro#redis-hashes
"""
def hdel(self, name: str, *keys: str) -> Union[Awaitable[int], int]:
"""
Delete ``keys`` from hash ``name``
For more information, see https://... | HashCommands |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1302404,
"end": 1302596
} | class ____(VegaLiteSchema):
"""SymbolShape schema wrapper."""
_schema = {"$ref": "#/definitions/SymbolShape"}
def __init__(self, *args):
super().__init__(*args)
| SymbolShape |
python | bokeh__bokeh | release/action.py | {
"start": 1124,
"end": 1225
} | class ____(ActionReturn):
""""""
kind = ActionResult.PASS
ui = staticmethod(passed)
| PASSED |
python | redis__redis-py | redis/_parsers/commands.py | {
"start": 286,
"end": 573
} | class ____(Enum):
ALL_NODES = "all_nodes"
ALL_SHARDS = "all_shards"
ALL_REPLICAS = "all_replicas"
MULTI_SHARD = "multi_shard"
SPECIAL = "special"
DEFAULT_KEYLESS = "default_keyless"
DEFAULT_KEYED = "default_keyed"
DEFAULT_NODE = "default_node"
| RequestPolicy |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/types.py | {
"start": 9033,
"end": 9138
} | class ____(sqltypes.Boolean):
def get_dbapi_type(self, dbapi):
return dbapi.NUMBER
| _OracleBoolean |
python | Pylons__pyramid | src/pyramid/config/views.py | {
"start": 85483,
"end": 93315
} | class ____:
def __init__(self):
self.registrations = []
self.cache_busters = []
def generate(self, path, request, **kw):
for url, spec, route_name in self.registrations:
if path.startswith(spec):
subpath = path[len(spec) :]
if WIN: # pragma: ... | StaticURLInfo |
python | django__django | tests/admin_filters/tests.py | {
"start": 3058,
"end": 3210
} | class ____(DecadeListFilter):
title = "publication decade"
parameter_name = "decade__in" # Ends with '__in"
| DecadeListFilterParameterEndsWith__In |
python | dateutil__dateutil | tests/test_relativedelta.py | {
"start": 262,
"end": 27638
} | class ____(unittest.TestCase):
now = datetime(2003, 9, 17, 20, 54, 47, 282310)
today = date(2003, 9, 17)
def testInheritance(self):
# Ensure that relativedelta is inheritance-friendly.
class rdChildClass(relativedelta):
pass
ccRD = rdChildClass(years=1, months=1, days=1... | RelativeDeltaTest |
python | ray-project__ray | python/ray/serve/tests/test_http_headers.py | {
"start": 1133,
"end": 5823
} | class ____:
def verify_result(self):
for header_attr in ["X-Request-ID"]:
resp = httpx.get(
f"{get_application_url()}", headers={header_attr: "123-234"}
)
assert resp.status_code == 200
assert resp.json() == 1
assert resp.headers[he... | TestUserProvidedRequestIDHeader |
python | Netflix__metaflow | test/core/tests/detect_segfault.py | {
"start": 67,
"end": 1284
} | class ____(MetaflowTest):
"""
Test that segmentation faults produce a message in the logs
"""
PRIORITY = 2
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
"rec... | DetectSegFaultTest |
python | huggingface__transformers | tests/models/patchtst/test_modeling_patchtst.py | {
"start": 5104,
"end": 11510
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
PatchTSTModel,
PatchTSTForPrediction,
PatchTSTForPretraining,
PatchTSTForClassification,
PatchTSTForRegression,
)
if is_torch_available()
... | PatchTSTModelTest |
python | apache__thrift | lib/py/src/server/THttpServer.py | {
"start": 951,
"end": 1565
} | class ____(Exception):
"""Allows handlers to override the HTTP response
Normally, THttpServer always sends a 200 response. If a handler wants
to override this behavior (e.g., to simulate a misconfigured or
overloaded web server during testing), it can raise a ResponseException.
The function passed... | ResponseException |
python | langchain-ai__langchain | libs/core/langchain_core/tracers/evaluation.py | {
"start": 1017,
"end": 8367
} | class ____(BaseTracer):
"""Tracer that runs a run evaluator whenever a run is persisted.
Attributes:
client : Client
The LangSmith client instance used for evaluating the runs.
"""
name: str = "evaluator_callback_handler"
example_id: UUID | None = None
"""The example ID ass... | EvaluatorCallbackHandler |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/dependency.py | {
"start": 31936,
"end": 36396
} | class ____(_DependencyProcessor):
"""For many-to-one relationships with no one-to-many backref,
searches for parents through the unit of work when a primary
key has changed and updates them.
Theoretically, this approach could be expanded to support transparent
deletion of objects referenced via man... | _DetectKeySwitch |
python | bokeh__bokeh | tests/unit/bokeh/document/test_events__document.py | {
"start": 12478,
"end": 14084
} | class ____:
def test_init(self) -> None:
doc = Document()
m = SomeModel()
e = bde.ColumnsPatchedEvent(doc, m, "data", [1, 2], "setter", "invoker")
assert e.document == doc
assert e.model == m
assert e.attr == "data"
assert e.patches == [1, 2]
assert e.... | TestColumnsPatchedEvent |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_michigan_zip.py | {
"start": 1751,
"end": 4094
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Michigan zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
... | ExpectColumnValuesToBeValidMichiganZip |
python | pypa__setuptools | setuptools/command/develop.py | {
"start": 160,
"end": 1411
} | class ____(Command):
"""Set up package for development"""
user_options = [
("install-dir=", "d", "install package to DIR"),
('no-deps', 'N', "don't install dependencies"),
('user', None, f"install in user site-package '{site.USER_SITE}'"),
('prefix=', None, "installation prefix"... | develop |
python | streamlit__streamlit | lib/streamlit/watcher/path_watcher.py | {
"start": 1346,
"end": 5716
} | class ____:
def __init__(
self,
_path_str: str,
_on_changed: Callable[[str], None],
*, # keyword-only arguments:
glob_pattern: str | None = None,
allow_nonexistent: bool = False,
) -> None:
pass
# EventBasedPathWatcher will be a stub and have no functio... | NoOpPathWatcher |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dlp.py | {
"start": 7122,
"end": 7995
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook")
def test_create_stored_info_type(self, mock_hook):
mock_hook.return_value.create_stored_info_type.return_value = StoredInfoType(name=DLP_JOB_PATH)
operator = CloudDLPCreateStoredInfoTypeOperator(organization_id=... | TestCloudDLPCreateStoredInfoTypeOperator |
python | bokeh__bokeh | src/bokeh/core/validation/issue.py | {
"start": 1420,
"end": 1507
} | class ____:
code: int
name: str
description: str
@dataclass(frozen=True)
| Issue |
python | pandas-dev__pandas | asv_bench/benchmarks/series_methods.py | {
"start": 6763,
"end": 7063
} | class ____:
params = [[10**3, 10**6], ["fast", "slow"], ["bool", "boolean"]]
param_names = ["N", "case", "dtype"]
def setup(self, N, case, dtype):
val = case != "fast"
self.s = Series([val] * N, dtype=dtype)
def time_all(self, N, case, dtype):
self.s.all()
| All |
python | astropy__astropy | astropy/modeling/fitting.py | {
"start": 63976,
"end": 64629
} | class ____(_NLLSQFitter):
"""
Trust Region Reflective algorithm and least squares statistic.
Parameters
----------
calc_uncertainties : bool
If the covariance matrix should be computed and set in the fit_info.
Default: False
Attributes
----------
fit_info :
A `s... | TRFLSQFitter |
python | getsentry__sentry | src/sentry/migrations/0981_add_dashboard_migration_fields.py | {
"start": 155,
"end": 1617
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | neetcode-gh__leetcode | python/0297-serialize-and-deserialize-binary-tree.py | {
"start": 172,
"end": 797
} | class ____:
def serialize(self, root):
res = []
def dfs(node):
if not node:
res.append("N")
return
res.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ",".join(res)
def deseri... | Codec |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/renderer.py | {
"start": 10231,
"end": 10341
} | class ____(Exception):
"Information unavailable. Did not yet receive the CPR response."
| HeightIsUnknownError |
python | kamyu104__LeetCode-Solutions | Python/campus-bikes.py | {
"start": 67,
"end": 1114
} | class ____(object):
def assignBikes(self, workers, bikes):
"""
:type workers: List[List[int]]
:type bikes: List[List[int]]
:rtype: List[int]
"""
def manhattan(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
distances = [[] for _ in... | Solution |
python | huggingface__transformers | src/transformers/models/camembert/modeling_camembert.py | {
"start": 10655,
"end": 12061
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
super().__init__()
self.is_cross_attention = is_cross_attention
attention_class = CamembertCrossAttention if is_cross_attention else CamembertSelfAttention
self.self = attent... | CamembertAttention |
python | pypa__pip | src/pip/_internal/utils/misc.py | {
"start": 15844,
"end": 19310
} | class ____:
secret: str
redacted: str
def __repr__(self) -> str:
return f"<HiddenText {str(self)!r}>"
def __str__(self) -> str:
return self.redacted
def __eq__(self, other: object) -> bool:
# Equality is particularly useful for testing.
if type(self) is type(other)... | HiddenText |
python | psf__black | tests/data/cases/class_methods_new_line.py | {
"start": 187,
"end": 288
} | class ____:
"""Just a docstring."""
def __init__(self):
pass
| ClassWithTheDocstringAndInit |
python | ray-project__ray | release/nightly_tests/placement_group_tests/pg_run.py | {
"start": 281,
"end": 463
} | class ____(object):
def __init__(self, i):
self.i = i
def work(self):
time.sleep(0.1)
print("work ", self.i)
@ray.remote(num_cpus=1, num_gpus=1)
| Worker |
python | kamyu104__LeetCode-Solutions | Python/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.py | {
"start": 33,
"end": 734
} | class ____(object):
def findTheCity(self, n, edges, distanceThreshold):
"""
:type n: int
:type edges: List[List[int]]
:type distanceThreshold: int
:rtype: int
"""
dist = [[float("inf")]*n for _ in xrange(n)]
for i, j, w in edges:
dist[i][j]... | Solution |
python | doocs__leetcode | solution/0700-0799/0743.Network Delay Time/Solution.py | {
"start": 0,
"end": 623
} | class ____:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
g = [[inf] * n for _ in range(n)]
for u, v, w in times:
g[u - 1][v - 1] = w
dist = [inf] * n
dist[k - 1] = 0
vis = [False] * n
for _ in range(n):
t = -1
... | Solution |
python | spyder-ide__spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | {
"start": 3536,
"end": 4451
} | class ____:
Close = 'close'
ConvertToBool = 'convert_to_bool_action'
ConvertToComplex = 'convert_to_complex_action'
ConvertToFloat = 'convert_to_float_action'
ConvertToInt = 'convert_to_int_action'
ConvertToStr = 'convert_to_str_action'
Copy = 'copy_action'
DuplicateColumn = 'duplicate_c... | DataframeEditorActions |
python | realpython__materials | python-guitar-synthesizer/source_code_final/src/digitar/instrument.py | {
"start": 470,
"end": 798
} | class ____:
strings: tuple[VibratingString, ...]
@classmethod
def from_notes(cls, *notes: str) -> Self:
return cls(
tuple(
VibratingString(Pitch.from_scientific_notation(note))
for note in reversed(notes)
)
)
@dataclass(frozen=True)
| StringTuning |
python | automl__auto-sklearn | test/test_metalearning/pyMetaLearn/test_metalearning_configuration.py | {
"start": 284,
"end": 1879
} | class ____(unittest.TestCase):
def test_metalearning_cs_size(self):
self.cwd = os.getcwd()
data_dir = os.path.dirname(__file__)
data_dir = os.path.join(data_dir, "test_meta_base_data")
os.chdir(data_dir)
# Total: 176, categorical: 3, numerical: 7, string: 7
total = 1... | MetalearningConfiguration |
python | getsentry__sentry | src/sentry/rules/conditions/event_attribute.py | {
"start": 7708,
"end": 7956
} | class ____(AttributeHandler):
minimum_path_length = 1
@classmethod
def _handle(cls, path: list[str], event: GroupEvent) -> list[str]:
return [str(event.data.get("type"))]
@attribute_registry.register("extra")
| TypeAttributeHandler |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/memory_cleanup_test.py | {
"start": 1441,
"end": 6737
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
def setUp(self):
super(MemoryCleanupTest, self).setUp()
self._devices = self.configureDevicesForMultiDeviceTest(3)
def assertMemoryNotIncreasing(self, f, num_iters, max_increase_mb):
"""Assert memory usage doesn't increase beyond given thr... | MemoryCleanupTest |
python | davidhalter__parso | parso/python/errors.py | {
"start": 25683,
"end": 26716
} | class ____(SyntaxRule):
message = "from __future__ imports must occur at the beginning of the file"
def is_issue(self, node):
if _is_future_import(node):
if not _is_future_import_first(node):
return True
for from_name, future_name in node.get_paths():
... | _FutureImportRule |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_deployments.py | {
"start": 41882,
"end": 43518
} | class ____:
async def test_read_deployment(
self,
client,
deployment,
):
response = await client.get(f"/deployments/{deployment.id}")
assert response.status_code == status.HTTP_200_OK
assert response.json()["id"] == str(deployment.id)
assert response.json(... | TestReadDeployment |
python | doocs__leetcode | solution/0600-0699/0645.Set Mismatch/Solution2.py | {
"start": 0,
"end": 310
} | class ____:
def findErrorNums(self, nums: List[int]) -> List[int]:
cnt = Counter(nums)
n = len(nums)
ans = [0] * 2
for x in range(1, n + 1):
if cnt[x] == 2:
ans[0] = x
if cnt[x] == 0:
ans[1] = x
return ans
| Solution |
python | pytorch__pytorch | torchgen/api/autograd.py | {
"start": 9554,
"end": 9746
} | class ____:
name: str
type: Type
# TODO: only to keep it byte-for-byte compatible with the old codegen, should remove.
cpp_type: str
@dataclass(frozen=True)
| DifferentiableOutput |
python | realpython__materials | python-mappings/pizza_menu.py | {
"start": 45,
"end": 1765
} | class ____(MutableMapping):
def __init__(self, menu: dict):
self._menu = {}
self._first_letters = {}
for key, value in menu.items():
first_letter = key[0].lower()
if first_letter in self._first_letters:
self._raise_duplicate_key_error(key)
... | PizzaMenu |
python | pytorch__pytorch | test/dynamo/test_autograd_function.py | {
"start": 4075,
"end": 4318
} | class ____(torch.autograd.Function):
@staticmethod
def forward(ctx, foo):
return torch.add(foo, foo)
@staticmethod
def backward(ctx, grad_output):
return grad_output * grad_output.stride()[-1]
| CustomFuncStrideBwd |
python | bokeh__bokeh | src/bokeh/core/query.py | {
"start": 6554,
"end": 6941
} | class ____(_Operator):
''' Form disjunctions from other query predicates.
Construct an ``OR`` expression by making a dict with ``OR`` as the key,
and a list of other query expressions as the value:
.. code-block:: python
# matches any Axis subclasses or models with .name == "mycircle"
... | OR |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 9015,
"end": 9890
} | class ____(LTTextLine):
def __init__(self, word_margin):
LTTextLine.__init__(self, word_margin)
self._x1 = +INF
return
def add(self, obj):
if isinstance(obj, LTChar) and self.word_margin:
margin = self.word_margin * max(obj.width, obj.height)
if self._x1... | LTTextLineHorizontal |
python | google__pytype | pytype/tools/merge_pyi/test_data/typevar.py | {
"start": 21,
"end": 94
} | class ____:
def __init__(self, initialdata = None):
pass
| UserDict |
python | django-haystack__django-haystack | test_haystack/test_indexes.py | {
"start": 25041,
"end": 29959
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.sb = connections["default"].get_backend()
self.bmsi = BasicModelSearchIndex()
self.fmsi = FieldsModelSearchIndex()
self.emsi = ExcludesModelSearchIndex()
self.fwomsi = FieldsWithOverrideModelSearchIndex()
... | ModelSearchIndexTestCase |
python | wandb__wandb | wandb/vendor/pygments/lexers/crystal.py | {
"start": 708,
"end": 16845
} | class ____(ExtendedRegexLexer):
"""
For `Crystal <http://crystal-lang.org>`_ source code.
.. versionadded:: 2.2
"""
name = 'Crystal'
aliases = ['cr', 'crystal']
filenames = ['*.cr']
mimetypes = ['text/x-crystal']
flags = re.DOTALL | re.MULTILINE
def heredoc_callback(self, mat... | CrystalLexer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/types.py | {
"start": 9377,
"end": 10039
} | class ____(_IntegerType, sqltypes.INTEGER):
"""MySQL INTEGER type."""
__visit_name__ = "INTEGER"
def __init__(self, display_width: Optional[int] = None, **kw: Any):
"""Construct an INTEGER.
:param display_width: Optional, maximum display width for this number.
:param unsigned: a ... | INTEGER |
python | py-pdf__pypdf | pypdf/constants.py | {
"start": 8317,
"end": 8759
} | class ____:
"""
Table 4.5.
Table 11 in the 2.0 reference.
"""
K = "/K" # integer
END_OF_LINE = "/EndOfLine" # boolean
ENCODED_BYTE_ALIGN = "/EncodedByteAlign" # boolean
COLUMNS = "/Columns" # integer
ROWS = "/Rows" # integer
END_OF_BLOCK = "/EndOfBlock" # boolean
BLACK... | CcittFaxDecodeParameters |
python | pallets__werkzeug | src/werkzeug/datastructures/cache_control.py | {
"start": 5234,
"end": 7250
} | class ____(ImmutableDictMixin[str, t.Optional[str]], _CacheControl): # type: ignore[misc]
"""A cache control for requests. This is immutable and gives access
to all the request-relevant cache control headers.
To get a header of the :class:`RequestCacheControl` object again you can
convert the object ... | RequestCacheControl |
python | apache__thrift | lib/py/src/transport/TTransport.py | {
"start": 6953,
"end": 7151
} | class ____(object):
"""Factory transport that builds framed transports"""
def getTransport(self, trans):
framed = TFramedTransport(trans)
return framed
| TFramedTransportFactory |
python | kamyu104__LeetCode-Solutions | Python/add-and-search-word-data-structure-design.py | {
"start": 60,
"end": 209
} | class ____(object):
# Initialize your data structure here.
def __init__(self):
self.is_string = False
self.leaves = {}
| TrieNode |
python | joke2k__faker | faker/providers/__init__.py | {
"start": 570,
"end": 23485
} | class ____:
__provider__ = "base"
__lang__: Optional[str] = None
__use_weighting__ = False
# Locales supported by Linux Mint from `/usr/share/i18n/SUPPORTED`
language_locale_codes = {
"aa": ("DJ", "ER", "ET"),
"af": ("ZA",),
"ak": ("GH",),
"am": ("ET",),
"an"... | BaseProvider |
python | dagster-io__dagster | python_modules/libraries/dagster-sling/dagster_sling/resources.py | {
"start": 1548,
"end": 4034
} | class ____(PermissiveConfig):
"""A representation of a connection to a database or file to be used by Sling. This resource can be used as a source or a target for a Sling syncs.
Reference the Sling docs for more information on possible connection types and parameters: https://docs.slingdata.io/connections
... | SlingConnectionResource |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/helpers/object_helpers.py | {
"start": 248,
"end": 1162
} | class ____(EnumMeta):
"""A metaclass for creating enums with case-insensitive keys."""
def __getitem__(cls, item):
try:
return super().__getitem__(item)
except Exception:
for key in cls._member_map_:
if key.casefold() == item.casefold():
... | CaseInsensitiveKeys |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.