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 | pypa__pip | tests/unit/test_req_install.py | {
"start": 1847,
"end": 4503
} | class ____:
def test_install_req_from_string_invalid_requirement(self) -> None:
"""
Requirement strings that cannot be parsed by
packaging.requirements.Requirement raise an InstallationError.
"""
with pytest.raises(InstallationError) as excinfo:
install_req_from_r... | TestInstallRequirementFrom |
python | openai__openai-python | src/openai/types/responses/parsed_response.py | {
"start": 2121,
"end": 2364
} | class ____(ResponseOutputMessage, GenericModel, Generic[ContentType]):
if TYPE_CHECKING:
content: List[ParsedContent[ContentType]] # type: ignore[assignment]
else:
content: List[ParsedContent]
| ParsedResponseOutputMessage |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_flakiness.py | {
"start": 4827,
"end": 6216
} | class ____(Exception):
pass
@composite
def single_bool_lists(draw):
n = draw(integers(0, 20))
result = [False] * (n + 1)
result[n] = True
return result
@xfail_on_crosshair(Why.nested_given)
@example([True, False, False, False], [3], None)
@example([False, True, False, False], [3], None)
@example... | SatisfyMe |
python | geekcomputers__Python | brickout-game/brickout-game.py | {
"start": 5316,
"end": 10210
} | class ____(pygame.sprite.Group):
def __init__(self, screen, x, y, width, height):
self.__screen = screen
self._x = x
self._y = y
self._width = width
self._height = height
self._bricks = []
X = x
Y = y
for i in range(3):
for j in ra... | BrickWall |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image02.py | {
"start": 315,
"end": 898
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | kamyu104__LeetCode-Solutions | Python/search-a-2d-matrix-ii.py | {
"start": 33,
"end": 580
} | class ____(object):
# @param {integer[][]} matrix
# @param {integer} target
# @return {boolean}
def searchMatrix(self, matrix, target):
m = len(matrix)
if m == 0:
return False
n = len(matrix[0])
if n == 0:
return False
i, j = 0, n - 1
... | Solution |
python | pandas-dev__pandas | asv_bench/benchmarks/frame_methods.py | {
"start": 8743,
"end": 9246
} | class ____:
def setup(self):
N = 100_000
data = np.random.randn(N, 2)
mi = MultiIndex.from_arrays(
[
np.arange(N),
date_range("1970-01-01", periods=N, freq="ms"),
]
)
self.df = DataFrame(data)
self.df_mi = DataFr... | ToRecords |
python | apache__airflow | airflow-core/tests/unit/cli/commands/test_config_command.py | {
"start": 22565,
"end": 25292
} | class ____:
@conf_vars({("core", "executor"): "SequentialExecutor"})
def test_update_config_all_options_dry_run(self, tmp_path, monkeypatch, capsys):
cfg_file = tmp_path / "airflow.cfg"
initial_config = "[core]\nexecutor = SequentialExecutor\n"
cfg_file.write_text(initial_config)
... | TestCliConfigUpdate |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 46815,
"end": 48781
} | class ____(TestCase):
"""Tests for ``split_before()``"""
def test_starts_with_sep(self):
actual = list(mi.split_before('xooxoo', lambda c: c == 'x'))
expected = [['x', 'o', 'o'], ['x', 'o', 'o']]
self.assertEqual(actual, expected)
def test_ends_with_sep(self):
actual = list... | SplitBeforeTest |
python | numpy__numpy | numpy/matrixlib/tests/test_defmatrix.py | {
"start": 10101,
"end": 10341
} | class ____:
def test_basic(self):
x = asmatrix(np.zeros((3, 2), float))
y = np.zeros((3, 1), float)
y[:, 0] = [0.8, 0.2, 0.3]
x[:, 1] = y > 0.5
assert_equal(x, [[0, 1], [0, 0], [0, 0]])
| TestIndexing |
python | pydata__xarray | xarray/core/coordinates.py | {
"start": 6049,
"end": 29960
} | class ____(AbstractCoordinates):
"""Dictionary like container for Xarray coordinates (variables + indexes).
This collection is a mapping of coordinate names to
:py:class:`~xarray.DataArray` objects.
It can be passed directly to the :py:class:`~xarray.Dataset` and
:py:class:`~xarray.DataArray` cons... | Coordinates |
python | doocs__leetcode | solution/1100-1199/1105.Filling Bookcase Shelves/Solution.py | {
"start": 0,
"end": 474
} | class ____:
def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
n = len(books)
f = [0] * (n + 1)
for i, (w, h) in enumerate(books, 1):
f[i] = f[i - 1] + h
for j in range(i - 1, 0, -1):
w += books[j - 1][0]
if w >... | Solution |
python | gevent__gevent | src/gevent/_util.py | {
"start": 277,
"end": 5100
} | class ____(object):
"""
A special object you must never pass to any gevent API.
Used as a marker object for keyword arguments that cannot have the
builtin None (because that might be a valid value).
"""
__slots__ = ()
def __repr__(self):
return '<default value>'
_NONE = _NONE()
WR... | _NONE |
python | scipy__scipy | scipy/stats/tests/test_generation/reference_distributions.py | {
"start": 14537,
"end": 14851
} | class ____(ReferenceDistribution):
def __init__(self, *, skew):
super().__init__(skew=skew)
def _pdf(self, x, skew):
b = 2 / skew
a = b**2
c = -b
res = abs(b)/mp.gamma(a) * (b*(x-c))**(a-1) * mp.exp(-b*(x-c))
return res if abs(res.real) == res else 0
| Pearson3 |
python | langchain-ai__langchain | libs/core/langchain_core/outputs/llm_result.py | {
"start": 361,
"end": 3894
} | class ____(BaseModel):
"""A container for results of an LLM call.
Both chat models and LLMs generate an LLMResult object. This object contains the
generated outputs and any additional information that the model provider wants to
return.
"""
generations: list[
list[Generation | ChatGene... | LLMResult |
python | imageio__imageio | imageio/plugins/example.py | {
"start": 238,
"end": 5499
} | class ____(Format):
"""The dummy format is an example format that does nothing.
It will never indicate that it can read or write a file. When
explicitly asked to read, it will simply read the bytes. When
explicitly asked to write, it will raise an error.
This documentation is shown when the user do... | DummyFormat |
python | django__django | tests/string_lookup/models.py | {
"start": 482,
"end": 612
} | class ____(models.Model):
parent = models.OneToOneField("Base", models.CASCADE)
name = models.CharField(max_length=50)
| Child |
python | apache__airflow | providers/common/sql/src/airflow/providers/common/sql/operators/sql.py | {
"start": 4024,
"end": 7086
} | class ____(BaseOperator):
"""
This is a base class for generic SQL Operator to get a DB Hook.
The provided method is .get_db_hook(). The default behavior will try to
retrieve the DB hook based on connection type.
You can customize the behavior by overriding the .get_db_hook() method.
:param co... | BaseSQLOperator |
python | apache__airflow | providers/standard/src/airflow/providers/standard/operators/python.py | {
"start": 23845,
"end": 40617
} | class ____(_BasePythonVirtualenvOperator):
"""
Run a function in a virtualenv that is created and destroyed automatically.
The function (has certain caveats) must be defined using def, and not be
part of a class. All imports must happen inside the function
and no variables outside the scope may be ... | PythonVirtualenvOperator |
python | getsentry__sentry | src/sentry/feedback/migrations/0005_feedback_fk_not_db_contstr.py | {
"start": 348,
"end": 2028
} | 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 | PyCQA__pyflakes | pyflakes/test/test_undefined_names.py | {
"start": 107,
"end": 23099
} | class ____(TestCase):
def test_undefined(self):
self.flakes('bar', m.UndefinedName)
def test_definedInListComp(self):
self.flakes('[a for a in range(10) if a]')
def test_undefinedInListComp(self):
self.flakes('''
[a for a in range(10)]
a
''',
... | Test |
python | run-llama__llama_index | llama-index-core/llama_index/core/retrievers/recursive_retriever.py | {
"start": 620,
"end": 8314
} | class ____(BaseRetriever):
"""
Recursive retriever.
This retriever will recursively explore links from nodes to other
retrievers/query engines.
For any retrieved nodes, if any of the nodes are IndexNodes,
then it will explore the linked retriever/query engine, and query that.
Args:
... | RecursiveRetriever |
python | django-haystack__django-haystack | test_haystack/elasticsearch_tests/test_elasticsearch_backend.py | {
"start": 7561,
"end": 7997
} | class ____(UnifiedIndex):
spy_args = None
def get_index(self, model_klass):
if self.spy_args is not None:
self.spy_args.setdefault("get_index", []).append(model_klass)
return super().get_index(model_klass)
@contextmanager
def spy(self):
try:
self.spy_arg... | ElasticSearchMockUnifiedIndex |
python | ray-project__ray | python/ray/tests/spark/test_databricks_hook.py | {
"start": 735,
"end": 2946
} | class ____:
@classmethod
def setup_class(cls):
os.environ["SPARK_WORKER_CORES"] = "2"
cls.spark = (
SparkSession.builder.master("local-cluster[1, 2, 1024]")
.config("spark.task.cpus", "1")
.config("spark.task.maxFailures", "1")
.config("spark.execu... | TestDatabricksHook |
python | apache__airflow | shared/logging/src/airflow_shared/logging/structlog.py | {
"start": 5651,
"end": 5941
} | class ____(structlog.BytesLogger):
__slots__ = ("name",)
def __init__(self, name: str | None = None, file: BinaryIO | None = None):
self.name = name
if file is not None:
file = make_file_io_non_caching(file)
super().__init__(file)
| NamedBytesLogger |
python | getsentry__sentry | src/sentry/dynamic_sampling/models/base.py | {
"start": 119,
"end": 276
} | class ____(ABC):
@abstractmethod
def validate(self) -> bool:
# By default, we want each model value to be valid.
return True
| ModelInput |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 20516,
"end": 23254
} | class ____(Widget, Generic[T]):
"""A representation of button_group that is used by ``st.feedback``."""
_value: list[T] | None
proto: ButtonGroupProto = field(repr=False)
options: list[ButtonGroupProto.Option]
form_id: str
def __init__(self, proto: ButtonGroupProto, root: ElementTree) -> None... | ButtonGroup |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/common.py | {
"start": 1724,
"end": 1912
} | class ____(StrictBaseModel, Generic[T]):
"""Base class for bulk actions."""
action: BulkAction = Field(..., description="The action to be performed on the entities.")
| BulkBaseAction |
python | joke2k__faker | faker/providers/automotive/nl_BE/__init__.py | {
"start": 48,
"end": 372
} | class ____(AutomotiveProvider):
"""Implement automotive provider for `nl_BE` locale.
https://nl.wikipedia.org/wiki/Belgisch_kenteken
"""
license_formats = (
"???-###", # 1973-2008
"###-???", # 2008-2010
# New formats after 2010
"1-???-###",
"2-???-###",
)
| Provider |
python | getsentry__sentry | tests/sentry/middleware/integrations/parsers/test_github.py | {
"start": 12580,
"end": 16924
} | class ____(TestCase):
factory = RequestFactory()
path = reverse("sentry-integration-github-webhook")
@pytest.fixture(autouse=True)
def setup(self):
with override_options({"github.webhook-type-routing.enabled": True}):
yield
def setUp(self) -> None:
super().setUp()
... | GithubRequestParserOverwatchForwarderTest |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-hwp/llama_index/readers/hwp/base.py | {
"start": 197,
"end": 3196
} | class ____(BaseReader):
"""
Hwp Reader. Reads contents from Hwp file.
Args: None.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.FILE_HEADER_SECTION = "FileHeader"
self.HWP_SUMMARY_SECTION = "\x05HwpSummaryInformation"
... | HWPReader |
python | kubernetes-client__python | kubernetes/client/models/v1_resource_attributes.py | {
"start": 383,
"end": 11116
} | 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... | V1ResourceAttributes |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/init_ops_test.py | {
"start": 14176,
"end": 16437
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testTruncatedNormalDistribution(self):
shape = [100, 100]
expect_mean = 0.
expect_var = 1. / shape[0]
init = init_ops.variance_scaling_initializer(
distribution="truncated_normal")
with self.session(), \
test.mock.patch.... | VarianceScalingInitializationTest |
python | ansible__ansible | test/lib/ansible_test/_internal/coverage_util.py | {
"start": 922,
"end": 1489
} | class ____:
"""Details about a coverage version and its supported Python versions."""
coverage_version: str
schema_version: int
min_python: tuple[int, int]
max_python: tuple[int, int]
COVERAGE_VERSIONS = (
# IMPORTANT: Keep this in sync with the ansible-test.txt requirements file.
Coverag... | CoverageVersion |
python | ApeWorX__ape | tests/conftest.py | {
"start": 12969,
"end": 14151
} | class ____:
"""
Same CLI commands are better tested using a python subprocess,
such as `ape test` commands because duplicate pytest main methods
do not run well together, or `ape plugins` commands, which may
modify installed plugins.
"""
def __init__(
self, root_cmd: Optional[Sequen... | SubprocessRunner |
python | kamyu104__LeetCode-Solutions | Python/find-the-divisibility-array-of-a-string.py | {
"start": 42,
"end": 376
} | class ____(object):
def divisibilityArray(self, word, m):
"""
:type word: str
:type m: int
:rtype: List[int]
"""
result = []
curr = 0
for c in word:
curr = (curr*10+(ord(c)-ord('0')))%m
result.append(int(curr == 0))
retu... | Solution |
python | lepture__authlib | authlib/jose/rfc8037/jws_eddsa.py | {
"start": 119,
"end": 717
} | class ____(JWSAlgorithm):
name = "EdDSA"
description = "Edwards-curve Digital Signature Algorithm for JWS"
def prepare_key(self, raw_data):
return OKPKey.import_key(raw_data)
def sign(self, msg, key):
op_key = key.get_op_key("sign")
return op_key.sign(msg)
def verify(self,... | EdDSAAlgorithm |
python | rq__rq | tests/test_queue.py | {
"start": 37146,
"end": 37652
} | class ____(RQTestCase):
def test_enqueue_at(self):
"""enqueue_at() creates a job in ScheduledJobRegistry"""
queue = Queue(connection=self.connection)
scheduled_time = datetime.now(timezone.utc) + timedelta(seconds=10)
job = queue.enqueue_at(scheduled_time, say_hello)
registry... | TestJobScheduling |
python | jina-ai__jina | tests/helper.py | {
"start": 114,
"end": 1162
} | class ____(Executor):
@requests(on='/')
def process(self, docs: DocumentArray, **kwargs):
for doc in docs:
doc.text = doc.text + 'world'
doc.tags['processed'] = True
def _validate_dummy_custom_gateway_response(port, expected):
import requests
resp = requests.get(f'http... | ProcessExecutor |
python | wandb__wandb | wandb/integration/metaflow/metaflow.py | {
"start": 790,
"end": 9411
} | class ____:
def __init__(self, flow):
# do this to avoid recursion problem with __setattr__
self.__dict__.update(
{
"flow": flow,
"inputs": {},
"outputs": {},
"base": set(dir(flow)),
"params": {p: getattr(flo... | ArtifactProxy |
python | weaviate__weaviate-python-client | weaviate/auth.py | {
"start": 202,
"end": 971
} | class ____:
"""Authenticate for the Client Credential flow using client secrets.
Acquire the client secret from your identify provider and set the appropriate scope. The client includes hardcoded
scopes for Azure, otherwise it needs to be supplied.
Scopes can be given as:
- List of strings: ["sco... | _ClientCredentials |
python | django__django | django/test/client.py | {
"start": 7211,
"end": 13120
} | class ____(BaseHandler):
"""An async version of ClientHandler."""
def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
self.enforce_csrf_checks = enforce_csrf_checks
super().__init__(*args, **kwargs)
async def __call__(self, scope):
# Set up middleware if needed. We could... | AsyncClientHandler |
python | scipy__scipy | scipy/ndimage/tests/test_morphology.py | {
"start": 132710,
"end": 137867
} | class ____:
def _setup(self, xp):
a = np.zeros((5, 5), dtype=bool)
a[1:4, 1:4] = True
a[4, 4] = True
self.array = xp.asarray(a)
self.sq3x3 = xp.ones((3, 3))
self.opened_old = ndimage.binary_opening(self.array, self.sq3x3,
... | TestBinaryOpeningClosing |
python | huggingface__transformers | src/transformers/models/deberta/modeling_deberta.py | {
"start": 25467,
"end": 29427
} | class ____(DebertaPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.embeddings = DebertaEmbeddings(config)
self.encoder = DebertaEncoder(config)
self.z_steps = 0
self.config = config
# Initialize weights and apply final processing
se... | DebertaModel |
python | davidhalter__jedi | test/static_analysis/class_simple.py | {
"start": 78,
"end": 152
} | class ____(Base.Nested):
pass
X().foo()
#! 4 attribute-error
X().bar()
| X |
python | getsentry__sentry | src/sentry/rules/conditions/event_attribute.py | {
"start": 7448,
"end": 7708
} | class ____(AttributeHandler):
minimum_path_length = 1
@classmethod
def _handle(cls, path: list[str], event: GroupEvent) -> list[str]:
return [str(event.get_tag("environment"))]
@attribute_registry.register("type")
| EnvironmentAttributeHandler |
python | gevent__gevent | src/greentest/3.10/test_ftplib.py | {
"start": 39285,
"end": 42464
} | class ____(TestCase):
def setUp(self):
self.evt = threading.Event()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(20)
self.port = socket_helper.bind_port(self.sock)
self.server_thread = threading.Thread(target=self.server)
self.se... | TestTimeouts |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_data_validation08.py | {
"start": 315,
"end": 1033
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("data_validation08.xlsx")
def test_create_file(self):
"""Test the creation of a XlsxWriter file with data validation."""
workbook =... | TestCompareXLSXFiles |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-make-all-array-elements-equal.py | {
"start": 75,
"end": 612
} | class ____(object):
def minOperations(self, nums, queries):
"""
:type nums: List[int]
:type queries: List[int]
:rtype: List[int]
"""
nums.sort()
prefix = [0]*(len(nums)+1)
for i in xrange(len(nums)):
prefix[i+1] = prefix[i]+nums[i]
... | Solution |
python | python-visualization__folium | folium/features.py | {
"start": 67559,
"end": 68991
} | class ____(MacroElement):
"""
When one clicks on a Map that contains a ClickForLatLng,
the coordinates of the pointer's position are copied to clipboard.
Parameters
==========
format_str : str, default 'lat + "," + lng'
The javascript string used to format the text copied to clipboard.
... | ClickForLatLng |
python | getsentry__sentry | src/sentry/sentry_metrics/indexer/postgres/models.py | {
"start": 1032,
"end": 1362
} | class ____(BaseIndexer):
__relocation_scope__ = RelocationScope.Excluded
class Meta:
db_table = "sentry_stringindexer"
app_label = "sentry"
constraints = [
models.UniqueConstraint(fields=["string", "organization_id"], name="unique_org_string"),
]
@region_silo_model... | StringIndexer |
python | apache__airflow | task-sdk/src/airflow/sdk/api/client.py | {
"start": 27298,
"end": 29374
} | class ____:
"""
Operations related to Human in the loop. Require Airflow 3.1+.
:meta: private
"""
__slots__ = ("client",)
def __init__(self, client: Client) -> None:
self.client = client
def add_response(
self,
*,
ti_id: uuid.UUID,
options: list[st... | HITLOperations |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 39174,
"end": 43436
} | class ____(Source):
def name(self) -> str:
return ""
def guard_source(self) -> GuardSource:
return GuardSource.BACKWARD_STATE
def get_local_source_name(
source: Source, *, only_allow_input: bool = False
) -> Optional[str]:
if isinstance(source, ChainedSource):
return get_local... | BackwardStateSource |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/core_tests/host_representation_tests/test_repo_handle.py | {
"start": 457,
"end": 2007
} | class ____(InProcessCodeLocation):
@property
def repository_code_pointer_dict(self) -> Mapping[str, Optional[CodePointer]]:
return {}
@dg.asset
def my_asset():
pass
defs = dg.Definitions(assets=[my_asset])
def test_repo_handle_without_code_pointers():
origin = InProcessCodeLocationOrigin(
... | InProcesssCodeLocationWithoutCodePointers |
python | pytorch__pytorch | torch/jit/quantized.py | {
"start": 1169,
"end": 1463
} | class ____(QuantizedRNNCellBase):
def __init__(self, other):
super().__init__(other)
raise RuntimeError(
"torch.jit.QuantizedLSTMCell is no longer supported. "
"Please use the torch.ao.nn.quantized.dynamic.LSTMCell instead."
)
| QuantizedLSTMCell |
python | huggingface__transformers | src/transformers/models/convbert/modeling_convbert.py | {
"start": 13399,
"end": 14344
} | class ____(nn.Module):
def __init__(self, input_size, output_size, num_groups):
super().__init__()
self.input_size = input_size
self.output_size = output_size
self.num_groups = num_groups
self.group_in_dim = self.input_size // self.num_groups
self.group_out_dim = self... | GroupedLinearLayer |
python | kamyu104__LeetCode-Solutions | Python/check-if-the-rectangle-corner-is-reachable.py | {
"start": 2531,
"end": 3969
} | class ____(object):
def canReachCorner(self, X, Y, circles):
"""
:type X: int
:type Y: int
:type circles: List[List[int]]
:rtype: bool
"""
def check(x1, y1, r1, x2, y2, r2):
return (x1-x2)**2+(y1-y2)**2 <= (r1+r2)**2
def iter_dfs(src, dst)... | Solution3 |
python | django__django | tests/servers/tests.py | {
"start": 1598,
"end": 1850
} | class ____(LiveServerThread):
server_class = CloseConnectionTestServer
def _create_server(self, connections_override=None):
return super()._create_server(connections_override=self.connections_override)
| CloseConnectionTestLiveServerThread |
python | simplejson__simplejson | simplejson/tests/test_item_sort_key.py | {
"start": 90,
"end": 1376
} | class ____(TestCase):
def test_simple_first(self):
a = {'a': 1, 'c': 5, 'jack': 'jill', 'pick': 'axe', 'array': [1, 5, 6, 9], 'tuple': (83, 12, 3), 'crate': 'dog', 'zeak': 'oh'}
self.assertEqual(
'{"a": 1, "c": 5, "crate": "dog", "jack": "jill", "pick": "axe", "zeak": "oh", "array": [1, ... | TestItemSortKey |
python | tiangolo__fastapi | docs_src/extra_models/tutorial003.py | {
"start": 217,
"end": 644
} | class ____(BaseItem):
type: str = "plane"
size: int
items = {
"item1": {"description": "All my friends drive a low rider", "type": "car"},
"item2": {
"description": "Music is my aeroplane, it's my aeroplane",
"type": "plane",
"size": 5,
},
}
@app.get("/items/{item_id}", r... | PlaneItem |
python | pytorch__pytorch | test/torch_np/numpy_tests/linalg/test_linalg.py | {
"start": 10256,
"end": 11056
} | class ____:
TEST_CASES = CASES
def check_cases(self, require=None, exclude=None):
"""
Run func on each of the cases with all of the tags in require, and none
of the tags in exclude
"""
if require is None:
require = set()
if exclude is None:
... | LinalgTestCase |
python | readthedocs__readthedocs.org | readthedocs/filetreediff/dataclasses.py | {
"start": 477,
"end": 618
} | class ____:
"""A file in a file tree manifest."""
path: str
main_content_hash: str
@dataclass(slots=True)
| FileTreeDiffManifestFile |
python | getsentry__sentry | tests/sentry/auth_v2/endpoints/test_auth_merge_user_accounts.py | {
"start": 324,
"end": 1949
} | class ____(APITestCase):
endpoint = "sentry-api-0-auth-merge-accounts"
method = "get"
def test_simple(self) -> None:
user1 = self.create_user(username="mifu1", email="mifu@example.com")
user2 = self.create_user(username="mifu2", email="mifu@example.com")
# unrelated user
sel... | ListUserAccountsWithSharedEmailTest |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 68245,
"end": 68440
} | class ____(BaseModel, extra="forbid"):
"""
Exact match on any of the given values
"""
any: "AnyVariants" = Field(..., description="Exact match on any of the given values")
| MatchAny |
python | psf__requests | src/requests/auth.py | {
"start": 2851,
"end": 3095
} | class ____(HTTPBasicAuth):
"""Attaches HTTP Proxy Authentication to a given Request object."""
def __call__(self, r):
r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password)
return r
| HTTPProxyAuth |
python | getsentry__sentry | src/sentry/search/eap/trace_metrics/config.py | {
"start": 658,
"end": 789
} | class ____:
metric_name: str
metric_type: MetricType
metric_unit: str | None
@dataclass(frozen=True, kw_only=True)
| Metric |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 34684,
"end": 36105
} | class ____(RoleImpl):
__slots__ = ()
_skip_clauseelement_for_target_match = True
def _literal_coercion(self, element, *, argname=None, **kw):
self._raise_for_expected(element, argname)
def _implicit_coercions(
self,
element: Any,
resolved: Any,
argname: Optiona... | JoinTargetImpl |
python | pandas-dev__pandas | asv_bench/benchmarks/tslibs/timestamp.py | {
"start": 1263,
"end": 2451
} | class ____:
params = [_tzs]
param_names = ["tz"]
def setup(self, tz):
self.ts = Timestamp("2017-08-25 08:16:14", tzinfo=tz)
def time_tz(self, tz):
self.ts.tz
def time_dayofweek(self, tz):
self.ts.dayofweek
def time_dayofyear(self, tz):
self.ts.dayofyear
d... | TimestampProperties |
python | openai__openai-python | src/openai/types/beta/threads/message_list_params.py | {
"start": 207,
"end": 1296
} | class ____(TypedDict, total=False):
after: str
"""A cursor for use in pagination.
`after` is an object ID that defines your place in the list. For instance, if
you make a list request and receive 100 objects, ending with obj_foo, your
subsequent call can include after=obj_foo in order to fetch the ... | MessageListParams |
python | openai__openai-python | src/openai/types/responses/response_output_text_param.py | {
"start": 2002,
"end": 2428
} | class ____(TypedDict, total=False):
file_id: Required[str]
"""The ID of the file."""
index: Required[int]
"""The index of the file in the list of files."""
type: Required[Literal["file_path"]]
"""The type of the file path. Always `file_path`."""
Annotation: TypeAlias = Union[
AnnotationF... | AnnotationFilePath |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_core/test_worker.py | {
"start": 48338,
"end": 55739
} | class ____:
"""Tests worker service account."""
def test_should_add_component_specific_labels(self):
docs = render_chart(
values={
"executor": "CeleryExecutor",
"workers": {
"serviceAccount": {"create": True},
"labels":... | TestWorkerServiceAccount |
python | getsentry__sentry | src/sentry/api/serializers/models/orgauthtoken.py | {
"start": 134,
"end": 750
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
token = kwargs["token"]
data = {
"id": str(obj.id),
"name": obj.name,
"scopes": obj.get_scopes(),
"tokenLastCharacters": obj.token_last_characters,
"dateCreated": obj.... | OrgAuthTokenSerializer |
python | huggingface__transformers | src/transformers/models/dpt/modeling_dpt.py | {
"start": 36564,
"end": 38216
} | class ____(nn.Module):
"""
Output head consisting of 3 convolutional layers. It progressively halves the feature dimension and upsamples
the predictions to the input resolution after the first convolutional layer (details can be found in the paper's
supplementary material).
"""
def __init__(sel... | DPTDepthEstimationHead |
python | huggingface__transformers | src/transformers/models/deepseek_v2/modular_deepseek_v2.py | {
"start": 20731,
"end": 21285
} | class ____(LlamaDecoderLayer):
def __init__(self, config: DeepseekV2Config, layer_idx: int):
super().__init__(config, layer_idx)
self.self_attn = DeepseekV2Attention(config=config, layer_idx=layer_idx)
self.mlp = DeepseekV2Moe(config) if layer_idx >= config.first_k_dense_replace else Deepse... | DeepseekV2DecoderLayer |
python | tiangolo__fastapi | tests/test_skip_defaults.py | {
"start": 279,
"end": 363
} | class ____(Model):
y: int
z: int = 0
w: Optional[int] = None
| ModelSubclass |
python | django__django | tests/one_to_one/models.py | {
"start": 1485,
"end": 1630
} | class ____(models.Model):
link = models.OneToOneField(ManualPrimaryKey, models.CASCADE)
name = models.CharField(max_length=50)
| RelatedModel |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dlp.py | {
"start": 111851,
"end": 115598
} | class ____(GoogleCloudBaseOperator):
"""
Updates a job trigger.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDLPUpdateJobTriggerOperator`
:param job_trigger_id: The ID of the DLP job trigger to be updated.
:param... | CloudDLPUpdateJobTriggerOperator |
python | django-import-export__django-import-export | tests/core/tests/test_fields.py | {
"start": 259,
"end": 363
} | class ____:
def __init__(self, name, date=None):
self.name = name
self.date = date
| Obj |
python | scrapy__scrapy | tests/test_http2_client_protocol.py | {
"start": 4634,
"end": 4747
} | class ____(LeafResource):
def render_GET(self, request: TxRequest):
return NOT_DONE_YET
| TimeoutResponse |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 47571,
"end": 47720
} | class ____(Elemwise):
_parameters = ["frame", "left", "right", "inclusive"]
_defaults = {"inclusive": "both"}
operation = M.between
| Between |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 21235,
"end": 21876
} | class ____(WrapperLine):
wrapper: PythonWrapperCodegen
kernel_name: str
kernel_body: str
metadata: Optional[str] = None
gpu: bool = True
cpp_definition: Optional[str] = None
def codegen(self, code: IndentedBuffer) -> None:
self.wrapper._define_kernel_helper(
self.kernel_... | KernelDefinitionLine |
python | scikit-image__scikit-image | src/skimage/measure/fit.py | {
"start": 22667,
"end": 51300
} | class ____(_BaseModel):
"""Total least squares estimator for 2D ellipses.
The functional model of the ellipse is::
xt = xc + a*cos(theta)*cos(t) - b*sin(theta)*sin(t)
yt = yc + a*sin(theta)*cos(t) + b*cos(theta)*sin(t)
d = sqrt((x - xt)**2 + (y - yt)**2)
where ``(xt, yt)`` is the ... | EllipseModel |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/depends_on_manyvariants/package.py | {
"start": 217,
"end": 634
} | class ____(Package):
"""
A package with a dependency on `manyvariants`, so that `manyvariants` can
be spliced in tests.
"""
homepage = "https://www.test.com"
has_code = False
version("1.0")
version("2.0")
depends_on("manyvariants@1.0", when="@1.0")
depends_on("manyvariants@2.0... | DependsOnManyvariants |
python | pytorch__pytorch | torch/__init__.py | {
"start": 21775,
"end": 25881
} | class ____:
"""
Like a float (including magic methods), but redirects all operations on the
wrapped node. This is used in particular to symbolically record operations
in the symbolic shape workflow.
"""
def __init__(self, node):
# This field MUST be named node; C++ binding code assumes ... | SymFloat |
python | readthedocs__readthedocs.org | readthedocs/integrations/models.py | {
"start": 9677,
"end": 11511
} | class ____(TimeStampedModel):
"""Inbound webhook integration for projects."""
GITHUBAPP = "githubapp"
GITHUB_WEBHOOK = "github_webhook"
BITBUCKET_WEBHOOK = "bitbucket_webhook"
GITLAB_WEBHOOK = "gitlab_webhook"
API_WEBHOOK = "api_webhook"
WEBHOOK_INTEGRATIONS = (
(GITHUB_WEBHOOK, _(... | Integration |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax.py | {
"start": 1602,
"end": 1662
} | class ____:
my_var: int | str
@dataclass()
| CustomDataClass2 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/dependency.py | {
"start": 10081,
"end": 12040
} | class ____(Node):
definition: "OpDefinition" # pyright: ignore[reportIncompatibleVariableOverride]
def __init__(
self,
name: str,
definition: "OpDefinition",
graph_definition: "GraphDefinition",
tags: Optional[Mapping[str, str]] = None,
hook_defs: Optional[Abstr... | OpNode |
python | jazzband__django-oauth-toolkit | tests/test_hybrid.py | {
"start": 4927,
"end": 31591
} | class ____(BaseTest):
def test_skip_authorization_completely(self):
"""
If application.skip_authorization = True, should skip the authorization page.
"""
self.client.login(username="hy_test_user", password="123456")
self.application.skip_authorization = True
self.appl... | TestHybridView |
python | ray-project__ray | doc/source/serve/doc_code/varying_deps.py | {
"start": 144,
"end": 1106
} | class ____:
def __init__(
self, ver_25_handle: DeploymentHandle, ver_26_handle: DeploymentHandle
):
self.ver_25_handle = ver_25_handle
self.ver_26_handle = ver_26_handle
async def __call__(self, request: Request):
if request.query_params["version"] == "25":
retur... | Ingress |
python | ansible__ansible | test/lib/ansible_test/_internal/ci/azp.py | {
"start": 5240,
"end": 11006
} | class ____:
"""Change information for an Azure Pipelines build."""
def __init__(self, args: CommonConfig) -> None:
self.args = args
self.git = Git()
try:
self.org_uri = os.environ['SYSTEM_COLLECTIONURI'] # ex: https://dev.azure.com/{org}/
self.project = os.envi... | AzurePipelinesChanges |
python | encode__django-rest-framework | tests/models.py | {
"start": 1865,
"end": 2191
} | class ____(RESTFrameworkModel):
target = models.ForeignKey(ForeignKeyTarget, help_text='Target',
verbose_name='Target',
limit_choices_to={"name__startswith": "limited-"},
on_delete=models.CASCADE)
| ForeignKeySourceWithLimitedChoices |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/field_utils.py | {
"start": 7492,
"end": 9028
} | class ____(_ConfigHasFields):
"""Defines a config dict with a partially specified schema.
A permissive dict allows partial specification of the config schema. Any fields with a
specified schema will be type checked. Other fields will be allowed, but will be ignored by
the type checker.
Args:
... | Permissive |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 33108,
"end": 33940
} | class ____:
subpath = ('__init__.py',)
traversed = None
environ = {'REQUEST_METHOD': 'GET', 'wsgi.version': (1, 0)}
def get_response(self, application):
return application(None, None)
def httpdate(ts):
return ts.strftime("%a, %d %b %Y %H:%M:%S GMT")
def read_(filename):
with open(fi... | DummyRequest |
python | PyCQA__pylint | tests/functional/b/broad_exception/broad_exception_caught_trystar.py | {
"start": 104,
"end": 607
} | class ____(CustomBroadException):
pass
try:
__revision__ += 1
except* Exception: # [broad-exception-caught]
print('error')
try:
__revision__ += 1
except* BaseException: # [broad-exception-caught]
print('error')
try:
__revision__ += 1
except* ValueError:
print('error')
try:
__revi... | CustomNarrowException |
python | pezy__LeetCode | 103. Maximum Depth of Binary Tree/solution.py | {
"start": 128,
"end": 739
} | class ____:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
... | Solution |
python | pikepdf__pikepdf | src/pikepdf/canvas.py | {
"start": 27621,
"end": 27791
} | class ____:
"""Loaded image.
This class is used to track images that have been loaded into a
canvas.
"""
name: Name
image: Image.Image
| LoadedImage |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_with_poly.py | {
"start": 5382,
"end": 5482
} | class ____(
_WithPolymorphicBase, _PolymorphicAliasedJoins
):
pass
| PolymorphicAliasedJoinsTest |
python | allegroai__clearml | clearml/backend_api/services/v2_9/queues.py | {
"start": 63235,
"end": 64417
} | class ____(Response):
"""
Response of queues.remove_task endpoint.
:param removed: Number of tasks removed (0 or 1)
:type removed: int
"""
_service = "queues"
_action = "remove_task"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {
"remove... | RemoveTaskResponse |
python | ansible__ansible | test/integration/targets/ansible-test-sanity-pylint/ansible_collections/ns/col/plugins/lookup/deprecated.py | {
"start": 1336,
"end": 1417
} | class ____(LookupBase):
def run(self, **kwargs):
return []
| LookupModule |
python | getsentry__sentry | tests/sentry/issues/test_ingest.py | {
"start": 35980,
"end": 36904
} | class ____(OccurrenceTestMixin, TestCase):
def test(self) -> None:
culprit = "abcde" * 100
occurrence = self.build_occurrence(culprit=culprit)
event = self.store_event(data={}, project_id=self.project.id)
assert _create_issue_kwargs(occurrence, event, None) == {
"platform... | CreateIssueKwargsTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.