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 | encode__django-rest-framework | tests/models.py | {
"start": 1011,
"end": 1411
} | class ____(RESTFrameworkModel):
name = models.CharField(max_length=100)
def get_first_source(self):
"""Used for testing related field against a callable."""
return self.sources.all().order_by('pk')[0]
@property
def first_source(self):
"""Used for testing related field against a... | ForeignKeyTarget |
python | spack__spack | lib/spack/spack/spec.py | {
"start": 223154,
"end": 223263
} | class ____(spack.error.SpecError):
"""Called for errors in Spec path-format strings."""
| SpecFormatPathError |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 42865,
"end": 44571
} | class ____(Request):
"""
Delete all task event. *This cannot be undone!*
:param task: Task ID
:type task: str
:param allow_locked: Allow deleting events even if the task is locked
:type allow_locked: bool
"""
_service = "events"
_action = "delete_for_task"
_version = "2.9"
... | DeleteForTaskRequest |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_us_state.py | {
"start": 1787,
"end": 4619
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid state abbreviations.
See https://pypi.org/project/us/ for more information. \
DC statehood is a perennial issue in data science, and the owners of the us repo addressed it differently than we have: https://github.com/unitedstates... | ExpectColumnValuesToBeValidUSState |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_M.py | {
"start": 17340,
"end": 18473
} | class ____(Benchmark):
r"""
Mishra 10 objective function.
This class defines the Mishra 10 global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
TODO - int(x) should be used instead of floor(x)!!!!!
f_{\text{Mishra10}}({x}) = \left[ \lfloo... | Mishra10 |
python | euske__pdfminer | pdfminer/cmapdb.py | {
"start": 6490,
"end": 11640
} | class ____(PSStackParser):
def __init__(self, cmap, fp):
PSStackParser.__init__(self, fp)
self.cmap = cmap
# some ToUnicode maps don't have "begincmap" keyword.
self._in_cmap = True
return
def run(self):
try:
self.nextobject()
except PSEOF:
... | CMapParser |
python | PyCQA__pylint | tests/functional/ext/redefined_variable_type/redefined_variable_type.py | {
"start": 2130,
"end": 2296
} | class ____:
async def funtion1(self):
potato = 1
print(potato)
async def funtion2(self):
potato = {}
print(potato)
| AsyncFunctions |
python | python-attrs__attrs | src/attr/validators.py | {
"start": 17871,
"end": 20247
} | class ____:
validator = attrib()
msg = attrib(
converter=default_if_none(
"not_ validator child '{validator!r}' "
"did not raise a captured error"
)
)
exc_types = attrib(
validator=deep_iterable(
member_validator=_subclass_of(Exception),
... | _NotValidator |
python | plotly__plotly.py | plotly/graph_objs/candlestick/increasing/_line.py | {
"start": 233,
"end": 3039
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "candlestick.increasing"
_path_str = "candlestick.increasing.line"
_valid_props = {"color", "width"}
@property
def color(self):
"""
Sets the color of line bounding the box(es).
The 'color' property is a color and may b... | Line |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/callback_runner.py | {
"start": 1337,
"end": 4122
} | class ____(Protocol):
def __call__(
self,
func: Callable[P, R],
outlet_events: OutletEventAccessorsProtocol,
*,
logger: logging.Logger | Logger,
) -> _ExecutionCallableRunner[P, R]: ...
def create_executable_runner(
func: Callable[P, R],
outlet_events: OutletEve... | ExecutionCallableRunner |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/metadata.py | {
"start": 4913,
"end": 5084
} | class ____(graphene.Union):
class Meta:
types = (GrapheneLocalFileCodeReference, GrapheneUrlCodeReference)
name = "SourceLocation"
| GrapheneSourceLocation |
python | more-itertools__more-itertools | more_itertools/more.py | {
"start": 166576,
"end": 167301
} | class ____:
__slots__ = ('iterator', 'link', 'lock')
def __init__(self, iterable):
it = iter(iterable)
if isinstance(it, _concurrent_tee):
self.iterator = it.iterator
self.link = it.link
self.lock = it.lock
else:
self.iterator = it
... | _concurrent_tee |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 58736,
"end": 60821
} | class ____:
"""Test zh_CN address provider methods"""
def test_postcode(self, faker, num_samples):
for _ in range(num_samples):
postcode = faker.postcode()
assert isinstance(postcode, str)
assert re.fullmatch(r"[1-9]\d{5}", postcode)
def test_city_name(self, fak... | TestZhCn |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_checks/asset_check_spec.py | {
"start": 1614,
"end": 5522
} | class ____(IHaveNew, LegacyNamedTupleMixin):
name: PublicAttr[str]
asset_key: PublicAttr[AssetKey]
description: PublicAttr[Optional[str]]
additional_deps: PublicAttr[Iterable[LazyAssetDep]]
blocking: PublicAttr[bool]
metadata: PublicAttr[Mapping[str, Any]]
automation_condition: PublicAttr[Op... | AssetCheckSpec |
python | aimacode__aima-python | nlp4e.py | {
"start": 3587,
"end": 10798
} | class ____:
def __init__(self, name, rules, lexicon):
"""A grammar has a set of rules and a lexicon.
Each rule has a probability."""
self.name = name
self.rules = rules
self.lexicon = lexicon
self.categories = defaultdict(list)
for lhs in lexicon:
... | ProbGrammar |
python | pytorch__pytorch | torch/export/graph_signature.py | {
"start": 2808,
"end": 3448
} | class ____:
kind: OutputKind
arg: ArgumentSpec
target: Optional[str]
def __post_init__(self):
assert isinstance(
self.arg,
(
TensorArgument,
SymIntArgument,
SymFloatArgument,
SymBoolArgument,
... | OutputSpec |
python | dabeaz-course__practical-python | Solutions/4_10/tableformat.py | {
"start": 660,
"end": 877
} | class ____(TableFormatter):
'''
Output data in CSV format.
'''
def headings(self, headers):
print(','.join(headers))
def row(self, rowdata):
print(','.join(rowdata))
| CSVTableFormatter |
python | bokeh__bokeh | src/bokeh/server/callbacks.py | {
"start": 3545,
"end": 4369
} | class ____(SessionCallback):
''' Represent a callback to execute once on the ``IOLoop`` after a specified
time interval passes.
'''
_timeout: int
def __init__(self, callback: Callback, timeout: int, *, callback_id: ID) -> None:
'''
Args:
callback (callable) :
... | TimeoutCallback |
python | coleifer__peewee | peewee.py | {
"start": 31422,
"end": 33476
} | class ____(_HashableSource, Source):
def __init__(self, name, query, recursive=False, columns=None,
materialized=None):
self._alias = name
self._query = query
self._recursive = recursive
self._materialized = materialized
if columns is not None:
co... | CTE |
python | tensorflow__tensorflow | tensorflow/python/data/ops/readers.py | {
"start": 12148,
"end": 14741
} | class ____(dataset_ops.UnaryDataset):
"""A `Dataset` that maps a function over its input and flattens the result."""
def __init__(self,
input_dataset,
map_func,
cycle_length,
block_length,
sloppy,
buffer_output_elements,
... | ParallelInterleaveDataset |
python | ApeWorX__ape | src/ape/plugins/project.py | {
"start": 852,
"end": 1607
} | class ____(PluginType):
"""
A plugin for downloading packages and creating
:class:`~ape.plugins.project.ProjectPlugin` implementations.
"""
@hookspec
def dependencies(self) -> dict[str, type["DependencyAPI"]]: # type: ignore[empty-body]
"""
A hook that returns a :class:`~ape.ap... | DependencyPlugin |
python | pyca__cryptography | tests/hazmat/primitives/test_hash_vectors.py | {
"start": 1212,
"end": 1560
} | class ____:
test_sha256 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA2"),
["SHA256LongMsg.rsp", "SHA256ShortMsg.rsp"],
hashes.SHA256(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.SHA384()),
skip_message="Does n... | TestSHA256 |
python | getsentry__sentry | src/sentry_plugins/pagerduty/plugin.py | {
"start": 329,
"end": 4851
} | class ____(CorePluginMixin, NotificationPlugin):
description = "Send alerts to PagerDuty."
slug = "pagerduty"
title = "PagerDuty"
conf_key = slug
conf_title = title
required_field = "service_key"
feature_descriptions = [
FeatureDescription(
"""
Manage incident... | PagerDutyPlugin |
python | tornadoweb__tornado | tornado/test/asyncio_test.py | {
"start": 5584,
"end": 7775
} | class ____(unittest.TestCase):
# These tests are only relevant on windows, but they should pass anywhere.
def setUp(self):
# As a precaution, ensure that we've run an event loop at least once
# so if it spins up any singleton threads they're already there.
asyncio.run(self.dummy_tornado_... | SelectorThreadLeakTest |
python | doocs__leetcode | solution/1000-1099/1090.Largest Values From Labels/Solution.py | {
"start": 0,
"end": 446
} | class ____:
def largestValsFromLabels(
self, values: List[int], labels: List[int], numWanted: int, useLimit: int
) -> int:
ans = num = 0
cnt = Counter()
for v, l in sorted(zip(values, labels), reverse=True):
if cnt[l] < useLimit:
cnt[l] += 1
... | Solution |
python | wandb__wandb | wandb/integration/yolov8/yolov8.py | {
"start": 546,
"end": 11371
} | class ____:
"""An internal YOLO model wrapper that tracks metrics, and logs models to Weights & Biases.
Usage:
```python
from wandb.integration.yolov8.yolov8 import WandbCallback
model = YOLO("yolov8n.pt")
wandb_logger = WandbCallback(
model,
)
for event, callback_fn in wandb_l... | WandbCallback |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/solver27.py | {
"start": 632,
"end": 791
} | class ____(Generic[T]):
pass
reveal_type(ClassA[int], expected_text="type[ClassA[int]]")
def deco4() -> Callable[[type[T]], type[T]]: ...
@deco4()
| ClassA |
python | Textualize__textual | src/textual/_node_list.py | {
"start": 417,
"end": 531
} | class ____(Exception):
"""Raised when attempting to add a widget with an id that already exists."""
| DuplicateIds |
python | mlflow__mlflow | mlflow/entities/logged_model_parameter.py | {
"start": 116,
"end": 1140
} | class ____(_MlflowObject):
"""
MLflow entity representing a parameter of a Model.
"""
def __init__(self, key, value):
if "pyspark.ml" in sys.modules:
import pyspark.ml.param
if isinstance(key, pyspark.ml.param.Param):
key = key.name
value... | LoggedModelParameter |
python | ApeWorX__ape | src/ape/api/projects.py | {
"start": 2869,
"end": 4020
} | class ____(ProjectAPI):
"""
The default ProjectAPI implementation.
"""
CONFIG_FILE_NAME: str = "ape-config"
EXTENSIONS: tuple[str, ...] = (".yaml", ".yml", ".json")
@property
def is_valid(self) -> bool:
return True # If all else fails, treat as a default Ape project.
@cached_... | ApeProject |
python | Netflix__metaflow | metaflow/runtime.py | {
"start": 83914,
"end": 84737
} | class ____(object):
def __init__(self, name, maxsize):
self.name = name
self._maxsize = maxsize
self._buffer = BytesIO()
self._size = 0
self._eof = False
def write(self, bytedata, system_msg=False):
if system_msg:
self._buffer.write(bytedata)
... | TruncatedBuffer |
python | ray-project__ray | ci/ray_ci/doc/autodoc.py | {
"start": 290,
"end": 5284
} | class ____:
"""
Autodoc class represents the top level sphinx autodoc landing page and finds
autodoc APIs that would be generated from sphinx from all sub-pages.
"""
def __init__(self, head_rst_file: str):
"""
Args:
head_rst_file: The path to the landing page RST file th... | Autodoc |
python | numba__numba | numba/cuda/compiler.py | {
"start": 2093,
"end": 2387
} | class ____(CompileResult):
@property
def entry_point(self):
return id(self)
def cuda_compile_result(**entries):
entries = sanitize_compile_result_entries(entries)
return CUDACompileResult(**entries)
@register_pass(mutates_CFG=True, analysis_only=False)
| CUDACompileResult |
python | pytorch__pytorch | torch/jit/_script.py | {
"start": 8982,
"end": 11664
} | class ____(type):
def __init__(cls, name, bases, attrs): # noqa: B902
# Aggregate all the ScriptMethods and constants from superclasses
cls._methods: dict[str, Any] = {}
cls._constants_set = set(getattr(cls, "__constants__", ()))
for base in reversed(bases):
for k, v in ... | ScriptMeta |
python | zarr-developers__zarr-python | src/zarr/storage/_logging.py | {
"start": 566,
"end": 7399
} | class ____(WrapperStore[T_Store]):
"""
Store that logs all calls to another wrapped store.
Parameters
----------
store : Store
Store to wrap
log_level : str
Log level
log_handler : logging.Handler
Log handler
Attributes
----------
counter : dict
... | LoggingStore |
python | realpython__materials | python-argparse/custom_action.py | {
"start": 18,
"end": 388
} | class ____(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print(f"Storing {values} in the {option_string} option...")
setattr(namespace, self.dest, values)
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-n", "--name", action=VerboseStore)
ar... | VerboseStore |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 171493,
"end": 172137
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"environment_id",
"wait_timer",
"reviewers",
"client_mutation_id",
)
environment_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), gr... | UpdateEnvironmentInput |
python | mlflow__mlflow | tests/genai/judges/test_alignment_optimizer.py | {
"start": 994,
"end": 2250
} | class ____(AlignmentOptimizer):
"""Mock AlignmentOptimizer implementation for testing."""
def align(self, judge: Judge, traces: list[Trace]) -> Judge:
# Return a new judge with modified name to show it was processed
return MockJudge(name=f"{judge.name}_optimized")
def test_alignment_optimizer... | MockOptimizer |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 218010,
"end": 219299
} | class ____(VegaLiteSchema):
"""
CompositionConfig schema wrapper.
Parameters
----------
columns : float
The number of columns to include in the view composition layout.
**Default value**: ``undefined`` -- An infinite number of columns (a single row)
will be assumed. This is... | CompositionConfig |
python | sqlalchemy__sqlalchemy | test/orm/test_instrumentation.py | {
"start": 10236,
"end": 11583
} | class ____(fixtures.MappedTest):
def fixture(self):
return Table(
"t",
MetaData(),
Column("id", Integer, primary_key=True),
Column("type", Integer),
Column("x", Integer),
Column("y", Integer),
)
def test_partially_mapped_in... | MapperInitTest |
python | google__flatbuffers | tests/MyGame/Example/NestedUnion/Any.py | {
"start": 96,
"end": 729
} | class ____(object):
NONE = 0
Vec3 = 1
TestSimpleTableWithEnum = 2
def AnyCreator(unionType, table):
from flatbuffers.table import Table
if not isinstance(table, Table):
return None
if unionType == Any.Vec3:
import MyGame.Example.NestedUnion.Vec3
return MyGame.Example.Nes... | Any |
python | pytorch__pytorch | test/onnx/test_utility_funs.py | {
"start": 2967,
"end": 71094
} | class ____(_BaseTestCase):
opset_version = None
def test_is_in_onnx_export(self):
test_self = self
class MyModule(torch.nn.Module):
def forward(self, x):
test_self.assertTrue(torch.onnx.is_in_onnx_export())
raise ValueError
return x +... | TestUtilityFuns |
python | huggingface__transformers | tests/models/instructblip/test_processing_instructblip.py | {
"start": 902,
"end": 1579
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = InstructBlipProcessor
@classmethod
def _setup_tokenizer(cls):
tokenizer_class = cls._get_component_class_from_processor("tokenizer")
return tokenizer_class.from_pretrained("hf-internal-testing/tiny-random-GPT2Model")
... | InstructBlipProcessorTest |
python | astropy__astropy | astropy/units/tests/test_quantity_non_ufuncs.py | {
"start": 2602,
"end": 2883
} | class ____(BasicTestSetup):
def check(self, func, *args, **kwargs):
o = func(self.q, *args, **kwargs)
expected = func(self.q.value, *args, **kwargs) * self.q.unit
assert o.shape == expected.shape
assert np.all(o == expected)
| InvariantUnitTestSetup |
python | pyca__cryptography | src/cryptography/x509/certificate_transparency.py | {
"start": 315,
"end": 398
} | class ____(utils.Enum):
X509_CERTIFICATE = 0
PRE_CERTIFICATE = 1
| LogEntryType |
python | pydata__xarray | xarray/tests/test_ufuncs.py | {
"start": 5978,
"end": 6411
} | class ____(np.ndarray):
# Minimal subclassed duck array with its own self-contained namespace,
# which implements a few ufuncs
def __new__(cls, array):
obj = np.asarray(array).view(cls)
return obj
def __array_namespace__(self, *, api_version=None):
return DuckArray
@staticm... | DuckArray |
python | tensorflow__tensorflow | tensorflow/python/tpu/topology_test.py | {
"start": 808,
"end": 1535
} | class ____(test.TestCase):
def testSerialization(self):
"""Tests if the class is able to generate serialized strings."""
original_topology = topology.Topology(
mesh_shape=[1, 1, 1, 2],
device_coordinates=[[[0, 0, 0, 0], [0, 0, 0, 1]]],
)
serialized_str = original_topology.serialized()... | TopologyTest |
python | sqlalchemy__sqlalchemy | test/sql/test_metadata.py | {
"start": 168068,
"end": 182909
} | class ____(fixtures.TestBase):
@contextmanager
def _fixture(self):
from sqlalchemy.engine.default import DefaultDialect
class ParticipatingDialect(DefaultDialect):
construct_arguments = [
(schema.Index, {"x": 5, "y": False, "z_one": None}),
(schema.Fo... | DialectKWArgTest |
python | encode__django-rest-framework | tests/test_model_serializer.py | {
"start": 39936,
"end": 40184
} | class ____(models.Model):
text = models.CharField(max_length=100)
bar = models.ForeignKey(
'Issue7550BarModel', null=True, blank=True, on_delete=models.SET_NULL,
related_name='foos', related_query_name='foo')
| Issue7550FooModel |
python | walkccc__LeetCode | solutions/288. Unique Word Abbreviation/288.py | {
"start": 0,
"end": 556
} | class ____:
def __init__(self, dictionary: list[str]):
self.dict = set(dictionary)
# T := unique, F := not unique
self.abbrUnique = {}
for word in self.dict:
abbr = self._getAbbr(word)
self.abbrUnique[abbr] = abbr not in self.abbrUnique
def isUnique(self, word: str) -> bool:
abbr =... | ValidWordAbbr |
python | PyCQA__pylint | tests/functional/s/slots_checks.py | {
"start": 2236,
"end": 2298
} | class ____:
__slots__ = Good.__slots__
| PotentiallyFourthGood |
python | PrefectHQ__prefect | tests/server/models/test_block_registration.py | {
"start": 2682,
"end": 3876
} | class ____:
async def test_register_new_block_type(self, session):
read_block_type = await read_block_type_by_slug(
session, block_type_slug="secret"
)
assert read_block_type is None
registered_block_type_id = await register_block_type(
session=session, block... | TestRegisterBlockType |
python | apache__airflow | providers/sftp/src/airflow/providers/sftp/decorators/sensors/sftp.py | {
"start": 1037,
"end": 2882
} | class ____(SFTPSensor):
"""
Wraps a Python callable and captures args/kwargs when called for execution.
:param python_callable: A reference to an object that is callable
:param task_id: task Id
:param op_args: a list of positional arguments that will get unpacked when
calling your callable ... | _DecoratedSFTPSensor |
python | numba__numba | numba/tests/test_typeinfer.py | {
"start": 30223,
"end": 30871
} | class ____(unittest.TestCase):
"""
Make sure partial typing stores type errors in compiler state properly
"""
def test_partial_typing_error(self):
# example with type unification error
def impl(flag):
if flag:
a = 1
else:
a = str(1)... | TestPartialTypingErrors |
python | numpy__numpy | numpy/matrixlib/tests/test_matrix_linalg.py | {
"start": 1480,
"end": 1538
} | class ____(SVDCases, MatrixTestCase):
pass
| TestSVDMatrix |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ViewBox/ViewBoxMenu.py | {
"start": 200,
"end": 9283
} | class ____(QtWidgets.QMenu):
def __init__(self, view):
QtWidgets.QMenu.__init__(self)
self.view = weakref.ref(view) ## keep weakref to view to avoid circular reference (don't know why, but this prevents the ViewBox from being collected)
self.valid = False ## tells us whether the u... | ViewBoxMenu |
python | kamyu104__LeetCode-Solutions | Python/separate-the-digits-in-an-array.py | {
"start": 44,
"end": 429
} | class ____(object):
def separateDigits(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = []
for x in reversed(nums):
while x:
result.append(x%10)
x //= 10
result.reverse()
return result
... | Solution |
python | sympy__sympy | sympy/polys/domains/simpledomain.py | {
"start": 150,
"end": 377
} | class ____(Domain[Er]):
"""Base class for simple domains, e.g. ZZ, QQ. """
is_Simple = True
def inject(self, *gens):
"""Inject generators into this domain. """
return self.poly_ring(*gens)
| SimpleDomain |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/repository_definition/repository_data.py | {
"start": 1794,
"end": 7428
} | class ____(ABC):
"""Users should usually rely on the :py:func:`@repository <repository>` decorator to create new
repositories, which will in turn call the static constructors on this class. However, users may
subclass :py:class:`RepositoryData` for fine-grained control over access to and lazy creation
o... | RepositoryData |
python | run-llama__llama_index | llama-index-core/llama_index/core/postprocessor/pii.py | {
"start": 3552,
"end": 5323
} | class ____(BaseNodePostprocessor):
"""
NER PII Node processor.
Uses a HF transformers model.
"""
pii_node_info_key: str = "__pii_node_info__"
@classmethod
def class_name(cls) -> str:
return "NERPIINodePostprocessor"
def mask_pii(self, ner: Callable, text: str) -> Tuple[str, ... | NERPIINodePostprocessor |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 6006,
"end": 6068
} | class ____(BinOp):
pass
@infer_global(operator.mul)
| BinOpSub |
python | PyCQA__pylint | tests/test_check_parallel.py | {
"start": 1950,
"end": 2700
} | class ____(BaseRawFileChecker):
"""A checker that does not need to consolidate data across run invocations."""
name = "sequential-checker"
test_data = "sequential"
msgs = {
"R9999": (
"Test",
"sequential-test-check",
"Some helpful text.",
)
}
... | SequentialTestChecker |
python | django__django | tests/test_utils/tests.py | {
"start": 13087,
"end": 15662
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.person_pk = str(Person.objects.create(name="test").pk)
cls.url = f"/test_utils/get_person/{cls.person_pk}/"
def test_simple(self):
with CaptureQueriesContext(connection) as captured_queries:
Person.objects.ge... | CaptureQueriesContextManagerTests |
python | doocs__leetcode | solution/2500-2599/2541.Minimum Operations to Make Array Equal II/Solution.py | {
"start": 0,
"end": 425
} | class ____:
def minOperations(self, nums1: List[int], nums2: List[int], k: int) -> int:
ans = x = 0
for a, b in zip(nums1, nums2):
if k == 0:
if a != b:
return -1
continue
if (a - b) % k:
return -1
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/number-of-days-between-two-dates.py | {
"start": 819,
"end": 1054
} | class ____(object):
def daysBetweenDates(self, date1, date2):
delta = datetime.datetime.strptime(date1, "%Y-%m-%d")
delta -= datetime.datetime.strptime(date2, "%Y-%m-%d")
return abs(delta.days)
| Solution2 |
python | pallets__werkzeug | src/werkzeug/middleware/lint.py | {
"start": 3567,
"end": 3876
} | class ____:
def __init__(self, write: t.Callable[[bytes], object], chunks: list[int]) -> None:
self._write = write
self._chunks = chunks
def __call__(self, s: bytes) -> None:
check_type("write()", s, bytes)
self._write(s)
self._chunks.append(len(s))
| GuardedWrite |
python | pypa__pip | src/pip/_vendor/packaging/_parser.py | {
"start": 610,
"end": 691
} | class ____(Node):
def serialize(self) -> str:
return str(self)
| Variable |
python | Lightning-AI__lightning | src/lightning/fabric/utilities/distributed.py | {
"start": 16023,
"end": 17311
} | class ____:
"""A barrier with an infinite timeout.
Creates a new process group with the GLOO backend with a very high timeout that makes the barrier effectively wait
forever. This is useful in cases where you want to execute a long-running operation on a subset of ranks that should
not be subject to th... | _InfiniteBarrier |
python | google__jax | tests/buffer_callback_test.py | {
"start": 831,
"end": 6529
} | class ____(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if jtu.test_device_matches(["tpu"]):
self.skipTest("Not supported on TPU.")
@parameterized.parameters(jtu.dtypes.all)
@jtu.run_on_devices("cpu")
def test_numpy(self, dtype):
def callback(ctx, out, arg):
with self.assertRaise... | BufferCallbackTest |
python | ray-project__ray | python/ray/train/v2/_internal/execution/worker_group/worker.py | {
"start": 3699,
"end": 8649
} | class ____:
def __init__(self):
self._callbacks: List[WorkerCallback] = []
def execute(self, fn: Callable[..., T], *fn_args, **fn_kwargs) -> T:
return fn(*fn_args, **fn_kwargs)
def run_train_fn(self, train_fn_ref: ObjectRefWrapper[Callable[[], None]]):
"""Run the training function ... | RayTrainWorker |
python | wepe__MachineLearning | Ridge/kernel_ridge/kernel_ridge.py | {
"start": 94,
"end": 2611
} | class ____():
"""
Simple implementation of a Kernel Ridge Regression using the
closed form for training.
Doc: https://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf
"""
def __init__(self, kernel_type='linear', C=1.0, gamma=5.0):
"""
:param kernel_t... | KernelRidge |
python | walkccc__LeetCode | solutions/710. Random Pick with Blacklist/710.py | {
"start": 0,
"end": 590
} | class ____:
def __init__(self, n: int, blacklist: list[int]):
self.validRange = n - len(blacklist)
self.dict = {}
maxAvailable = n - 1
for b in blacklist:
self.dict[b] = -1
for b in blacklist:
if b < self.validRange:
# Find the slot that haven't been used.
while maxA... | Solution |
python | PyCQA__pylint | tests/functional/t/too/too_few_public_methods.py | {
"start": 62,
"end": 260
} | class ____: # [too-few-public-methods]
def __init__(self):
pass
def meth1(self):
print(self)
def _dontcount(self):
print(self)
# Don't emit for these cases.
| Aaaa |
python | mitsuhiko__rye | rye-devtools/src/rye_devtools/common.py | {
"start": 626,
"end": 2246
} | class ____(NamedTuple):
major: int
minor: int
patch: int
@classmethod
def from_str(cls, version: str) -> Self:
major, minor, patch = version.split(".", 3)
return cls(int(major), int(minor), int(patch))
def __str__(self) -> str:
return f"{self.major}.{self.minor}.{self.p... | Version |
python | sympy__sympy | sympy/plotting/series.py | {
"start": 57667,
"end": 61824
} | class ____(Line2DBaseSeries):
is_parametric = True
def _set_parametric_line_label(self, label):
"""Logic to set the correct label to be shown on the plot.
If `use_cm=True` there will be a colorbar, so we show the parameter.
If `use_cm=False`, there might be a legend, so we show the expr... | ParametricLineBaseSeries |
python | PrefectHQ__prefect | tests/server/models/test_variables.py | {
"start": 1411,
"end": 3085
} | class ____:
async def test_create_variable(
self,
session,
):
current_time = now("UTC")
variable = VariableCreate(
name="my_variable", value="my-value", tags=["123", "456"]
)
model = await create_variable(session, variable)
await session.commi... | TestCreateVariable |
python | numba__llvmlite | setup.py | {
"start": 2492,
"end": 2908
} | class ____(build_ext):
def run(self):
build_ext.run(self)
build_library_files(self.dry_run)
# HACK: this makes sure the library file (which is large) is only
# included in binary builds, not source builds.
from llvmlite.utils import get_library_files
self.distributio... | LlvmliteBuildExt |
python | aimacode__aima-python | csp.py | {
"start": 37146,
"end": 42234
} | class ____:
"""Solves a CSP with arc consistency and domain splitting"""
def __init__(self, csp):
"""a CSP solver that uses arc consistency
* csp is the CSP to be solved
"""
self.csp = csp
def GAC(self, orig_domains=None, to_do=None, arc_heuristic=sat_up):
"""
... | ACSolver |
python | pandas-dev__pandas | pandas/tests/generic/test_duplicate_labels.py | {
"start": 7471,
"end": 13580
} | class ____:
@pytest.mark.parametrize(
"cls, axes",
[
(pd.Series, {"index": ["a", "a"], "dtype": float}),
(pd.DataFrame, {"index": ["a", "a"]}),
(pd.DataFrame, {"index": ["a", "a"], "columns": ["b", "b"]}),
(pd.DataFrame, {"columns": ["b", "b"]}),
... | TestRaises |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/optimization/test_manual_optimization.py | {
"start": 20030,
"end": 25093
} | class ____(BoringModel):
def __init__(self):
super().__init__()
self.automatic_optimization = False
def loss_ones(self, batch, prediction):
# An arbitrary loss to have a loss that updates the model weights during `Trainer.fit` calls
return torch.nn.functional.mse_loss(prediction... | TesManualOptimizationDDPModel |
python | numpy__numpy | numpy/_core/tests/test_cpu_features.py | {
"start": 1671,
"end": 3923
} | class ____:
features = []
features_groups = {}
features_map = {}
features_flags = set()
def load_flags(self):
# a hook
pass
def test_features(self):
self.load_flags()
for gname, features in self.features_groups.items():
test_features = [self.cpu_have... | AbstractTest |
python | astropy__astropy | astropy/nddata/utils.py | {
"start": 16358,
"end": 34739
} | class ____:
"""
Create a cutout object from a 2D array.
The returned object will contain a 2D cutout array. If
``copy=False`` (default), the cutout array is a view into the
original ``data`` array, otherwise the cutout array will contain a
copy of the original data.
If a `~astropy.wcs.WCS... | Cutout2D |
python | PyCQA__pylint | tests/functional/n/name/name_preset_snake_case.py | {
"start": 607,
"end": 702
} | class ____(Enum): # [invalid-name]
const_with_snake_case = 42
another_const = 43
| FooEnum |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/testing/codegen.py | {
"start": 1905,
"end": 1996
} | class ____(NodeSampler):
sample_map = dict(((gast.USub, 1), (gast.UAdd, 0)))
| UnaryOpSampler |
python | langchain-ai__langchain | libs/core/langchain_core/output_parsers/pydantic.py | {
"start": 433,
"end": 4464
} | class ____(JsonOutputParser, Generic[TBaseModel]):
"""Parse an output using a Pydantic model."""
pydantic_object: Annotated[type[TBaseModel], SkipValidation()]
"""The Pydantic model to parse."""
def _parse_obj(self, obj: dict) -> TBaseModel:
try:
if issubclass(self.pydantic_object,... | PydanticOutputParser |
python | redis__redis-py | tests/test_pubsub.py | {
"start": 23503,
"end": 29434
} | class ____:
"These tests only validate that we get unicode values back"
channel = "uni" + chr(4456) + "code"
pattern = "uni" + chr(4456) + "*"
data = "abc" + chr(4458) + "123"
def make_message(self, type, channel, data, pattern=None):
return {"type": type, "channel": channel, "pattern": pa... | TestPubSubAutoDecoding |
python | jmcnamara__XlsxWriter | xlsxwriter/test/vml/test_write_shapetype.py | {
"start": 289,
"end": 1442
} | class ____(unittest.TestCase):
"""
Test the Vml _write_shapetype() method.
"""
def setUp(self):
self.fh = StringIO()
self.vml = Vml()
self.vml._set_filehandle(self.fh)
def test_write_comment_shapetype(self):
"""Test the _write_comment_shapetype() method"""
... | TestWriteVshapetype |
python | mlflow__mlflow | mlflow/genai/scorers/registry.py | {
"start": 637,
"end": 1180
} | class ____(MlflowException):
"""Exception thrown when building a scorer store with an unsupported URI"""
def __init__(self, unsupported_uri, supported_uri_schemes):
message = (
f"Scorer registration functionality is unavailable; got unsupported URI"
f" '{unsupported_uri}' for sc... | UnsupportedScorerStoreURIException |
python | pytorch__pytorch | test/distributed/checkpoint/_experimental/test_checkpointer.py | {
"start": 16273,
"end": 25248
} | class ____(TestCase):
"""Tests specific to AsyncCheckpointer functionality."""
def setUp(self):
super().setUp()
# Create a temporary directory for checkpoints
self.temp_dir = tempfile.mkdtemp()
# Create real objects for testing
self.rank_info = RankInfo(
glo... | TestAsyncCheckpointerSpecific |
python | huggingface__transformers | src/transformers/models/sam3/modeling_sam3.py | {
"start": 86647,
"end": 100914
} | class ____(Sam3PreTrainedModel):
input_modalities = ["image", "text"]
_checkpoint_conversion_mapping = {
r"detector_model.(.+)": r"\1" # the regex allows to remove the prefix, and add it back in revert mode
}
_keys_to_ignore_on_load_unexpected = [
r"^tracker_model.",
r"^tracker_... | Sam3Model |
python | getsentry__sentry-python | sentry_sdk/integrations/loguru.py | {
"start": 679,
"end": 1481
} | class ____(enum.IntEnum):
TRACE = 5
DEBUG = 10
INFO = 20
SUCCESS = 25
WARNING = 30
ERROR = 40
CRITICAL = 50
DEFAULT_LEVEL = LoggingLevels.INFO.value
DEFAULT_EVENT_LEVEL = LoggingLevels.ERROR.value
SENTRY_LEVEL_FROM_LOGURU_LEVEL = {
"TRACE": "DEBUG",
"DEBUG": "DEBUG",
"INFO": ... | LoggingLevels |
python | gevent__gevent | src/greentest/3.11/test_socket.py | {
"start": 201450,
"end": 204677
} | class ____(unittest.TestCase):
class MockSocket(socket.socket):
def connect(self, *args):
raise TimeoutError('timed out')
@contextlib.contextmanager
def mocked_socket_module(self):
"""Return a socket which times out on connect"""
old_socket = socket.socket
socke... | NetworkConnectionNoServer |
python | openai__openai-python | src/openai/types/evals/run_cancel_response.py | {
"start": 6798,
"end": 7166
} | class ____(BaseModel):
template: List[DataSourceResponsesInputMessagesTemplateTemplate]
"""A list of chat messages forming the prompt or context.
May include variable references to the `item` namespace, ie {{item.name}}.
"""
type: Literal["template"]
"""The type of input messages. Always `temp... | DataSourceResponsesInputMessagesTemplate |
python | Textualize__textual | src/textual/timer.py | {
"start": 916,
"end": 6255
} | class ____:
"""A class to send timer-based events.
Args:
event_target: The object which will receive the timer events.
interval: The time between timer events, in seconds.
name: A name to assign the event (for debugging).
callback: An optional callback to invoke when the event i... | Timer |
python | PrefectHQ__prefect | src/prefect/server/database/dependencies.py | {
"start": 1315,
"end": 6329
} | class ____(TypedDict):
database_config: Optional[BaseDatabaseConfiguration]
query_components: Optional["BaseQueryComponents"]
orm: Optional["BaseORMConfiguration"]
interface_class: Optional[type["PrefectDBInterface"]]
MODELS_DEPENDENCIES: _ModelDependencies = {
"database_config": None,
"query_... | _ModelDependencies |
python | viewflow__viewflow | viewflow/workflow/flow/views/create.py | {
"start": 1238,
"end": 1736
} | class ____(
FormLayoutMixin,
FormAjaxCompleteMixin,
FormDependentSelectMixin,
mixins.SuccessMessageMixin,
mixins.TaskSuccessUrlMixin,
mixins.TaskViewTemplateNames,
generic.CreateView,
):
template_filename = "start.html"
def form_valid(self, form):
self.object = form.save()
... | CreateArtifactView |
python | plotly__plotly.py | plotly/graph_objs/treemap/marker/colorbar/title/_font.py | {
"start": 233,
"end": 9949
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "treemap.marker.colorbar.title"
_path_str = "treemap.marker.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Font |
python | modin-project__modin | asv_bench/benchmarks/io/csv.py | {
"start": 2721,
"end": 5065
} | class ____:
shapes = get_benchmark_shapes("TimeReadCsvNamesDtype")
_dtypes_params = ["Int64", "Int64_Timestamp"]
_timestamp_columns = ["col1", "col2"]
param_names = ["shape", "names", "dtype"]
params = [
shapes,
["array-like"],
_dtypes_params,
]
def _get_file_id(sel... | TimeReadCsvNamesDtype |
python | google__jax | tests/sourcemap_test.py | {
"start": 739,
"end": 2366
} | class ____(jtu.JaxTestCase):
@parameterized.parameters(
(0,),
(1,),
(2,),
(3,),
(4,),
(5,),
(-1,),
(-2,),
(-3,),
(-4,),
(123,),
(456,),
(1024,),
(1025,),
(2**16,),
(2**31 - 1,),
)
def test_roundtrip_vlq(self, value):
... | SourceMapTest |
python | huggingface__transformers | src/transformers/models/qwen2/modeling_qwen2.py | {
"start": 11909,
"end": 12679
} | class ____(nn.Module):
def __init__(self, hidden_size, eps: float = 1e-6) -> None:
"""
Qwen2RMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states... | Qwen2RMSNorm |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.