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 | doocs__leetcode | solution/2200-2299/2220.Minimum Bit Flips to Convert Number/Solution.py | {
"start": 0,
"end": 115
} | class ____:
def minBitFlips(self, start: int, goal: int) -> int:
return (start ^ goal).bit_count()
| Solution |
python | streamlit__streamlit | lib/streamlit/components/v1/component_registry.py | {
"start": 5532,
"end": 5741
} | class ____:
@classmethod
def instance(cls) -> BaseComponentRegistry:
"""Returns the ComponentRegistry of the runtime instance."""
return get_instance().component_registry
| ComponentRegistry |
python | realpython__materials | asterioids-pygame-project/source_code_step_6/space_rocks/game.py | {
"start": 106,
"end": 2371
} | class ____:
MIN_ASTEROID_DISTANCE = 250
def __init__(self):
self._init_pygame()
self.screen = pygame.display.set_mode((800, 600))
self.background = load_sprite("space", False)
self.clock = pygame.time.Clock()
self.asteroids = []
self.spaceship = Spaceship((400, ... | SpaceRocks |
python | pandas-dev__pandas | pandas/tests/libs/test_hashtable.py | {
"start": 8930,
"end": 13849
} | class ____:
# TODO: moved from test_algos; may be redundancies with other tests
def test_string_hashtable_set_item_signature(self):
# GH#30419 fix typing in StringHashTable.set_item to prevent segfault
tbl = ht.StringHashTable()
tbl.set_item("key", 1)
assert tbl.get_item("key") ... | TestHashTableUnsorted |
python | ZoranPandovski__al-go-rithms | sort/python/external-sort.py | {
"start": 2842,
"end": 4338
} | class ____(object):
def __init__(self, block_size):
self.block_size = block_size
def sort(self, filename, sort_key=None):
num_blocks = self.get_number_blocks(filename, self.block_size)
splitter = FileSplitter(filename)
splitter.split(self.block_size, sort_key)
merger = ... | ExternalSort |
python | pytorch__pytorch | torch/csrc/lazy/test_mnist.py | {
"start": 329,
"end": 2721
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear... | Net |
python | joke2k__faker | faker/providers/company/vi_VN/__init__.py | {
"start": 45,
"end": 733
} | class ____(CompanyProvider):
# Source: https://vi.wikipedia.org/wiki/Danh_s%C3%A1ch_c%C3%B4ng_ty_Vi%E1%BB%87t_Nam
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{last_name}} và {{last_name}} {{company_suffix}}",
"{{last_name}} ... | Provider |
python | airbytehq__airbyte | airbyte-ci/connectors/live-tests/src/live_tests/commons/json_schema_helper.py | {
"start": 1895,
"end": 2212
} | class ____(Enum):
NULL = 0
BOOLEAN = 1
INTEGER = 2
NUMBER = 3
STRING = 4
OBJECT = 5
def __lt__(self, other: Any) -> bool:
if self.__class__ is other.__class__:
return self.value < other.value # type: ignore
else:
return NotImplemented
| ComparableType |
python | wandb__wandb | wandb/sdk/wandb_require.py | {
"start": 424,
"end": 2713
} | class ____:
"""Internal feature class."""
_features: tuple[str, ...]
def __init__(self, features: str | Iterable[str]) -> None:
self._features = (
tuple([features]) if isinstance(features, str) else tuple(features)
)
def require_require(self) -> None:
pass
def... | _Requires |
python | kamyu104__LeetCode-Solutions | Python/maximum-length-of-pair-chain.py | {
"start": 33,
"end": 394
} | class ____(object):
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
pairs.sort(key=lambda x: x[1])
cnt, i = 0, 0
for j in xrange(len(pairs)):
if j == 0 or pairs[i][1] < pairs[j][0]:
cnt += 1
... | Solution |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/combine_documents/stuff.py | {
"start": 4342,
"end": 11579
} | class ____(BaseCombineDocumentsChain):
"""Chain that combines documents by stuffing into context.
This chain takes a list of documents and first combines them into a single string.
It does this by formatting each document into a string with the `document_prompt`
and then joining them together with `doc... | StuffDocumentsChain |
python | django__django | tests/model_fields/test_slugfield.py | {
"start": 79,
"end": 636
} | class ____(TestCase):
def test_slugfield_max_length(self):
"""
SlugField honors max_length.
"""
bs = BigS.objects.create(s="slug" * 50)
bs = BigS.objects.get(pk=bs.pk)
self.assertEqual(bs.s, "slug" * 50)
def test_slugfield_unicode_max_length(self):
"""
... | SlugFieldTests |
python | getsentry__sentry | tests/sentry/grouping/seer_similarity/test_seer_eligibility.py | {
"start": 12344,
"end": 14705
} | class ____(TestCase):
def get_eligible_event_data(self) -> dict[str, Any]:
return {
"title": "FailedToFetchError('Charlie didn't bring the ball back')",
"exception": {
"values": [
{
"type": "FailedToFetchError",
... | EventContentIsSeerEligibleTest |
python | tensorflow__tensorflow | tensorflow/python/autograph/utils/tensor_list.py | {
"start": 1563,
"end": 2336
} | class ____(object):
"""Tensor list wrapper API-compatible with Python built-in list."""
def __init__(self, shape, dtype):
self.dtype = dtype
self.shape = shape
self.clear()
def append(self, value):
self.list_ = list_ops.tensor_list_push_back(self.list_, value)
def pop(self):
self.list_, v... | TensorList |
python | python__mypy | test-data/unit/plugins/badreturn2.py | {
"start": 37,
"end": 128
} | class ____:
pass
def plugin(version: str) -> type[MyPlugin]:
return MyPlugin
| MyPlugin |
python | jupyterlab__jupyterlab | packages/services/examples/browser-require/main.py | {
"start": 516,
"end": 1375
} | class ____(ExtensionHandlerJinjaMixin, ExtensionHandlerMixin, JupyterHandler):
"""Handle requests between the main app page and notebook server."""
def get(self):
"""Get the main page for the application's interface."""
config_data = {
# Use camelCase here, since that's what the lab... | ExampleHandler |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 7620,
"end": 8290
} | class ____(FunctionPass):
_name = "generic_rewrites"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
Perform any intermediate representation rewrites before type
inference.
"""
assert state.func_ir
msg = ('Internal erro... | GenericRewrites |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-ollama/tests/test_llms_ollama.py | {
"start": 886,
"end": 13656
} | class ____(BaseModel):
"""A song with name and artist."""
artist_name: str = Field(description="The name of the artist")
song_name: str = Field(description="The name of the song")
def generate_song(
artist_name: Annotated[str, "The name of the artist"],
song_name: Annotated[str, "The name of the ... | Song |
python | apache__avro | lang/py/avro/test/test_protocol.py | {
"start": 1374,
"end": 1515
} | class ____(TestProtocol):
"""A proxy for a valid protocol string that provides useful test metadata."""
valid = True
| ValidTestProtocol |
python | pypa__setuptools | setuptools/_distutils/command/build_py.py | {
"start": 318,
"end": 16696
} | class ____(Command):
description = "\"build\" pure Python modules (copy to build directory)"
user_options = [
('build-lib=', 'd', "directory to \"build\" (copy) to"),
('compile', 'c', "compile .py to .pyc"),
('no-compile', None, "don't compile .py files [default]"),
(
... | build_py |
python | django__django | django/contrib/gis/gdal/geometries.py | {
"start": 26802,
"end": 28848
} | class ____(GeometryCollection):
geos_support = False
# Class mapping dictionary (using the OGRwkbGeometryType as the key)
GEO_CLASSES = {
1: Point,
2: LineString,
3: Polygon,
4: MultiPoint,
5: MultiLineString,
6: MultiPolygon,
7: GeometryCollection,
8: CircularString,
9: Compou... | MultiCurve |
python | langchain-ai__langchain | libs/partners/openai/tests/integration_tests/chat_models/test_base.py | {
"start": 37904,
"end": 40584
} | class ____(BaseModel):
response: str
def test_stream_response_format() -> None:
full: BaseMessageChunk | None = None
chunks = []
for chunk in ChatOpenAI(model="gpt-5-nano").stream(
"how are ya", response_format=Foo
):
chunks.append(chunk)
full = chunk if full is None else f... | Foo |
python | huggingface__transformers | src/transformers/models/nystromformer/modeling_nystromformer.py | {
"start": 36277,
"end": 39718
} | class ____(NystromformerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
config.num_labels = 2
self.num_labels = config.num_labels
self.nystromformer = NystromformerModel(config)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
... | NystromformerForQuestionAnswering |
python | ray-project__ray | python/ray/data/tests/unit/test_datatype.py | {
"start": 26672,
"end": 29988
} | class ____:
"""Test that pattern-matching DataTypes can be used as arguments to factory methods."""
@pytest.mark.parametrize(
"factory_call,expected_logical_dtype",
[
# list with pattern-matching element type
(lambda: DataType.list(DataType.list()), "list"),
... | TestNestedPatternMatching |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_sort_values.py | {
"start": 22211,
"end": 29246
} | class ____: # test key sorting (issue 27237)
def test_sort_values_inplace_key(self, sort_by_key):
frame = DataFrame(
np.random.default_rng(2).standard_normal((4, 4)),
index=[1, 2, 3, 4],
columns=["A", "B", "C", "D"],
)
sorted_df = frame.copy()
re... | TestDataFrameSortKey |
python | squidfunk__mkdocs-material | includes/debug/cairo-lookup-linux.py | {
"start": 83,
"end": 3491
} | class ____(subprocess.Popen):
def __init__(self, *args, **kwargs):
print(f"Subprocess command:\n {' '.join(args[0])}")
super().__init__(*args, **kwargs)
def communicate(self, *args, **kwargs):
out, _ = super().communicate(*args, **kwargs)
out = out.rstrip()
print("Subp... | CustomPopen |
python | pytorch__pytorch | test/test_custom_ops.py | {
"start": 158988,
"end": 159830
} | class ____(CustomOpTestCaseBase):
test_ns = "mini_op_test"
def test_nonzero_again(self):
x = torch.tensor([0, 1, 2, 0, 0])
y = torch.ops.aten.nonzero.default(x)
self.assertEqual(y, torch.tensor([[1], [2]]))
optests.generate_opcheck_tests(
MiniOpTest,
["aten", "mini_op_test"],
... | MiniOpTestOther |
python | kamyu104__LeetCode-Solutions | Python/shuffle-string.py | {
"start": 600,
"end": 898
} | class ____(object):
def restoreString(self, s, indices):
"""
:type s: str
:type indices: List[int]
:rtype: str
"""
result = ['']*len(s)
for i, c in itertools.izip(indices, s):
result[i] = c
return "".join(result)
| Solution2 |
python | modin-project__modin | modin/config/envvars.py | {
"start": 41492,
"end": 41874
} | class ____(EnvironmentVariable, type=int):
"""
Targeted max number of dataframe rows which should be transferred between engines.
This is often the same value as MODIN_NATIVE_MAX_ROWS but it can be independently
set to change how transfer costs are considered.
"""
varname = "MODIN_NATIVE_MAX_X... | NativePandasTransferThreshold |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 495175,
"end": 496074
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("has_pinned_items", "items")
has_pinned_items = sgqlc.types.Field(
sgqlc.types.non_null(Boolean), graphql_name="hasPinnedItems"
)
items = sgqlc.types.Field(
... | ProfileItemShowcase |
python | crytic__slither | slither/detectors/statements/chronicle_unchecked_price.py | {
"start": 425,
"end": 6172
} | class ____(AbstractDetector):
"""
Documentation: This detector finds calls to Chronicle oracle where the returned price is not checked
https://docs.chroniclelabs.org/Resources/FAQ/Oracles#how-do-i-check-if-an-oracle-becomes-inactive-gets-deprecated
"""
ARGUMENT = "chronicle-unchecked-price"
HEL... | ChronicleUncheckedPrice |
python | walkccc__LeetCode | solutions/1996. The Number of Weak Characters in the Game/1996.py | {
"start": 0,
"end": 398
} | class ____:
def numberOfWeakCharacters(self, properties: list[list[int]]) -> int:
ans = 0
maxDefense = 0
# Sort properties by `attack` in descending order, then by `defense` in
# ascending order.
for _, defense in sorted(properties, key=lambda x: (-x[0], x[1])):
if defense < maxDefense:
... | Solution |
python | huggingface__transformers | src/transformers/models/xlm/modeling_xlm.py | {
"start": 57628,
"end": 62985
} | class ____(XLMPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.transformer = XLMModel(config)
self.qa_outputs = XLMSQuADHead(config)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
sel... | XLMForQuestionAnswering |
python | huggingface__transformers | src/transformers/models/hubert/modular_hubert.py | {
"start": 11573,
"end": 11760
} | class ____(Wav2Vec2ForSequenceClassification):
pass
__all__ = ["HubertForCTC", "HubertForSequenceClassification", "HubertModel", "HubertPreTrainedModel"]
| HubertForSequenceClassification |
python | pytorch__pytorch | torch/distributed/_composable/replicate_with_fsdp.py | {
"start": 10193,
"end": 14288
} | class ____(FSDPModule):
def __new__(cls, *args, **kwargs):
"""
Override ``__new__`` to remove the FSDP class and directly construct
the original class for cases like indexing into a container module.
"""
# Use index 2 since 0 is the dynamically constructed `FSDP<...>` class
... | ReplicateModule |
python | getsentry__sentry | tests/sentry/integrations/jira_server/test_utils.py | {
"start": 244,
"end": 539
} | class ____(TestCase):
def test_jira_server(self) -> None:
user_response = StubService.get_stub_data("jira", "jira_server_user.json")
assert build_user_choice(user_response, "name") == (
"bob",
"Bobby - bob@example.org (bob)",
)
| BuildUserChoiceTest |
python | PyCQA__pylint | tests/functional/s/super/super_init_not_called.py | {
"start": 501,
"end": 776
} | class ____(UninferableParent): # [undefined-variable]
"""An implementation that test if we don't crash on uninferable parents."""
def __init__(self):
...
# Tests for not calling the init of a parent that does not define one
# but inherits it.
| UninferableChild |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_range_return_values.py | {
"start": 277,
"end": 3296
} | class ____(unittest.TestCase):
"""
Test the return value for various functions that handle 1 or 2D ranges.
"""
def test_range_return_values(self):
"""Test writing a worksheet with data out of bounds."""
worksheet = Worksheet()
max_row = 1048576
max_col = 16384
... | TestRangeReturnValues |
python | apache__airflow | providers/docker/tests/unit/docker/decorators/test_docker.py | {
"start": 1939,
"end": 15680
} | class ____:
@pytest.mark.db_test
def test_basic_docker_operator(self, dag_maker, session):
@task.docker(image="python:3.9-slim", auto_remove="force")
def f():
import random
return [random.random() for _ in range(100)]
with dag_maker(session=session):
... | TestDockerDecorator |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 18202,
"end": 18855
} | class ____:
document: bool = False
embedding: bool = False
metadata: bool = False
rank: bool = False
uri: bool = False
@property
def included(self) -> Include:
includes = list()
if self.document:
includes.append("documents")
if self.embedding:
... | Projection |
python | huggingface__transformers | src/transformers/models/m2m_100/modeling_m2m_100.py | {
"start": 45875,
"end": 51380
} | class ____(M2M100PreTrainedModel, GenerationMixin):
base_model_prefix = "model"
_tied_weights_keys = {"lm_head.weight": "model.shared.weight"}
def __init__(self, config: M2M100Config):
super().__init__(config)
self.model = M2M100Model(config)
self.lm_head = nn.Linear(config.d_model,... | M2M100ForConditionalGeneration |
python | sdispater__pendulum | src/pendulum/_helpers.py | {
"start": 931,
"end": 8796
} | class ____(NamedTuple):
years: int
months: int
days: int
hours: int
minutes: int
seconds: int
microseconds: int
total_days: int
def __repr__(self) -> str:
return (
f"{self.years} years "
f"{self.months} months "
f"{self.days} days "
... | PreciseDiff |
python | ray-project__ray | doc/source/serve/doc_code/batching_guide.py | {
"start": 1896,
"end": 2857
} | class ____:
async def generate_numbers(self, max: str) -> AsyncGenerator[str, None]:
for i in range(max):
yield str(i)
await asyncio.sleep(0.1)
def __call__(self, request: Request) -> StreamingResponse:
max = int(request.query_params.get("max", "25"))
gen = self.... | StreamingResponder |
python | django__django | tests/migrations/migrations_test_apps/lookuperror_b/migrations/0002_b2.py | {
"start": 43,
"end": 690
} | class ____(migrations.Migration):
dependencies = [
("lookuperror_a", "0002_a2"),
("lookuperror_b", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="B2",
fields=[
(
"id",
models.AutoField(
... | Migration |
python | joerick__pyinstrument | pyinstrument/stack_sampler.py | {
"start": 11597,
"end": 12550
} | class ____(NamedTuple):
state: LiteralStr["in_context", "out_of_context_awaited", "out_of_context_unknown"]
"""
Definitions:
``in_context``: indicates that the sample comes from the subscriber's
context.
``out_of_context_awaited``: the sample comes from outside the
subscriber's cont... | AsyncState |
python | PrefectHQ__prefect | src/prefect/utilities/schema_tools/validation.py | {
"start": 668,
"end": 10743
} | class ____(Exception):
pass
PLACEHOLDERS_VALIDATOR_NAME = "_placeholders"
def _build_validator() -> type["_Validator"]:
def _applicable_validators(schema: Schema) -> Iterable[tuple[str, Any]]:
# the default implementation returns `schema.items()`
assert not isinstance(schema, bool)
s... | ValidationError |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_embedding_v3_checkpoint_adapter.py | {
"start": 9403,
"end": 14590
} | class ____(checkpoint_adapter.ReshardCallback):
"""Reshard callback for embeddings."""
def __init__(
self,
object_local_name: str,
from_shard_layouts: Mapping[
str, Sequence[sparse_core_layout_pb2.SparseCoreTableLayout]
],
to_shard_layouts: Sequence[sparse_core_layout_pb2.Sp... | EmbeddingReshardCallback |
python | Textualize__textual | docs/examples/guide/reactivity/refresh01.py | {
"start": 151,
"end": 300
} | class ____(Widget):
"""Generates a greeting."""
who = reactive("name")
def render(self) -> str:
return f"Hello, {self.who}!"
| Name |
python | matplotlib__matplotlib | lib/matplotlib/hatch.py | {
"start": 5257,
"end": 5438
} | class ____(Circles):
size = 0.2
def __init__(self, hatch, density):
self.num_rows = (hatch.count('o')) * density
super().__init__(hatch, density)
| SmallCircles |
python | huggingface__transformers | tests/models/clip/test_modeling_clip.py | {
"start": 24176,
"end": 26148
} | class ____(CLIPModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (CLIPForImageClassification,) if is_torch_available() else ()
pipeline_model_mapping = {"image-classification": CLIPForImageClassification} if is_torch_available() else {}
test_resize_embeddings = False
test_a... | CLIPForImageClassificationModelTest |
python | Pylons__pyramid | tests/test_authorization.py | {
"start": 18802,
"end": 19207
} | class ____:
def __init__(self, *arg, **kw):
self.__dict__.update(kw)
VIEW = 'view'
EDIT = 'edit'
CREATE = 'create'
DELETE = 'delete'
MODERATE = 'moderate'
ADMINISTER = 'administer'
COMMENT = 'comment'
GUEST_PERMS = (VIEW, COMMENT)
MEMBER_PERMS = GUEST_PERMS + (EDIT, CREATE, DELETE)
MODERATOR_PERMS = MEMB... | DummyContext |
python | Textualize__textual | docs/examples/styles/links.py | {
"start": 155,
"end": 376
} | class ____(App):
CSS_PATH = "links.tcss"
def compose(self) -> ComposeResult:
yield Static(TEXT)
yield Static(TEXT, id="custom")
if __name__ == "__main__":
app = LinksApp()
app.run()
| LinksApp |
python | tensorflow__tensorflow | tensorflow/python/debug/wrappers/dumping_wrapper.py | {
"start": 995,
"end": 5166
} | class ____(framework.NonInteractiveDebugWrapperSession):
"""Debug Session wrapper that dumps debug data to filesystem."""
def __init__(self,
sess,
session_root,
watch_fn=None,
thread_name_filter=None,
pass_through_operrors=None):
"""Con... | DumpingDebugWrapperSession |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 49208,
"end": 60038
} | class ____(GroupViTPreTrainedModel):
config: GroupViTConfig
def __init__(self, config: GroupViTConfig):
super().__init__(config)
if not isinstance(config.text_config, GroupViTTextConfig):
raise TypeError(
"config.text_config is expected to be of type GroupViTTextCon... | GroupViTModel |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 4224,
"end": 5049
} | class ____(BaseIO):
fname = "__test__.csv"
params = ([1000, 10000], ["D", "h"])
param_names = ["nobs", "freq"]
def setup(self, nobs, freq):
rng = period_range(start="2000-01-01", periods=nobs, freq=freq)
self.data = DataFrame({"a": 1}, index=rng)
if freq == "D":
sel... | ToCSVPeriodIndex |
python | pytorch__pytorch | torch/fx/experimental/migrate_gradual_types/constraint.py | {
"start": 3365,
"end": 4150
} | class ____(Constraint):
"""
Greatest Upper bound for tensors with dynamic type
"""
def __init__(self, res, rhs1, rhs2):
"""
:param res: tensor variable that stores the result of the output
:param rhs1: tensor or tensor variable
:param rhs2: tensor or tensor variabke
... | TGreatestUpperBound |
python | pypa__setuptools | setuptools/config/_validate_pyproject/formats.py | {
"start": 5106,
"end": 13564
} | class ____:
"""The ``trove_classifiers`` package is the official way of validating classifiers,
however this package might not be always available.
As a workaround we can still download a list from PyPI.
We also don't want to be over strict about it, so simply skipping silently is an
option (classif... | _TroveClassifier |
python | allegroai__clearml | clearml/automation/job.py | {
"start": 602,
"end": 19432
} | class ____(object):
_job_hash_description = "job_hash={}"
_job_hash_property = "pipeline_job_hash"
_hashing_callback = None
_last_batch_status_update_ts = 0
def __init__(self) -> None:
"""
Base Job is an abstract CLearML Job
"""
self._is_cached_task = False
s... | BaseJob |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/scaffold/branch/ai.py | {
"start": 3244,
"end": 6658
} | class ____(InputType):
"""Matches GitHub issue URLs and instructs AI tools to fetch issue details."""
@classmethod
def matches(cls, user_input: str) -> bool:
return user_input.startswith("https://github.com/")
@classmethod
def get_context(cls, user_input: str) -> str:
return (
... | GithubIssueInputType |
python | django__django | tests/test_runner_apps/tagged/tests_inheritance.py | {
"start": 109,
"end": 251
} | class ____(FooBase):
def test_no_new_tags(self):
pass
@tag("baz")
def test_new_func_tag(self):
pass
@tag("bar")
| Foo |
python | apache__airflow | airflow-core/tests/unit/dag_processing/test_collection.py | {
"start": 41068,
"end": 42204
} | class ____:
@pytest.fixture(autouse=True)
def setup_teardown(self, session):
yield
session.query(DagModel).filter(DagModel.dag_id == "test_dag").delete()
session.commit()
@pytest.mark.parametrize(
("initial_tags", "new_tags", "expected_tags"),
[
(["danger... | TestUpdateDagTags |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_compute.py | {
"start": 4191,
"end": 9741
} | class ____:
@mock.patch(COMPUTE_ENGINE_HOOK_PATH)
def test_insert_instance_should_execute_successfully(self, mock_hook):
get_instance_obj_mock = mock.MagicMock()
get_instance_obj_mock.__class__ = Instance
mock_hook.return_value.get_instance.side_effect = [
NotFound("Error mes... | TestGceInstanceInsert |
python | scipy__scipy | scipy/linalg/tests/test_fblas.py | {
"start": 16443,
"end": 16634
} | class ____(BaseGer):
blas_func = fblas.dger
dtype = float64
"""
##################################################
# Test blas ?gerc
# This will be a mess to test all cases.
"""
| TestDger |
python | ray-project__ray | python/ray/data/_internal/planner/plan_expression/expression_visitors.py | {
"start": 767,
"end": 2207
} | class ____(_ExprVisitor[None]):
"""Base visitor that provides automatic recursive traversal.
This class extends _ExprVisitor and provides default implementations
for composite nodes that automatically traverse child expressions.
"""
def visit_binary(self, expr: "BinaryExpr") -> None:
"""De... | _ExprVisitorBase |
python | charliermarsh__ruff | crates/ty_python_semantic/resources/corpus/75_classderef_no.py | {
"start": 0,
"end": 73
} | class ____:
def foo(self, bar):
def inner():
bar
| Foo |
python | kamyu104__LeetCode-Solutions | Python/find-substring-with-given-hash-value.py | {
"start": 44,
"end": 622
} | class ____(object):
def subStrHash(self, s, power, modulo, k, hashValue):
"""
:type s: str
:type power: int
:type modulo: int
:type k: int
:type hashValue: int
:rtype: str
"""
h, idx = 0, -1
pw = pow(power, k-1, modulo)
for i in... | Solution |
python | doocs__leetcode | lcof2/剑指 Offer II 080. 含有 k 个元素的组合/Solution.py | {
"start": 0,
"end": 380
} | class ____:
def combine(self, n: int, k: int) -> List[List[int]]:
res = []
def dfs(i, n, k, t):
if len(t) == k:
res.append(t.copy())
return
for j in range(i, n + 1):
t.append(j)
dfs(j + 1, n, k, t)
... | Solution |
python | celery__celery | celery/exceptions.py | {
"start": 4056,
"end": 4161
} | class ____(CeleryWarning):
"""Multiple workers are using the same nodename."""
| DuplicateNodenameWarning |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 831347,
"end": 831739
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("PackageVersion", graphql_... | PackageVersionEdge |
python | readthedocs__readthedocs.org | readthedocs/oauth/migrations/0005_add_account_relation.py | {
"start": 100,
"end": 1163
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("socialaccount", "0002_token_max_lengths"),
("oauth", "0004_drop_github_and_bitbucket_models"),
]
operations = [
migrations.AddField(
model_name="remoteorganization",
name="acc... | Migration |
python | walkccc__LeetCode | solutions/62. Unique Paths/62.py | {
"start": 0,
"end": 293
} | class ____:
def uniquePaths(self, m: int, n: int) -> int:
# dp[i][j] := the number of unique paths from (0, 0) to (i, j)
dp = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[-1][-1]
| Solution |
python | qdrant__qdrant-client | tools/async_client_generator/transformers/constant_transformer.py | {
"start": 41,
"end": 573
} | class ____(ast.NodeTransformer):
def __init__(self, constant_replace_map: Optional[dict[str, str]]):
self.constant_replace_map = (
constant_replace_map if constant_replace_map is not None else {}
)
def visit_Constant(self, node: ast.Constant) -> ast.AST:
for old_value, new_v... | ConstantTransformer |
python | pypa__hatch | src/hatch/venv/core.py | {
"start": 3701,
"end": 4348
} | class ____(VirtualEnv):
def __init__(self, parent_python, platform, verbosity=0):
self.parent_python = parent_python
self.parent_dir = TemporaryDirectory()
directory = Path(self.parent_dir.name).resolve() / get_random_venv_name()
super().__init__(directory, platform, verbosity)
... | TempVirtualEnv |
python | pennersr__django-allauth | allauth/socialaccount/providers/baidu/provider.py | {
"start": 217,
"end": 671
} | class ____(ProviderAccount):
def get_profile_url(self):
return "https://www.baidu.com/p/" + self.account.extra_data.get("uname")
def get_avatar_url(self):
return (
"https://tb.himg.baidu.com/sys/portraitn/item/"
+ self.account.extra_data.get("portrait")
)
de... | BaiduAccount |
python | ansible__ansible | test/units/module_utils/json_utils/test_filter_non_json_lines.py | {
"start": 844,
"end": 2916
} | class ____(unittest.TestCase):
single_line_json_dict = u"""{"key": "value", "olá": "mundo"}"""
single_line_json_array = u"""["a","b","c"]"""
multi_line_json_dict = u"""{
"key":"value"
}"""
multi_line_json_array = u"""[
"a",
"b",
"c"]"""
all_inputs = [
single_line_json_dict,
single_l... | TestAnsibleModuleExitJson |
python | kamyu104__LeetCode-Solutions | Python/network-recovery-pathways.py | {
"start": 114,
"end": 2069
} | class ____(object):
def findMaxPathScore(self, edges, online, k):
"""
:type edges: List[List[int]]
:type online: List[bool]
:type k: int
:rtype: int
"""
INF = float("inf")
def binary_search_right(left, right, check):
while left <= right:
... | Solution |
python | django__django | tests/db_functions/math/test_atan.py | {
"start": 269,
"end": 2351
} | class ____(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = IntegerModel.objects.annotate(null_atan=ATan("normal")).first()
self.assertIsNone(obj.null_atan)
def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6"))
obj... | ATanTests |
python | numpy__numpy | benchmarks/benchmarks/bench_ufunc.py | {
"start": 11589,
"end": 12601
} | class ____(Benchmark):
def setup(self):
self.c = np.ones(500000, dtype=np.int8)
self.i = np.ones(150000, dtype=np.int32)
self.f = np.zeros(150000, dtype=np.float32)
self.d = np.zeros(75000, dtype=np.float64)
# fault memory
self.f *= 1.
self.d *= 1.
def ti... | CustomInplace |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass4.py | {
"start": 200,
"end": 403
} | class ____(type):
def do_something(self, p1: str, p2: int):
pass
MyCustomClass = MyMeta("MyCustomClass", (object,), {})
reveal_type(MyCustomClass, expected_text="type[MyCustomClass]")
| MyMeta |
python | sympy__sympy | sympy/physics/mechanics/actuator.py | {
"start": 37397,
"end": 43633
} | class ____(ForceActuator):
r"""Coulomb kinetic friction with Stribeck and viscous effects.
Explanation
===========
This represents a Coulomb kinetic friction with the Stribeck and viscous effect,
described by the function:
.. math::
F = (\mu_k f_n + (\mu_s - \mu_k) f_n e^{-(\frac{v}{v... | CoulombKineticFriction |
python | huggingface__transformers | src/transformers/models/idefics/vision.py | {
"start": 1302,
"end": 3177
} | class ____(ModelOutput):
"""
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
Args:
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
... | IdeficsVisionModelOutput |
python | keras-team__keras | keras/src/layers/normalization/group_normalization_test.py | {
"start": 164,
"end": 5919
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_groupnorm(self):
self.run_layer_test(
layers.GroupNormalization,
init_kwargs={
"gamma_regularizer": regularizers.L2(0.01),
"beta_regularizer": regularizers.L2(0.01),
... | GroupNormalizationTest |
python | doocs__leetcode | solution/1400-1499/1411.Number of Ways to Paint N × 3 Grid/Solution.py | {
"start": 0,
"end": 272
} | class ____:
def numOfWays(self, n: int) -> int:
mod = 10**9 + 7
f0 = f1 = 6
for _ in range(n - 1):
g0 = (3 * f0 + 2 * f1) % mod
g1 = (2 * f0 + 2 * f1) % mod
f0, f1 = g0, g1
return (f0 + f1) % mod
| Solution |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_E.py | {
"start": 4887,
"end": 6324
} | class ____(Benchmark):
r"""
Egg Holder [1]_ objective function.
This class defines the Egg Holder global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{EggHolder}}=\sum_{1}^{n - 1}\left[-\left(x_{i + 1}
+ 47 \right ) \sin\sq... | EggHolder |
python | pyqtgraph__pyqtgraph | pyqtgraph/dockarea/Container.py | {
"start": 5017,
"end": 5881
} | class ____(SplitContainer):
def __init__(self, area):
SplitContainer.__init__(self, area, QtCore.Qt.Orientation.Horizontal)
def type(self):
return 'horizontal'
def updateStretch(self):
##Set the stretch values for this container to reflect its contents
#prin... | HContainer |
python | pytorch__pytorch | torch/testing/_internal/distributed/distributed_test.py | {
"start": 9129,
"end": 9466
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.a = nn.Linear(10, 10, bias=False)
self.b = nn.Linear(10, 10, bias=False)
self.c = nn.Linear(5, 5, bias=False)
def forward(self, x):
a = self.a(x)
b = self.b(x)
return (a, b)
| UnusedParamTwoLinLayerNet |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/utils.py | {
"start": 13238,
"end": 14792
} | class ____(dict[str, Any]):
"""Dictionary that can be added to another dictionary."""
def __add__(self, other: AddableDict) -> AddableDict:
"""Add a dictionary to this dictionary.
Args:
other: The other dictionary to add.
Returns:
A dictionary that is the resul... | AddableDict |
python | Netflix__metaflow | metaflow/user_configs/config_options.py | {
"start": 18602,
"end": 22435
} | class ____(click.Path):
# Small wrapper around click.Path to set the value from which to read configuration
# values. This is set immediately upon processing the --local-config-file
# option and will therefore then be available when processing any of the other
# --config options (which will call ConfigI... | LocalFileInput |
python | apache__airflow | providers/mysql/tests/unit/mysql/transfers/test_presto_to_mysql.py | {
"start": 1044,
"end": 2733
} | class ____:
def setup_method(self):
self.kwargs = dict(
sql="sql",
mysql_table="mysql_table",
task_id="test_presto_to_mysql_transfer",
)
args = {"owner": "airflow", "start_date": DEFAULT_DATE}
self.dag = DAG("test_presto_to_mysql_transfer", schedul... | TestPrestoToMySqlTransfer |
python | ray-project__ray | rllib/algorithms/dqn/dqn_learner.py | {
"start": 1428,
"end": 4654
} | class ____(Learner):
@OverrideToImplementCustomLogic_CallToSuperRecommended
@override(Learner)
def build(self) -> None:
super().build()
# Make target networks.
self.module.foreach_module(
lambda mid, mod: (
mod.make_target_networks()
if is... | DQNLearner |
python | astropy__astropy | astropy/utils/masked/tests/test_functions.py | {
"start": 14497,
"end": 14855
} | class ____(MaskedUfuncTests, LongitudeSetup):
def test_ufunc_inplace_quantity_initial(self):
out = Masked(np.zeros(self.ma.shape) << u.m)
result = np.add(self.ma, self.mb, out=out)
assert result is out
expected = np.add(self.ma, self.mb).view(Quantity)
assert_masked_equal(res... | TestMaskedLongitudeUfuncs |
python | pytorch__pytorch | torch/ao/quantization/experimental/observer.py | {
"start": 475,
"end": 5944
} | class ____(ObserverBase):
b: int
k: int
n: int
min_val: torch.Tensor
max_val: torch.Tensor
def __init__(self, b, k, dtype=torch.quint8) -> None:
super().__init__(dtype)
self.b = b
self.k = k
self.min_val = torch.tensor([])
self.max_val = torch.tensor([])... | APoTObserver |
python | django-extensions__django-extensions | django_extensions/db/fields/__init__.py | {
"start": 16864,
"end": 20123
} | class ____:
"""
UUIDFieldMixin
By default uses UUID version 4 (randomly generated UUID).
The field support all uuid versions which are natively supported by the uuid python module, except version 2.
For more information see: https://docs.python.org/lib/module-uuid.html
""" # noqa: E501
D... | UUIDFieldMixin |
python | ray-project__ray | rllib/evaluation/episode_v2.py | {
"start": 794,
"end": 14949
} | class ____:
"""Tracks the current state of a (possibly multi-agent) episode."""
def __init__(
self,
env_id: EnvID,
policies: PolicyMap,
policy_mapping_fn: Callable[[AgentID, "EpisodeV2", "RolloutWorker"], PolicyID],
*,
worker: Optional["RolloutWorker"] = None,
... | EpisodeV2 |
python | apache__airflow | airflow-core/src/airflow/secrets/environment_variables.py | {
"start": 1026,
"end": 1542
} | class ____(BaseSecretsBackend):
"""Retrieves Connection object and Variable from environment variable."""
def get_conn_value(self, conn_id: str) -> str | None:
return os.environ.get(CONN_ENV_PREFIX + conn_id.upper())
def get_variable(self, key: str) -> str | None:
"""
Get Airflow V... | EnvironmentVariablesBackend |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_test.py | {
"start": 122602,
"end": 128648
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_deprecated_v1
def testBasic(self):
a = constant_op.constant([2.0], name="a")
with ops.colocate_with(a.op):
b = constant_op.constant(3.0)
c = constant_op.constant(4.0)
self.assertEqual([b"loc:@a"], a.op.colocation_groups())
self.asse... | ColocationGroupTest |
python | kubernetes-client__python | kubernetes/client/models/v1_csi_storage_capacity_list.py | {
"start": 383,
"end": 7115
} | 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... | V1CSIStorageCapacityList |
python | pandas-dev__pandas | asv_bench/benchmarks/tslibs/tz_convert.py | {
"start": 522,
"end": 1509
} | class ____:
params = [
_sizes,
[x for x in _tzs if x is not None],
]
param_names = ["size", "tz"]
def setup(self, size, tz):
if size == 10**6 and tz is tzlocal_obj:
# tzlocal is cumbersomely slow, so skip to keep runtime in check
raise NotImplementedError... | TimeTZConvert |
python | allegroai__clearml | clearml/hyperdatasets/data_view.py | {
"start": 6288,
"end": 47227
} | class ____:
_MAX_BATCH_SIZE = 10000
_DEFAULT_LOCAL_BATCH_SIZE = 500
def __init__(
self,
name=None,
description=None,
tags=None,
iteration_order="sequential",
iteration_infinite=False,
iteration_random_seed=None,
iteration_limit=None,
a... | DataView |
python | openai__openai-python | src/openai/lib/streaming/chat/_events.py | {
"start": 303,
"end": 437
} | class ____(BaseModel):
type: Literal["chunk"]
chunk: ChatCompletionChunk
snapshot: ParsedChatCompletionSnapshot
| ChunkEvent |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.