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 | walkccc__LeetCode | solutions/496. Next Greater Element I/496.py | {
"start": 0,
"end": 351
} | class ____:
def nextGreaterElement(self, nums1: list[int], nums2: list[int]) -> list[int]:
numToNextGreater = {}
stack = [] # a decreasing stack
for num in nums2:
while stack and stack[-1] < num:
numToNextGreater[stack.pop()] = num
stack.append(num)
return [numToNextGreater.get(... | Solution |
python | jazzband__django-pipeline | tests/tests/test_storage.py | {
"start": 896,
"end": 1065
} | class ____(DummyCompiler):
"""Handles css files"""
output_extension = "css"
def match_file(self, path):
return path.endswith(".css")
| DummyCSSCompiler |
python | sphinx-doc__sphinx | sphinx/ext/imgmath.py | {
"start": 1088,
"end": 1426
} | class ____(SphinxError):
category = 'Math extension error'
def __init__(
self, msg: str, stderr: str | None = None, stdout: str | None = None
) -> None:
if stderr:
msg += '\n[stderr]\n' + stderr
if stdout:
msg += '\n[stdout]\n' + stdout
super().__init... | MathExtError |
python | pandas-dev__pandas | pandas/tests/io/formats/test_to_latex.py | {
"start": 11573,
"end": 20775
} | class ____:
@pytest.fixture
def caption_table(self):
"""Caption for table/tabular LaTeX environment."""
return "a table in a \\texttt{table/tabular} environment"
@pytest.fixture
def short_caption(self):
"""Short caption for testing \\caption[short_caption]{full_caption}."""
... | TestToLatexCaptionLabel |
python | fastai__fastai | fastai/callback/tracker.py | {
"start": 836,
"end": 2473
} | class ____(Callback):
"A `Callback` that keeps track of the best value in `monitor`."
order,remove_on_fetch,_only_train_loop = 60,True,True
def __init__(self,
monitor='valid_loss', # value (usually loss or metric) being monitored.
comp=None, # numpy comparison operator; np.less if monitor i... | TrackerCallback |
python | gevent__gevent | src/greentest/3.14/test_urllib2_localnet.py | {
"start": 8149,
"end": 9501
} | class ____(http.server.BaseHTTPRequestHandler):
"""This is a 'fake proxy' that makes it look like the entire
internet has gone down due to a sudden zombie invasion. It main
utility is in providing us with authentication support for
testing.
"""
def __init__(self, digest_auth_handler, *args, **... | FakeProxyHandler |
python | kubernetes-client__python | kubernetes/client/api/version_api.py | {
"start": 543,
"end": 5113
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | VersionApi |
python | spyder-ide__spyder | spyder/plugins/run/widgets.py | {
"start": 5138,
"end": 19310
} | class ____(BaseRunConfigDialog):
"""Run execution parameters edition dialog."""
def __init__(
self,
parent,
executor_name,
executor_params: Dict[
Tuple[str, str], SupportedExecutionRunConfiguration
],
param_names: Dict[Tuple[str, str], List[str]],
... | ExecutionParametersDialog |
python | numba__numba | numba/tests/test_sysinfo.py | {
"start": 2489,
"end": 4271
} | class ____(TestCase):
mem_total = 2 * 1024 ** 2 # 2_097_152
mem_available = 1024 ** 2 # 1_048_576
cpus_list = [1, 2]
def setUp(self):
super(TestSysInfoWithPsutil, self).setUp()
self.psutil_orig_state = nsi._psutil_import
# Mocking psutil
nsi._psutil_import = True
... | TestSysInfoWithPsutil |
python | encode__django-rest-framework | rest_framework/test.py | {
"start": 13890,
"end": 14823
} | class ____(testcases.SimpleTestCase):
"""
Isolate URL patterns on a per-TestCase basis. For example,
class ATestCase(URLPatternsTestCase):
urlpatterns = [...]
def test_something(self):
...
class AnotherTestCase(URLPatternsTestCase):
urlpatterns = [...]
def... | URLPatternsTestCase |
python | django-import-export__django-import-export | import_export/tmp_storages.py | {
"start": 1710,
"end": 2869
} | class ____(BaseStorage):
_storage = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._configure_storage()
self.MEDIA_FOLDER = kwargs.get("MEDIA_FOLDER", "django-import-export")
# issue 1589 - Ensure that for MediaStorage, we read in binary mode
kwargs.... | MediaStorage |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/entrypoint.py | {
"start": 264,
"end": 1445
} | class ____:
def some_entrypoint_function():
glob.append(1)
@MyEntrypoint
def method_entrypoint_with_decorator():
glob.append(1)
def nested_run():
def do_the_thing():
glob.append(1)
do_the_thing()
def immediate_examples():
glob.append(1)
def this_one_shouldnt_be_fo... | MyClass |
python | google__pytype | build_scripts/release.py | {
"start": 592,
"end": 2587
} | class ____(Exception):
def __init__(self, msg):
super().__init__()
self.msg = msg
def parse_args():
"""Parse and return the command line args."""
allowed_modes = (TEST_MODE, RELEASE_MODE)
parser = argparse.ArgumentParser()
parser.add_argument(
"-m",
"--mode",
type=str,
defau... | ReleaseError |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 1484,
"end": 2197
} | class ____(Token):
""" Represents a renaming in a use statement in Fortran.
Examples
========
>>> from sympy.codegen.fnodes import use_rename, use
>>> from sympy import fcode
>>> ren = use_rename("thingy", "convolution2d")
>>> print(fcode(ren, source_format='free'))
thingy => convoluti... | use_rename |
python | jina-ai__jina | jina/orchestrate/flow/base.py | {
"start": 2368,
"end": 148029
} | class ____(
PostMixin,
ProfileMixin,
HealthCheckMixin,
JAMLCompatible,
BaseOrchestrator,
metaclass=FlowType,
):
"""Flow is how Jina streamlines and distributes Executors."""
# overload_inject_start_client_flow
@overload
def __init__(
self,
*,
asyncio: Opt... | Flow |
python | weaviate__weaviate-python-client | weaviate/users/users.py | {
"start": 343,
"end": 440
} | class ____:
user_id: str
role_names: List[str]
user_type: UserTypes
@dataclass
| UserBase |
python | plotly__plotly.py | plotly/graph_objs/scatterpolar/selected/_marker.py | {
"start": 233,
"end": 3609
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolar.selected"
_path_str = "scatterpolar.selected.marker"
_valid_props = {"color", "opacity", "size"}
@property
def color(self):
"""
Sets the marker color of selected points.
The 'color' property is a color an... | Marker |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constrainedTypeVar1.py | {
"start": 366,
"end": 997
} | class ____(Generic[U]):
def generic_func1(self, a: U, b: str = "", **kwargs: U) -> U:
return a
a1 = ClassA[str]()
r1 = a1.generic_func1("hi")
reveal_type(r1, expected_text="str")
r2 = a1.generic_func1("hi", test="hi")
reveal_type(r2, expected_text="str")
# This should generate an error.
r3 = a1.generic_f... | ClassA |
python | kamyu104__LeetCode-Solutions | Python/maximize-sum-of-at-most-k-distinct-elements.py | {
"start": 329,
"end": 801
} | class ____(object):
def maxKDistinct(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
min_heap = []
for x in set(nums):
heapq.heappush(min_heap, x)
if len(min_heap) == k+1:
heapq.heappop(min_h... | Solution2 |
python | huggingface__transformers | tests/models/internvl/test_modeling_internvl.py | {
"start": 25862,
"end": 45440
} | class ____(unittest.TestCase):
def setUp(self):
self.small_model_checkpoint = "OpenGVLab/InternVL2_5-2B-MPO-hf"
self.medium_model_checkpoint = "OpenGVLab/InternVL2_5-8B-MPO-hf"
cleanup(torch_device, gc_collect=True)
def tearDown(self):
cleanup(torch_device, gc_collect=True)
... | InternVLLlamaIntegrationTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydocstyle/D.py | {
"start": 11994,
"end": 14791
} | class ____: # noqa: D203,D213
"""A Blah.
Parameters
----------
x : int
"""
def __init__(self, x):
pass
expect(os.path.normcase(__file__ if __file__[-1] != 'c' else __file__[:-1]),
'D100: Missing docstring in public module')
@expect('D201: No blank lines allowed before func... | Blah |
python | streamlit__streamlit | lib/streamlit/runtime/scriptrunner_utils/script_requests.py | {
"start": 5876,
"end": 12776
} | class ____:
"""An interface for communicating with a ScriptRunner. Thread-safe.
AppSession makes requests of a ScriptRunner through this class, and
ScriptRunner handles those requests.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._state = ScriptRequestType.CON... | ScriptRequests |
python | Farama-Foundation__Gymnasium | tests/vector/testing_utils.py | {
"start": 3103,
"end": 4698
} | class ____(gym.Env):
"""An environment with custom spaces for observation and action spaces."""
def __init__(self):
"""Initialise the environment."""
super().__init__()
self.observation_space = CustomSpace()
self.action_space = CustomSpace()
def reset(self, *, seed: int | N... | CustomSpaceEnv |
python | great-expectations__great_expectations | docs/sphinx_api_docs_source/public_api_report.py | {
"start": 3886,
"end": 8049
} | class ____:
"""Parse examples from docs to find classes, methods and functions used."""
def __init__(self, file_contents: Set[FileContents]) -> None:
self.file_contents = file_contents
def get_names_from_usage_in_docs_examples(self) -> Set[str]:
"""Get names in docs examples of classes, me... | DocsExampleParser |
python | PrefectHQ__prefect | src/prefect/settings/models/cloud.py | {
"start": 719,
"end": 2171
} | class ____(PrefectBaseSettings):
"""
Settings for interacting with Prefect Cloud
"""
model_config: ClassVar[SettingsConfigDict] = build_settings_config(("cloud",))
api_url: str = Field(
default="https://api.prefect.cloud/api",
description="API URL for Prefect Cloud. Used for authen... | CloudSettings |
python | doocs__leetcode | solution/1800-1899/1814.Count Nice Pairs in an Array/Solution.py | {
"start": 0,
"end": 349
} | class ____:
def countNicePairs(self, nums: List[int]) -> int:
def rev(x):
y = 0
while x:
y = y * 10 + x % 10
x //= 10
return y
cnt = Counter(x - rev(x) for x in nums)
mod = 10**9 + 7
return sum(v * (v - 1) // 2 for ... | Solution |
python | pypa__pip | src/pip/_vendor/urllib3/request.py | {
"start": 213,
"end": 6691
} | class ____(object):
"""
Convenience mixin for classes who implement a :meth:`urlopen` method, such
as :class:`urllib3.HTTPConnectionPool` and
:class:`urllib3.PoolManager`.
Provides behavior for making common types of HTTP request methods and
decides which type of request field encoding to use.
... | RequestMethods |
python | readthedocs__readthedocs.org | readthedocs/core/db.py | {
"start": 158,
"end": 1011
} | class ____:
"""
Router to map Django applications to a specific database.
:py:attr:`apps_to_db` is used to map an application to a database,
if an application isn't listed here, it will use the ``default`` database.
"""
def __init__(self):
self.apps_to_db = defaultdict(lambda: "default... | MapAppsRouter |
python | django-haystack__django-haystack | haystack/views.py | {
"start": 4355,
"end": 6902
} | class ____(SearchView):
def __init__(self, *args, **kwargs):
# Needed to switch out the default form class.
if kwargs.get("form_class") is None:
kwargs["form_class"] = FacetedSearchForm
super().__init__(*args, **kwargs)
def build_form(self, form_kwargs=None):
if for... | FacetedSearchView |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 74314,
"end": 74833
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = torch.nn.Conv2d(3, 5, 3).to(dtype=torch.float)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Conv2d(5, 5, 1).to(dtype=torch.float)
def forward(self, x):
x = self.fc1(x)
x = s... | ConvReluConvModel |
python | ray-project__ray | python/ray/llm/_internal/common/utils/cloud_utils.py | {
"start": 1008,
"end": 1093
} | class ____(BaseModelExtended):
bucket_uri: str
destination_path: str
| ExtraFiles |
python | tiangolo__fastapi | docs_src/response_model/tutorial001_py39.py | {
"start": 109,
"end": 556
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
tags: list[str] = []
@app.post("/items/", response_model=Item)
async def create_item(item: Item) -> Any:
return item
@app.get("/items/", response_model=list[Item])
async def read... | Item |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance6.py | {
"start": 1731,
"end": 1980
} | class ____(ParentD[int]): ...
def func7(a: ParentD[_T1]) -> _T1 | None:
if isinstance(a, ChildD1):
reveal_type(a, expected_text="ChildD1[_T1@func7]")
elif isinstance(a, ChildD2):
reveal_type(a, expected_text="ChildD2")
| ChildD2 |
python | great-expectations__great_expectations | tests/datasource/fluent/test_sql_datasources.py | {
"start": 3459,
"end": 14115
} | class ____:
def test_kwargs_passed_to_create_engine(
self,
create_engine_spy: mock.MagicMock, # noqa: TID251 # FIXME CoP
monkeypatch: pytest.MonkeyPatch,
ephemeral_context_with_defaults: EphemeralDataContext,
ds_kwargs: dict,
filter_gx_datasource_warnings: None,
... | TestConfigPasstrough |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/combinatory_ports.py | {
"start": 671,
"end": 807
} | class ____(Base):
def __init__(self, base: Base) -> None:
self.a: Base = base
def method(self):
self.a.method()
| A |
python | fastapi__sqlmodel | docs_src/tutorial/many_to_many/tutorial002.py | {
"start": 616,
"end": 3203
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
teams: List[Team] = Relationship(back_populates="heroes", link_model=HeroTeamLink)
sqlite_file_name = "da... | Hero |
python | networkx__networkx | networkx/algorithms/assortativity/tests/test_mixing.py | {
"start": 144,
"end": 1134
} | class ____(BaseTestDegreeMixing):
def test_degree_mixing_dict_undirected(self):
d = nx.degree_mixing_dict(self.P4)
d_result = {1: {2: 2}, 2: {1: 2, 2: 2}}
assert d == d_result
def test_degree_mixing_dict_undirected_normalized(self):
d = nx.degree_mixing_dict(self.P4, normalized=... | TestDegreeMixingDict |
python | pennersr__django-allauth | allauth/headless/tokens/strategies/sessions.py | {
"start": 239,
"end": 817
} | class ____(AbstractTokenStrategy):
def create_session_token(self, request: HttpRequest) -> str:
if not request.session.session_key:
request.session.save()
key = request.session.session_key
# We did save
assert isinstance(key, str) # nosec
return key
def look... | SessionTokenStrategy |
python | Pylons__pyramid | src/pyramid/httpexceptions.py | {
"start": 36083,
"end": 36544
} | class ____(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server is currently unable to handle the
request due to a temporary overloading or maintenance of the server.
code: 503, title: Service Unavailable
"""
code = 503
title = 'Service Unavailabl... | HTTPServiceUnavailable |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-talk/components.py | {
"start": 1313,
"end": 2041
} | class ____(DeclarativeAuthenticator):
config: Mapping[str, Any]
legacy_basic_auth: BasicHttpAuthenticator
basic_auth: BasicHttpAuthenticator
oauth: BearerAuthenticator
def __new__(cls, legacy_basic_auth, basic_auth, oauth, config, *args, **kwargs):
credentials = config.get("credentials", {}... | ZendeskTalkAuthenticator |
python | miyuchina__mistletoe | test/test_latex_renderer.py | {
"start": 5154,
"end": 5454
} | class ____(TestCase):
def test_html_entity(self):
self.assertIn('hello \\& goodbye', markdown('hello & goodbye', LaTeXRenderer))
def test_html_entity_in_link_target(self):
self.assertIn('\\href{foo}{hello}', markdown('[hello](foo)', LaTeXRenderer))
| TestHtmlEntity |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_daytime.py | {
"start": 2247,
"end": 5362
} | class ____(ColumnMapExpectation):
"""Expect the provided timestamp is daytime at the given GPS coordinate (latitude, longitude)."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
... | ExpectColumnValuesToBeDaytime |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_glacier.py | {
"start": 1428,
"end": 2291
} | class ____:
op_class: type[AwsBaseOperator]
default_op_kwargs: dict[str, Any]
def test_base_aws_op_attributes(self):
op = self.op_class(**self.default_op_kwargs)
assert op.hook.aws_conn_id == "aws_default"
assert op.hook._region_name is None
assert op.hook._verify is None
... | BaseGlacierOperatorsTests |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 9880,
"end": 9987
} | class ____(IncrementalShopifyGraphQlBulkStream):
bulk_query: InventoryItem = InventoryItem
| InventoryItems |
python | kubernetes-client__python | kubernetes/client/models/v1_probe.py | {
"start": 383,
"end": 13723
} | 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... | V1Probe |
python | requests__requests-oauthlib | tests/test_compliance_fixes.py | {
"start": 3447,
"end": 4583
} | class ____(TestCase):
def setUp(self):
mocker = requests_mock.Mocker()
mocker.post(
"https://login.mailchimp.com/oauth2/token",
json={"access_token": "mailchimp", "expires_in": 0, "scope": None},
)
mocker.start()
self.addCleanup(mocker.stop)
m... | MailChimpComplianceFixTest |
python | keras-team__keras | keras/src/optimizers/adamw.py | {
"start": 171,
"end": 3785
} | class ____(adam.Adam):
"""Optimizer that implements the AdamW algorithm.
AdamW optimization is a stochastic gradient descent method that is based on
adaptive estimation of first-order and second-order moments with an added
method to decay weights per the techniques discussed in the paper,
'Decouple... | AdamW |
python | pydata__xarray | asv_bench/benchmarks/repr.py | {
"start": 62,
"end": 663
} | class ____:
def setup(self):
a = np.arange(0, 100)
data_vars = dict()
for i in a:
data_vars[f"long_variable_name_{i}"] = xr.DataArray(
name=f"long_variable_name_{i}",
data=np.arange(0, 20),
dims=[f"long_coord_name_{i}_x"],
... | Repr |
python | django__django | tests/fixtures/models.py | {
"start": 1035,
"end": 1377
} | class ____(models.Model):
name = models.CharField(max_length=100)
featured = models.ForeignKey(
Article, models.CASCADE, related_name="fixtures_featured_set"
)
articles = models.ManyToManyField(
Article, blank=True, related_name="fixtures_articles_set"
)
def __str__(self):
... | Blog |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_operator.py | {
"start": 29271,
"end": 29448
} | class ____(OperatorPickleTestCase, __TestCase):
module = py_operator
module2 = py_operator
@unittest.skipUnless(c_operator, 'requires _operator')
| PyPyOperatorPickleTestCase |
python | pypa__pipenv | pipenv/patched/pip/_internal/commands/hash.py | {
"start": 434,
"end": 1763
} | class ____(Command):
"""
Compute a hash of a local package archive.
These can be used with --hash in a requirements file to do repeatable
installs.
"""
usage = "%prog [options] <file> ..."
ignore_require_venv = True
def add_options(self) -> None:
self.cmd_opts.add_option(
... | HashCommand |
python | wandb__wandb | wandb/sdk/artifacts/_generated/input_types.py | {
"start": 3177,
"end": 3328
} | class ____(GQLInput):
artifact_collection_name: str = Field(alias="artifactCollectionName")
alias: str = Field(max_length=128)
| ArtifactAliasInput |
python | walkccc__LeetCode | solutions/3548. Equal Sum Grid Partition II/3548.py | {
"start": 1,
"end": 689
} | class ____:
def canPartitionGrid(self, grid: list[list[int]]) -> bool:
summ = sum(map(sum, grid))
def canPartition(grid: list[list[int]]) -> bool:
topSum = 0
seen = set()
for i, row in enumerate(grid):
topSum += sum(row)
botSum = summ - topSum
seen |= set(row)
... | Solution |
python | apache__airflow | dev/breeze/tests/test_publish_docs_to_s3.py | {
"start": 974,
"end": 10930
} | class ____:
def setup_method(self):
self.publish_docs_to_s3 = S3DocsPublish(
source_dir_path="source_dir_path",
destination_location="destination_location",
exclude_docs="exclude_docs",
dry_run=False,
overwrite=False,
parallelism=1,
... | TestPublishDocsToS3 |
python | walkccc__LeetCode | solutions/3. Longest Substring Without Repeating Characters/3-2.py | {
"start": 0,
"end": 435
} | class ____:
def lengthOfLongestSubstring(self, s: str) -> int:
ans = 0
# The substring s[j + 1..i] has no repeating characters.
j = -1
# lastSeen[c] := the index of the last time c appeared
lastSeen = {}
for i, c in enumerate(s):
# Update j to lastSeen[c], so the window must start from ... | Solution |
python | pennersr__django-allauth | allauth/socialaccount/providers/xing/provider.py | {
"start": 564,
"end": 1059
} | class ____(OAuthProvider):
id = "xing"
name = "Xing"
account_class = XingAccount
oauth_adapter_class = XingOAuthAdapter
def extract_uid(self, data):
return data["id"]
def extract_common_fields(self, data):
return dict(
email=data.get("active_email"),
use... | XingProvider |
python | explosion__spaCy | spacy/pipeline/_edit_tree_internals/schemas.py | {
"start": 946,
"end": 1669
} | class ____(BaseModel):
__root__: Union[MatchNodeSchema, SubstNodeSchema]
def validate_edit_tree(obj: Dict[str, Any]) -> List[str]:
"""Validate edit tree.
obj (Dict[str, Any]): JSON-serializable data to validate.
RETURNS (List[str]): A list of error messages, if available.
"""
try:
Edi... | EditTreeSchema |
python | django__django | tests/schema/models.py | {
"start": 4303,
"end": 4544
} | class ____(models.Model):
title = models.CharField(max_length=255)
slug2 = models.SlugField(unique=True)
class Meta:
apps = new_apps
db_table = "schema_tag"
# Based on tests/reserved_names/models.py
| TagUniqueRename |
python | tiangolo__fastapi | tests/test_security_api_key_header.py | {
"start": 217,
"end": 1944
} | class ____(BaseModel):
username: str
def get_current_user(oauth_header: str = Security(api_key)):
user = User(username=oauth_header)
return user
@app.get("/users/me")
def read_current_user(current_user: User = Depends(get_current_user)):
return current_user
client = TestClient(app)
def test_secu... | User |
python | apache__airflow | providers/openlineage/src/airflow/providers/openlineage/utils/utils.py | {
"start": 27712,
"end": 29744
} | class ____(InfoJsonEncodable):
"""Defines encoding DagRun object to JSON."""
includes = [
"conf",
"dag_id",
"data_interval_start",
"data_interval_end",
"external_trigger", # Removed in Airflow 3, use run_type instead
"execution_date", # Airflow 2
"logic... | DagRunInfo |
python | numba__numba | numba/tests/test_cli.py | {
"start": 3934,
"end": 8361
} | class ____(TestCase):
def setUp(self):
# Mock the entire class, to report valid things,
# then override bits of it locally to check failures etc.
self._patches = []
mock_init = lambda self: None
self._patches.append(mock.patch.object(_GDBTestWrapper, '__init__',
... | TestGDBCLIInfo |
python | sympy__sympy | sympy/diffgeom/diffgeom.py | {
"start": 44628,
"end": 46866
} | class ____(Expr):
"""Lie derivative with respect to a vector field.
Explanation
===========
The transport operator that defines the Lie derivative is the pushforward of
the field to be derived along the integral curve of the field with respect
to which one derives.
Examples
========
... | LieDerivative |
python | dask__distributed | distributed/client.py | {
"start": 21214,
"end": 23736
} | class ____(Exception):
"""Raised when an action with a closed client can't be performed"""
def _handle_print(event):
_, msg = event
if not isinstance(msg, dict):
# someone must have manually logged a print event with a hand-crafted
# payload, rather than by calling worker.print(). In that ... | ClosedClientError |
python | allegroai__clearml | examples/frameworks/ignite/cifar_ignite.py | {
"start": 3215,
"end": 7140
} | class ____(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 3)
self.conv2 = nn.Conv2d(6, 16, 3)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(16 * 6 * 6, 120)
self.fc2 = nn.Linear(120, 84)
self.dorpout = nn.Dropout... | Net |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 95760,
"end": 97971
} | class ____(Response):
"""
Response of projects.get_task_tags endpoint.
:param tags: The list of unique tag values
:type tags: Sequence[str]
:param system_tags: The list of unique system tag values. Returned only if
'include_system' is set to 'true' in the request
:type system_tags: Sequ... | GetTaskTagsResponse |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/errors.py | {
"start": 1957,
"end": 2059
} | class ____(HypothesisException):
"""An internal error raised by choice_from_index."""
| ChoiceTooLarge |
python | openai__openai-python | src/openai/types/responses/response.py | {
"start": 1171,
"end": 1552
} | class ____(BaseModel):
reason: Optional[Literal["max_output_tokens", "content_filter"]] = None
"""The reason why the response is incomplete."""
ToolChoice: TypeAlias = Union[
ToolChoiceOptions,
ToolChoiceAllowed,
ToolChoiceTypes,
ToolChoiceFunction,
ToolChoiceMcp,
ToolChoiceCustom,
... | IncompleteDetails |
python | getsentry__sentry | tests/sentry/ratelimits/utils/test_enforce_rate_limit.py | {
"start": 826,
"end": 1169
} | class ____(RateLimitTestEndpoint):
enforce_rate_limit = False
urlpatterns = [
re_path(r"^/enforced$", RateLimitEnforcedEndpoint.as_view(), name="enforced-endpoint"),
re_path(r"^/unenforced$", RateLimitUnenforcedEndpoint.as_view(), name="unenforced-endpoint"),
]
@override_settings(ROOT_URLCONF=__name__)
| RateLimitUnenforcedEndpoint |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 189717,
"end": 190821
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of CreateProjectV2Field"""
__schema__ = github_schema
__field_names__ = ("project_id", "data_type", "name", "single_select_options", "client_mutation_id")
project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId")
""... | CreateProjectV2FieldInput |
python | conda__conda | conda/auxlib/entity.py | {
"start": 21097,
"end": 21151
} | class ____(ListField):
_type = list
| MutableListField |
python | weaviate__weaviate-python-client | weaviate/collections/batch/base.py | {
"start": 32923,
"end": 56099
} | class ____:
def __init__(
self,
connection: ConnectionSync,
consistency_level: Optional[ConsistencyLevel],
results: _BatchDataWrapper,
batch_mode: _BatchMode,
executor: ThreadPoolExecutor,
vectorizer_batching: bool,
objects: Optional[ObjectsBatchReques... | _BatchBaseNew |
python | plotly__plotly.py | tests/test_optional/test_tools/test_figure_factory.py | {
"start": 29438,
"end": 44984
} | class ____(TestCaseNoTemplate, NumpyTestUtilsMixin):
def test_unequal_z_text_size(self):
# check: PlotlyError if z and text are not the same dimensions
kwargs = {"z": [[1, 2], [1, 2]], "annotation_text": [[1, 2, 3], [1]]}
self.assertRaises(PlotlyError, ff.create_annotated_heatmap, **kwargs)... | TestAnnotatedHeatmap |
python | doocs__leetcode | solution/1500-1599/1507.Reformat Date/Solution.py | {
"start": 0,
"end": 282
} | class ____:
def reformatDate(self, date: str) -> str:
s = date.split()
s.reverse()
months = " JanFebMarAprMayJunJulAugSepOctNovDec"
s[1] = str(months.index(s[1]) // 3 + 1).zfill(2)
s[2] = s[2][:-2].zfill(2)
return "-".join(s)
| Solution |
python | apache__airflow | airflow-core/tests/unit/serialization/test_serde.py | {
"start": 5376,
"end": 5444
} | class ____:
__version__: ClassVar[int] = 2
x: int
@dataclass
| W |
python | geekcomputers__Python | insta_monitering/insta_datafetcher.py | {
"start": 427,
"end": 2759
} | class ____(object):
def __init__(self):
filename = os.getcwd() + "/" + "ipList.txt"
with open(filename, "r") as f:
ipdata = f.read()
self._IP = random.choice(ipdata.split(","))
def __call__(self, function_to_call_for_appling_proxy):
SOCKS5_PROXY_HOST = self._IP
... | PorxyApplyingDecorator |
python | scipy__scipy | scipy/stats/tests/test_morestats.py | {
"start": 93533,
"end": 100055
} | class ____:
@pytest.mark.parametrize("dtype", ["float32", "float64"])
def test_basic(self, dtype, xp):
dt = getattr(xp, dtype)
x = stats.norm.rvs(size=10000, loc=10, random_state=54321)
lmbda = 1
llf = stats.boxcox_llf(lmbda, xp.asarray(x, dtype=dt))
llf_expected = -x.si... | TestBoxcox_llf |
python | jina-ai__jina | jina/clients/mixin.py | {
"start": 6217,
"end": 6886
} | class ____:
"""The Profile Mixin for Client and Flow to expose `profile` API"""
def profiling(self, show_table: bool = True) -> Dict[str, float]:
"""Profiling a single query's roundtrip including network and computation latency. Results is summarized in a Dict.
:param show_table: whether to sh... | ProfileMixin |
python | django__django | tests/queries/tests.py | {
"start": 178537,
"end": 178889
} | class ____(TestCase):
def test_filter_rejects_invalid_arguments(self):
school = School.objects.create()
msg = "The following kwargs are invalid: '_connector', '_negated'"
with self.assertRaisesMessage(TypeError, msg):
School.objects.filter(pk=school.pk, _negated=True, _connector=... | TestInvalidFilterArguments |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/resources.py | {
"start": 701,
"end": 851
} | class ____(graphene.Enum):
VALUE = "VALUE"
ENV_VAR = "ENV_VAR"
class Meta:
name = "ConfiguredValueType"
| GrapheneConfiguredValueType |
python | apache__airflow | providers/openlineage/tests/unit/openlineage/dags/test_openlineage_execution.py | {
"start": 1089,
"end": 2783
} | class ____(BaseOperator):
def __init__(self, *, stall_amount=0, fail=False, **kwargs) -> None:
super().__init__(**kwargs)
self.stall_amount = stall_amount
self.fail = fail
def execute(self, context):
self.log.error("STALL AMOUNT %s", self.stall_amount)
time.sleep(1)
... | OpenLineageExecutionOperator |
python | getsentry__sentry | tests/sentry/rules/conditions/test_existing_high_priority_issue.py | {
"start": 312,
"end": 1467
} | class ____(RuleTestCase):
rule_cls = ExistingHighPriorityIssueCondition
def setUp(self) -> None:
self.rule = Rule(environment_id=1, project=self.project, label="label")
def test_applies_correctly(self) -> None:
rule = self.get_rule(rule=self.rule)
# This will never pass for non-ne... | ExistingHighPriorityIssueConditionTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias4.py | {
"start": 216,
"end": 1553
} | class ____:
pass
not_a_type = "ClassA"
def requires_string(a: str):
pass
requires_string(not_a_type)
# This should generate an error because type2 should
# not be interpreted as a string.
requires_string(type2)
# This should generate an error because the symbol
# is later declared as a TypeAlias.
my_typ... | ClassA |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py | {
"start": 78400,
"end": 88742
} | class ____(ShopifyBulkQuery):
"""
{
products(query: "updated_at:>='2020-01-20T00:00:00+00:00' AND updated_at:<'2024-04-25T00:00:00+00:00'", sortKey:UPDATED_AT) {
edges {
node {
__typename
id
publishedAt
... | Product |
python | django__django | tests/admin_widgets/models.py | {
"start": 5630,
"end": 5796
} | class ____(models.Model):
user = models.ForeignKey("auth.User", models.CASCADE, to_field="username")
def __str__(self):
return self.user.username
| Profile |
python | numpy__numpy | numpy/distutils/fujitsuccompiler.py | {
"start": 51,
"end": 834
} | class ____(UnixCCompiler):
"""
Fujitsu compiler.
"""
compiler_type = 'fujitsu'
cc_exe = 'fcc'
cxx_exe = 'FCC'
def __init__(self, verbose=0, dry_run=0, force=0):
UnixCCompiler.__init__(self, verbose, dry_run, force)
cc_compiler = self.cc_exe
cxx_compiler = self.cxx_... | FujitsuCCompiler |
python | kamyu104__LeetCode-Solutions | Python/match-substring-after-replacement.py | {
"start": 113,
"end": 953
} | class ____(object):
def matchReplacement(self, s, sub, mappings):
"""
:type s: str
:type sub: str
:type mappings: List[List[str]]
:rtype: bool
"""
def transform(x):
return ord(x)-ord('0') if x.isdigit() else ord(x)-ord('a')+10 if x.islower() else o... | Solution |
python | python-markdown__markdown | markdown/util.py | {
"start": 6590,
"end": 7073
} | class ____:
""" The base class for all processors.
Attributes:
Processor.md: The `Markdown` instance passed in an initialization.
Arguments:
md: The `Markdown` instance this processor is a part of.
"""
def __init__(self, md: Markdown | None = None):
self.md = md
if TYPE_... | Processor |
python | sympy__sympy | sympy/solvers/ode/single.py | {
"start": 1755,
"end": 7133
} | class ____:
"""Represents an ordinary differential equation (ODE)
This class is used internally in the by dsolve and related
functions/classes so that properties of an ODE can be computed
efficiently.
Examples
========
This class is used internally by dsolve. To instantiate an instance
... | SingleODEProblem |
python | django__django | django/db/models/fields/__init__.py | {
"start": 48710,
"end": 51352
} | class ____:
def check(self, **kwargs):
return [
*super().check(**kwargs),
*self._check_mutually_exclusive_options(),
*self._check_fix_default_value(),
]
def _check_mutually_exclusive_options(self):
# auto_now, auto_now_add, and default are mutually ex... | DateTimeCheckMixin |
python | PrefectHQ__prefect | tests/server/models/test_block_schemas.py | {
"start": 500,
"end": 11579
} | class ____:
async def test_create_block_schema(self, session, block_type_x):
block_schema = await models.block_schemas.create_block_schema(
session=session,
block_schema=schemas.actions.BlockSchemaCreate(
fields={
"title": "x",
... | TestCreateBlockSchema |
python | getsentry__sentry | tests/sentry/hybridcloud/models/test_outbox.py | {
"start": 1840,
"end": 5177
} | class ____(TestCase):
region = Region("eu", 1, "http://eu.testserver", RegionCategory.MULTI_TENANT)
region_config = (region,)
def test_skip_shards(self) -> None:
with self.options({"hybrid_cloud.authentication.disabled_user_shards": [100]}):
assert ControlOutbox(
shard_s... | ControlOutboxTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/types.py | {
"start": 5605,
"end": 6939
} | class ____(_FloatType, sqltypes.DOUBLE[Union[decimal.Decimal, float]]):
"""MySQL DOUBLE type."""
__visit_name__ = "DOUBLE"
def __init__(
self,
precision: Optional[int] = None,
scale: Optional[int] = None,
asdecimal: bool = True,
**kw: Any,
):
"""Construc... | DOUBLE |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_vf2pp.py | {
"start": 4439,
"end": 21961
} | class ____:
def test_custom_graph1_same_labels(self):
G1 = nx.Graph()
mapped = {1: "A", 2: "B", 3: "C", 4: "D", 5: "Z", 6: "E"}
edges1 = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 6), (3, 4), (5, 1), (5, 2)]
G1.add_edges_from(edges1)
G2 = nx.relabel_nodes(G1, mapped)
nx.s... | TestGraphISOVF2pp |
python | spack__spack | lib/spack/spack/container/writers.py | {
"start": 11910,
"end": 12689
} | class ____(PathContext):
"""Context used to instantiate a Singularity definition file"""
#: Name of the template used for Singularity definition files
template_name = "container/singularity.def"
@property
def singularity_config(self):
return self.container_config.get("singularity", {})
... | SingularityContext |
python | falconry__falcon | tests/test_middleware.py | {
"start": 28657,
"end": 29573
} | class ____(TestMiddleware):
@pytest.mark.parametrize('independent_middleware', [True, False])
def test_can_access_resource_params(self, asgi, util, independent_middleware):
"""Test that params can be accessed from within process_resource"""
global context
class Resource:
def... | TestResourceMiddleware |
python | langchain-ai__langchain | libs/core/langchain_core/tracers/base.py | {
"start": 847,
"end": 14311
} | class ____(_TracerCore, BaseCallbackHandler, ABC):
"""Base interface for tracers."""
@abstractmethod
def _persist_run(self, run: Run) -> None:
"""Persist a run."""
def _start_trace(self, run: Run) -> None:
"""Start a trace for a run."""
super()._start_trace(run)
self._o... | BaseTracer |
python | viewflow__viewflow | viewflow/forms/renderers.py | {
"start": 2542,
"end": 2614
} | class ____(WidgetRenderer):
tag = "vf-field-checkbox"
| CheckboxRenderer |
python | h5py__h5py | h5py/tests/test_group.py | {
"start": 7105,
"end": 8186
} | class ____(BaseGroup):
"""
Feature: Objects can be unlinked via "del" operator
"""
def test_delete(self):
""" Object deletion via "del" """
name = make_name()
self.f.create_group(name)
self.assertIn(name, self.f)
del self.f[name]
self.assertNotIn(nam... | TestDelete |
python | scipy__scipy | scipy/signal/tests/test_peak_finding.py | {
"start": 2611,
"end": 4989
} | class ____:
def test_empty(self):
"""Test with empty signal."""
x = np.array([], dtype=np.float64)
for array in _local_maxima_1d(x):
xp_assert_equal(array, np.array([]), check_dtype=False)
assert array.base is None
def test_linear(self):
"""Test with lin... | TestLocalMaxima1d |
python | ZoranPandovski__al-go-rithms | data_structures/Graphs/graphsearch/a-star-search/python/util/node.py | {
"start": 0,
"end": 940
} | class ____:
def __init__(self, id, heuristic, f):
self.id=id
self.heuristic=heuristic
self.totalCost=0
self.f=f
self.parent=None
def setParent(self,parent):
self.parent=parent
def __lt__(self, other):
return self.f < other.f
def __repr__(self):
... | node |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.