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 | Pylons__pyramid | docs/quick_tutorial/views/tutorial/tests.py | {
"start": 673,
"end": 1126
} | class ____(unittest.TestCase):
def setUp(self):
from tutorial import main
app = main({})
from webtest import TestApp
self.testapp = TestApp(app)
def test_home(self):
res = self.testapp.get('/', status=200)
self.assertIn(b'<body>Visit', res.body)
def test_he... | TutorialFunctionalTests |
python | huggingface__transformers | tests/models/seggpt/test_image_processing_seggpt.py | {
"start": 3543,
"end": 13419
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = SegGptImageProcessor if is_vision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester = SegGptImageProcessingTester(self)
@property
def image_processor_dict(self):
r... | SegGptImageProcessingTest |
python | Delgan__loguru | loguru/_logger.py | {
"start": 8531,
"end": 102542
} | class ____:
"""An object to dispatch logging messages to configured handlers.
The |Logger| is the core object of ``loguru``, every logging configuration and usage pass
through a call to one of its methods. There is only one logger, so there is no need to retrieve
one before usage.
Once the ``logge... | Logger |
python | ray-project__ray | python/ray/autoscaler/v2/autoscaler.py | {
"start": 1870,
"end": 8918
} | class ____:
def __init__(
self,
session_name: str,
config_reader: IConfigReader,
gcs_client: GcsClient,
event_logger: Optional[AutoscalerEventLogger] = None,
metrics_reporter: Optional[AutoscalerMetricsReporter] = None,
) -> None:
"""
Args:
... | Autoscaler |
python | pytorch__pytorch | test/inductor/test_codecache.py | {
"start": 106180,
"end": 107619
} | class ____(TestCase):
@requires_cuda_and_triton
def test_cuda_compile_command(self):
cmd_no_extra_args: str = cuda_compile_command(
["abc.cu", "def.cu"], "output", "so"
)
assert "nvcc " in cmd_no_extra_args, cmd_no_extra_args
assert "abc.cu" in cmd_no_extra_args, cmd_... | TestCudaCompileCommand |
python | ZoranPandovski__al-go-rithms | data_structures/Graphs/graphsearch/transitive_closure_graph/python/transitive_closure_graph.py | {
"start": 171,
"end": 1416
} | class ____:
def __init__(self,vertices):
# No. of vertices
self.V= vertices
# default dictionary to store graph
self.graph= defaultdict(list)
# To store transitive closure
self.tc = [[0 for j in range(self.V)] for i in range(self.V)]
# function to add an ed... | Graph |
python | pandas-dev__pandas | asv_bench/benchmarks/tslibs/fields.py | {
"start": 162,
"end": 783
} | class ____:
params = [
_sizes,
["seconds", "microseconds", "nanoseconds"],
]
param_names = ["size", "field"]
def setup(self, size, field):
arr = np.random.randint(0, 10, size=size, dtype="i8")
self.i8data = arr
arr = np.random.randint(-86400 * 1_000_000_000, 0, s... | TimeGetTimedeltaField |
python | nedbat__coveragepy | tests/test_annotate.py | {
"start": 349,
"end": 3784
} | class ____(CoverageTest):
"""Test the annotate feature with gold files."""
def make_multi(self) -> None:
"""Make a few source files we need for the tests."""
self.make_file(
"multi.py",
"""\
import a.a
import b.b
a.a.a(1)
... | AnnotationGoldTest |
python | bokeh__bokeh | src/bokeh/models/widgets/tables.py | {
"start": 19529,
"end": 19762
} | class ____(CellEditor):
''' Spinner-based time cell editor.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| TimeEditor |
python | falconry__falcon | tests/_inspect_fixture.py | {
"start": 1144,
"end": 1323
} | class ____:
def process_request(self, *args):
pass
def process_resource(self, *args):
pass
def process_response(self, *args):
pass
| MyMiddleware |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fragments.py | {
"start": 1479,
"end": 1660
} | class ____(GQLResult):
typename__: Typename[Literal["ArtifactSequence"]] = "ArtifactSequence"
name: str
project: Optional[ProjectInfoFragment]
| SourceCollectionInfoFragment |
python | astropy__astropy | astropy/utils/masked/tests/test_functions.py | {
"start": 14258,
"end": 14497
} | class ____(MaskedUfuncTests, QuantitySetup):
def test_ufunc_inplace_error2(self):
out = Masked(np.zeros(self.ma.shape))
with pytest.raises(TypeError):
np.add(self.ma, self.mb, out=out)
| TestMaskedQuantityUfuncs |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/mwaa.py | {
"start": 1452,
"end": 7694
} | class ____(AwsBaseSensor[MwaaHook]):
"""
Waits for a DAG Run in an MWAA Environment to complete.
If the DAG Run fails, an AirflowException is thrown.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:MwaaDagRunSensor`
:param ... | MwaaDagRunSensor |
python | numpy__numpy | benchmarks/benchmarks/bench_ufunc_strides.py | {
"start": 4499,
"end": 4700
} | class ____(_AbstractBinary):
arrlen = 100000
params = [
[np.maximum, np.minimum],
[1, 2], [1, 2], [1, 2],
['b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q']
]
| BinaryInt |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_compat.py | {
"start": 2966,
"end": 3772
} | class ____:
a: list
b: tuple
c: namedtuple
d: dict
e: defaultdict
def test_dataclass_asdict():
ANamedTuple = namedtuple("ANamedTuple", ("with_some_field"))
e = defaultdict(list)
e["a"].append(1)
obj = FilledWithStuff(a=[1], b=(2), c=ANamedTuple(3), d={4: 5}, e=e)
assert datacla... | FilledWithStuff |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/base_env.py | {
"start": 18998,
"end": 19562
} | class ____(NamedTuple):
"""
A NamedTuple containing information about the observation and action
spaces for a group of Agents under the same behavior.
- observation_specs is a List of ObservationSpec NamedTuple containing
information about the information of the Agent's observations such as their sh... | BehaviorSpec |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/request_builder.py | {
"start": 661,
"end": 1616
} | class ____:
def __init__(self, resource: str = None, api="client_center") -> None:
self._query_params = {}
self._body = None
self.resource = resource
if api == "client_center":
self._api = CLIENT_CENTER_BASE_URL
elif api == "bulk":
self._api = BULK_BAS... | RequestBuilder |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/analyzer_cli_test.py | {
"start": 78874,
"end": 81951
} | class ____(test_util.TensorFlowTestCase):
@classmethod
def setUpClass(cls):
cls._dump_root = tempfile.mkdtemp()
with session.Session(config=no_rewrite_session_config()) as sess:
loop_var = constant_op.constant(0, name="while_loop_test/loop_var")
cond = lambda loop_var: math_ops.less(loop_var, ... | AnalyzerCLIWhileLoopTest |
python | Pylons__pyramid | tests/test_events.py | {
"start": 11036,
"end": 11339
} | class ____:
def __init__(self):
self.subscribed = []
def add_subscriber(self, wrapped, ifaces, **predicates):
if not predicates:
self.subscribed.append((wrapped, ifaces))
else:
self.subscribed.append((wrapped, ifaces, predicates))
| DummyConfigurator |
python | django__django | django/core/mail/backends/dummy.py | {
"start": 110,
"end": 234
} | class ____(BaseEmailBackend):
def send_messages(self, email_messages):
return len(list(email_messages))
| EmailBackend |
python | jazzband__pip-tools | piptools/build.py | {
"start": 1225,
"end": 12519
} | class ____:
extras: tuple[str, ...]
requirements: tuple[InstallRequirement, ...]
build_requirements: tuple[InstallRequirement, ...]
def maybe_statically_parse_project_metadata(
src_file: pathlib.Path,
) -> StaticProjectMetadata | None:
"""
Return the metadata for a project, if it can be static... | ProjectMetadata |
python | allegroai__clearml | clearml/backend_config/environment.py | {
"start": 150,
"end": 1240
} | class ____(Entry):
@classmethod
def default_conversions(cls) -> Dict[Any, Callable[[str], Any]]:
conversions = super(EnvEntry, cls).default_conversions().copy()
conversions[bool] = text_to_bool
return conversions
def __init__(self, key: str, *more_keys: Any, **kwargs: Any) -> None:
... | EnvEntry |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/skip_test.py | {
"start": 3273,
"end": 5513
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(index=[-1, 2, 3])))
def testInvalidIndex(self, index):
dataset = dataset_ops.Dataset.range(10).skip(8)
with se... | SkipRandomAccessTest |
python | tornadoweb__tornado | tornado/test/httpserver_test.py | {
"start": 11196,
"end": 11434
} | class ____(PostEchoHandler):
def decode_argument(self, value, name=None):
try:
return value.decode("gbk")
except Exception:
raise HTTPError(400, "invalid gbk bytes: %r" % value)
| PostEchoGBKHandler |
python | ray-project__ray | python/ray/air/util/tensor_extensions/arrow.py | {
"start": 25459,
"end": 25712
} | class ____(pa.ExtensionScalar):
def as_py(self, **kwargs) -> np.ndarray:
return self.__array__()
def __array__(self) -> np.ndarray:
return self.type._extension_scalar_to_ndarray(self)
@PublicAPI(stability="beta")
| ArrowTensorScalar |
python | davidhalter__jedi | test/test_api/test_interpreter.py | {
"start": 23553,
"end": 26151
} | class ____:
its_me = 1
@pytest.mark.parametrize('class_is_findable', [False, True])
def test_try_to_use_return_annotation_for_property(class_is_findable):
class WithProperties(object):
@property
def with_annotation1(self) -> str:
raise BaseException
@property
def w... | Hello |
python | getsentry__sentry | tests/sentry/middleware/test_ratelimit_middleware.py | {
"start": 14576,
"end": 17301
} | class ____(APITestCase):
endpoint = "ratelimit-header-endpoint"
def test_header_counts(self) -> None:
"""Ensure that the header remainder counts decrease properly"""
with freeze_time("2000-01-01"):
expected_reset_time = int(time() + 100)
response = self.get_success_respo... | TestRatelimitHeader |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 645207,
"end": 645789
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("TeamEdge"), graphql_name="edges")
nodes = sgqlc.types.Field(sgqlc.type... | TeamConnection |
python | huggingface__transformers | src/transformers/models/qwen3/modeling_qwen3.py | {
"start": 23592,
"end": 23965
} | class ____(GenericForQuestionAnswering, Qwen3PreTrainedModel):
base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
__all__ = [
"Qwen3ForCausalLM",
"Qwen3ForQuestionAnswering",
"Qwen3PreTrainedModel",
"Qwen3Model",
"Qwen3ForSequenceClassification",
"... | Qwen3ForQuestionAnswering |
python | pypa__pipenv | pipenv/exceptions.py | {
"start": 4835,
"end": 5683
} | class ____(FileError):
formatted_message = "{} {{}} {{}}".format("[bold red]ERROR:[/bold red]")
def __init__(self, filename, message=None, **kwargs):
extra = kwargs.pop("extra", [])
if not message:
message = "[bold]Please ensure that the file exists![/bold]"
message = self.f... | PipenvFileError |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 277346,
"end": 300771
} | class ____(VegaLiteSchema):
"""
Config schema wrapper.
Parameters
----------
arc : dict, :class:`RectConfig`
Arc-specific Config
area : dict, :class:`AreaConfig`
Area-Specific Config
aria : bool
A boolean flag indicating if ARIA default attributes should be included ... | Config |
python | pyca__cryptography | tests/hazmat/primitives/test_x448.py | {
"start": 1319,
"end": 12531
} | class ____:
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "X448", "rfc7748.txt"),
load_nist_vectors,
),
)
def test_rfc7748(self, vector, backend):
private = binascii.unhexlify(vector["input_scalar"])
pub... | TestX448Exchange |
python | python-pillow__Pillow | src/PIL/ImageFilter.py | {
"start": 7853,
"end": 8036
} | class ____(BuiltinFilter):
name = "Contour"
# fmt: off
filterargs = (3, 3), 1, 255, (
-1, -1, -1,
-1, 8, -1,
-1, -1, -1,
)
# fmt: on
| CONTOUR |
python | falconry__falcon | tests/test_httperror.py | {
"start": 36288,
"end": 36515
} | class ____(AsyncOnlyMediaHandler):
def serialize(self, media, content_type=None):
assert media == {'title': '410 Gone'}
return b'this is sync instead'
_serialize_sync = serialize
| SyncInterfaceMediaHandler |
python | chroma-core__chroma | chromadb/utils/embedding_functions/text2vec_embedding_function.py | {
"start": 213,
"end": 3081
} | class ____(EmbeddingFunction[Documents]):
"""
This class is used to generate embeddings for a list of texts using the Text2Vec model.
"""
def __init__(self, model_name: str = "shibing624/text2vec-base-chinese"):
"""
Initialize the Text2VecEmbeddingFunction.
Args:
mo... | Text2VecEmbeddingFunction |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_ean.py | {
"start": 850,
"end": 1834
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.to_be_valid_ean"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(... | ColumnValuesToBeValidEan |
python | doocs__leetcode | solution/1100-1199/1182.Shortest Distance to Target Color/Solution.py | {
"start": 0,
"end": 730
} | class ____:
def shortestDistanceColor(
self, colors: List[int], queries: List[List[int]]
) -> List[int]:
n = len(colors)
right = [[inf] * 3 for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for j in range(3):
right[i][j] = right[i + 1][j]
... | Solution |
python | Netflix__metaflow | metaflow/plugins/argo/argo_workflows.py | {
"start": 206295,
"end": 207046
} | class ____(object):
# https://argoproj.github.io/argo-workflows/fields/#parameter
def __init__(self, name):
tree = lambda: defaultdict(tree)
self.payload = tree()
self.payload["name"] = name
def value(self, value):
self.payload["value"] = value
return self
def ... | Parameter |
python | dagster-io__dagster | python_modules/dagster/dagster/_daemon/sensor.py | {
"start": 4095,
"end": 27075
} | class ____(AbstractContextManager):
def __init__(
self,
remote_sensor: RemoteSensor,
tick: InstigatorTick,
instance: DagsterInstance,
logger: logging.Logger,
tick_retention_settings,
):
self._remote_sensor = remote_sensor
self._instance = instance
... | SensorLaunchContext |
python | huggingface__transformers | src/transformers/models/align/modeling_align.py | {
"start": 41172,
"end": 48812
} | class ____(AlignPreTrainedModel):
config: AlignConfig
def __init__(self, config: AlignConfig):
super().__init__(config)
if not isinstance(config.text_config, AlignTextConfig):
raise TypeError(
"config.text_config is expected to be of type AlignTextConfig but is of t... | AlignModel |
python | pyca__cryptography | tests/hazmat/primitives/test_pkcs12.py | {
"start": 10948,
"end": 27466
} | class ____:
@pytest.mark.parametrize(
(
"kgenerator",
"ktype",
"kparam",
),
[
pytest.param(
ed448.Ed448PrivateKey.generate,
ed448.Ed448PrivateKey,
[],
marks=pytest.mark.supported(
... | TestPKCS12Creation |
python | huggingface__transformers | tests/models/mbart/test_tokenization_mbart.py | {
"start": 1181,
"end": 2974
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "facebook/mbart-large-en-ro"
tokenizer_class = MBartTokenizer
integration_expected_tokens = ['▁This', '▁is', '▁a', '▁test', '▁', '😊', '▁I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fals', 'é', '.', '▁', '... | MBartTokenizationTest |
python | ray-project__ray | rllib/core/rl_module/torch/torch_compile_config.py | {
"start": 65,
"end": 1601
} | class ____:
"""Configuration options for RLlib's usage of torch.compile in RLModules.
# On `torch.compile` in Torch RLModules
`torch.compile` invokes torch's dynamo JIT compiler that can potentially bring
speedups to RL Module's forward methods.
This is a performance optimization that should be dis... | TorchCompileConfig |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 135985,
"end": 137258
} | class ____(Request):
"""
Convert public projects to private
:param ids: Ids of the projects to convert. Only the projects originated by the
company can be converted
:type ids: Sequence[str]
"""
_service = "projects"
_action = "make_private"
_version = "2.20"
_schema = {
... | MakePrivateRequest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/source_salesforce/streams.py | {
"start": 38475,
"end": 42375
} | class ____(RestSalesforceStream, CheckpointMixin, ABC):
state_checkpoint_interval = 500
_slice = None
def __init__(self, replication_key: str, stream_slice_step: str = "P30D", **kwargs):
self.replication_key = replication_key
super().__init__(**kwargs)
self._stream_slice_step = stre... | IncrementalRestSalesforceStream |
python | django__django | django/contrib/gis/db/models/functions.py | {
"start": 12203,
"end": 12254
} | class ____(GeomOutputGeoFunc):
arity = 1
| Envelope |
python | numpy__numpy | numpy/distutils/fcompiler/pg.py | {
"start": 1810,
"end": 3568
} | class ____(FCompiler):
compiler_type = 'flang'
description = 'Portland Group Fortran LLVM Compiler'
version_pattern = r'\s*(flang|clang) version (?P<version>[\d.-]+).*'
ar_exe = 'lib.exe'
possible_executables = ['flang']
executables = {
'version_cmd': ["<F77>", "--version"],
'c... | PGroupFlangCompiler |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 46501,
"end": 46902
} | class ____:
def test_bernoulli(self):
brn = special.bernoulli(5)
assert_allclose(brn, array([1.0000,
-0.5000,
0.1667,
0.0000,
-0.0333,
... | TestBernoulli |
python | numba__numba | numba/cuda/cudadecl.py | {
"start": 2356,
"end": 2485
} | class ____(ConcreteTemplate):
key = cuda.threadfence_block
cases = [signature(types.none)]
@register
| Cuda_threadfence_block |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-opensearch/llama_index/vector_stores/opensearch/base.py | {
"start": 1141,
"end": 35251
} | class ____:
"""
Object encapsulating an Opensearch index that has vector search enabled.
If the index does not yet exist, it is created during init.
Therefore, the underlying index is assumed to either:
1) not exist yet or 2) be created due to previous usage of this class.
Args:
endpoi... | OpensearchVectorClient |
python | eventlet__eventlet | tests/greendns_test.py | {
"start": 32586,
"end": 34005
} | class ____(tests.LimitedTestCase):
def _make_mock_getaliases(self):
class GetAliases:
aliases = ['cname.example.com']
def __call__(self, *args, **kwargs):
return self.aliases
getaliases = GetAliases()
return getaliases
def setUp(self):
... | TestGethostbyname_ex |
python | neetcode-gh__leetcode | python/0133-clone-graph.py | {
"start": 0,
"end": 407
} | class ____:
def cloneGraph(self, node: "Node") -> "Node":
oldToNew = {}
def dfs(node):
if node in oldToNew:
return oldToNew[node]
copy = Node(node.val)
oldToNew[node] = copy
for nei in node.neighbors:
copy.neighbors.ap... | Solution |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/session_debug_multi_gpu_test.py | {
"start": 1358,
"end": 3415
} | class ____(test_util.TensorFlowTestCase):
def setUp(self):
self._dump_root = tempfile.mkdtemp()
def tearDown(self):
ops.reset_default_graph()
# Tear down temporary dump directory.
if os.path.isdir(self._dump_root):
file_io.delete_recursively(self._dump_root)
def testMultiGPUSessionRun(se... | SessionDebugMultiGPUTest |
python | numba__numba | numba/tests/test_dictimpl.py | {
"start": 6042,
"end": 20038
} | class ____(TestCase):
def setUp(self):
"""Bind to the c_helper library and provide the ctypes wrapper.
"""
dict_t = ctypes.c_void_p
iter_t = ctypes.c_void_p
hash_t = ctypes.c_ssize_t
def wrap(name, restype, argtypes=()):
proto = ctypes.CFUNCTYPE(restype, ... | TestDictImpl |
python | bokeh__bokeh | src/bokeh/core/property/visual.py | {
"start": 3444,
"end": 3762
} | class ____(String):
def validate(self, value: Any, detail: bool = True) -> None:
super().validate(value, detail)
if not (isinstance(value, str) and CSS_LENGTH_RE.match(value)):
msg = "" if not detail else f"{value!r} is not a valid CSS length"
raise ValueError(msg)
| CSSLength |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_to_exist.py | {
"start": 2342,
"end": 12412
} | class ____(BatchExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectColumnToExist is a \
Batch Expectation.
BatchExpectations are one of the most common types of Expectation. They are evaluated for an entire Batch, and answer a semantic question about the Batch itself.
Args:
... | ExpectColumnToExist |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/core_tests/resource_tests/test_with_resources.py | {
"start": 19575,
"end": 20865
} | class ____(PickledObjectFilesystemIOManager):
def __init__(self):
super().__init__(base_dir="/tmp/dagster/foo-io-manager")
io_manager_resource_fn = lambda _: FooIoManager()
foo_io_manager_def = dg.IOManagerDefinition(
resource_fn=io_manager_resource_fn,
config_schema={},
)
def create_asset_job()... | FooIoManager |
python | lxml__lxml | doc/s5/ep2008/atom.py | {
"start": 8752,
"end": 9170
} | class ____(object):
def __get__(self, obj, type=None):
if obj is None:
return self
return parse_date(obj.text)
def __set__(self, obj, value):
if not value:
obj.text = None
return
if isinstance(value, datetime):
value = _strftime(va... | _date_text_property |
python | paramiko__paramiko | paramiko/agent.py | {
"start": 6658,
"end": 7798
} | class ____(AgentProxyThread):
"""
Class to be used when wanting to ask a remote SSH Agent
"""
def __init__(self, agent, chan):
AgentProxyThread.__init__(self, agent)
self.__chan = chan
def get_connection(self):
return self.__chan, None
def get_agent_connection():
"""
... | AgentRemoteProxy |
python | ray-project__ray | python/ray/tune/callback.py | {
"start": 2126,
"end": 11739
} | class ____(metaclass=_CallbackMeta):
"""Tune base callback that can be extended and passed to a ``TrialRunner``
Tune callbacks are called from within the ``TrialRunner`` class. There are
several hooks that can be used, all of which are found in the submethod
definitions of this base class.
The par... | Callback |
python | django-compressor__django-compressor | compressor/tests/test_filters.py | {
"start": 23579,
"end": 25221
} | class ____(TestCase):
"""
Test to check the Specializations of filters.
"""
def test_closure_filter(self):
filter = ClosureCompilerFilter("")
self.assertEqual(
filter.options,
(("binary", str("java -jar compiler.jar")), ("args", str(""))),
)
def test... | SpecializedFiltersTest |
python | crytic__slither | slither/tools/properties/properties/properties.py | {
"start": 483,
"end": 929
} | class ____(NamedTuple): # pylint: disable=inherit-non-class,too-few-public-methods
name: str
content: str
type: PropertyType
return_type: PropertyReturn
is_unit_test: bool
caller: PropertyCaller # Only for unit tests. Echidna will try all the callers
is_property_test: bool
description:... | Property |
python | scrapy__scrapy | scrapy/http/response/html.py | {
"start": 257,
"end": 300
} | class ____(TextResponse):
pass
| HtmlResponse |
python | pytorch__pytorch | torch/backends/cuda/__init__.py | {
"start": 1711,
"end": 2509
} | class ____:
r"""
Represent a specific plan cache for a specific `device_index`.
The attributes `size` and `max_size`, and method `clear`, can fetch and/ or
change properties of the C++ cuFFT plan cache.
"""
def __init__(self, device_index):
self.device_index = device_index
size = ... | cuFFTPlanCache |
python | pytorch__pytorch | torch/testing/_internal/opinfo/core.py | {
"start": 1693,
"end": 3688
} | class ____:
"""Describes which test, or type of tests, should be wrapped in the given
decorators when testing an operator. Any test that matches all provided
arguments will be decorated. The decorators will only be applied if the
active_if argument is True."""
__slots__ = [
"decorators",
... | DecorateInfo |
python | walkccc__LeetCode | solutions/1522. Diameter of N-Ary Tree/1522.py | {
"start": 0,
"end": 626
} | class ____:
def diameter(self, root: 'Node') -> int:
ans = 0
def maxDepth(root: 'Node') -> int:
"""Returns the maximum depth of the subtree rooted at `root`."""
nonlocal ans
maxSubDepth1 = 0
maxSubDepth2 = 0
for child in root.children:
maxSubDepth = maxDepth(child)
... | Solution |
python | django__django | tests/admin_views/models.py | {
"start": 4169,
"end": 4229
} | class ____(Color):
class Meta:
proxy = True
| Color2 |
python | langchain-ai__langchain | libs/langchain/tests/mock_servers/robot/server.py | {
"start": 1234,
"end": 1365
} | class ____(str, Enum):
"""The style of walking."""
normal = "normal"
casual = "casual"
energetic = "energetic"
| Style |
python | tartley__colorama | colorama/ansi.py | {
"start": 1789,
"end": 2321
} | class ____(AnsiCodes):
BLACK = 40
RED = 41
GREEN = 42
YELLOW = 43
BLUE = 44
MAGENTA = 45
CYAN = 46
WHITE = 47
RESET = 49
# These are fairly well supported, but not part of the standard.
... | AnsiBack |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/resources.py | {
"start": 28312,
"end": 32896
} | class ____(BaseAirbyteWorkspace):
"""This resource allows users to programatically interface with the Airbyte REST API to launch
syncs and monitor their progress for a given Airbyte workspace.
**Examples:**
Using OAuth client credentials:
.. code-block:: python
import dagster as dg
... | AirbyteWorkspace |
python | kamyu104__LeetCode-Solutions | Python/substrings-of-size-three-with-distinct-characters.py | {
"start": 50,
"end": 527
} | class ____(object):
def countGoodSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
K = 3
result = 0
count = collections.Counter()
for i in xrange(len(s)):
if i >= K:
count[s[i-K]] -= 1
if not count[s[i-K... | Solution |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 1562,
"end": 1855
} | class ____(StrEnum):
"""
ActionFieldMappingKeys is an enum that represents the keys of an action field mapping.
"""
INTEGRATION_ID_KEY = "integration_id_key"
TARGET_IDENTIFIER_KEY = "target_identifier_key"
TARGET_DISPLAY_KEY = "target_display_key"
| ActionFieldMappingKeys |
python | marshmallow-code__marshmallow | src/marshmallow/fields.py | {
"start": 62611,
"end": 64036
} | class ____(Field[ipaddress.IPv4Interface | ipaddress.IPv6Interface]):
"""A IPInterface field.
IP interface is the non-strict form of the IPNetwork type where arbitrary host
addresses are always accepted.
IPAddress and mask e.g. '192.168.0.2/24' or '192.168.0.2/255.255.255.0'
see https://python.re... | IPInterface |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/seq2seq_lstm.py | {
"start": 4069,
"end": 5229
} | class ____(nn.Module):
"""LSTM decoder.
Attributes:
init_state: [batch_size, hidden_size]
Initial state of the decoder (i.e., the final state of the encoder).
teacher_force: See docstring on Seq2seq module.
vocab_size: Size of the vocabulary.
"""
init_state: tuple[Any, ...]
teacher_force: b... | Decoder |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass10.py | {
"start": 361,
"end": 404
} | class ____(Generic[T]):
pass
@dataclass
| B |
python | coleifer__peewee | tests/models.py | {
"start": 173807,
"end": 174515
} | class ____(ModelTestCase):
database = get_in_memory_db()
requires = [Person]
def test_column_name_stripping(self):
d1 = datetime.date(1990, 1, 1)
d2 = datetime.date(1990, 1, 1)
p1 = Person.create(first='f1', last='l1', dob=d1)
p2 = Person.create(first='f2', last='l2', dob=d2... | TestColumnNameStripping |
python | keras-team__keras | keras/src/losses/losses.py | {
"start": 6499,
"end": 8162
} | class ____(LossFunctionWrapper):
"""Computes the mean squared logarithmic error between `y_true` & `y_pred`.
Formula:
```python
loss = mean(square(log(y_true + 1) - log(y_pred + 1)))
```
Args:
reduction: Type of reduction to apply to the loss. In almost all cases
this shou... | MeanSquaredLogarithmicError |
python | pytorch__pytorch | test/nn/test_load_state_dict.py | {
"start": 489,
"end": 20321
} | class ____(NNTestCase):
_do_cuda_memory_leak_check = True
_do_cuda_non_default_stream = True
@unittest.skipIf(not TEST_NUMPY, "numpy not found")
@swap([True, False])
def test_load_state_dict_invalid(self):
m = torch.nn.Linear(2, 2, bias=False)
state_dict = {"weight": np.random.rand... | TestLoadStateDict |
python | tensorflow__tensorflow | tensorflow/python/distribute/collective_all_reduce_strategy_test.py | {
"start": 11642,
"end": 17316
} | class ____(
CollectiveAllReduceStrategyTestBase,
strategy_test_lib.DistributionTestBase,
parameterized.TestCase):
@classmethod
def setUpClass(cls):
"""Create a local cluster with 3 workers."""
cls._cluster_spec = multi_worker_test_base.create_in_process_cluster(
num_workers=3, num_ps=0)... | DistributedCollectiveAllReduceStrategyTest |
python | huggingface__transformers | src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py | {
"start": 4942,
"end": 5982
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, attn_implementation: str = "sdpa") -> None:
super().__init__()
self.norm1 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
self.norm2 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
self.attn = Qwen2_5_VLVisionAttention(conf... | Qwen2_5_VLVisionBlock |
python | scipy__scipy | scipy/integrate/_rules/_genz_malik.py | {
"start": 184,
"end": 7308
} | class ____(NestedFixedRule):
"""
Genz-Malik cubature.
Genz-Malik is only defined for integrals of dimension >= 2.
Parameters
----------
ndim : int
The spatial dimension of the integrand.
xp : array_namespace, optional
The namespace for the node and weight arrays. Default i... | GenzMalikCubature |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vector_index.py | {
"start": 1342,
"end": 1567
} | class ____(_MultiVectorEncodingConfigCreate):
ksim: Optional[int]
dprojections: Optional[int]
repetitions: Optional[int]
@staticmethod
def encoding_name() -> str:
return "muvera"
| _MuveraConfigCreate |
python | django-debug-toolbar__django-debug-toolbar | debug_toolbar/panels/__init__.py | {
"start": 300,
"end": 9438
} | class ____:
"""
Base class for panels.
"""
is_async = False
def __init__(self, toolbar, get_response: GetResponse):
self.toolbar = toolbar
self.get_response = get_response
self.from_store = False
# Private panel properties
@classproperty
def panel_id(cls):
... | Panel |
python | jpadilla__pyjwt | jwt/exceptions.py | {
"start": 1788,
"end": 1945
} | class ____(PyJWKError):
"""Raised if the algorithm requires ``cryptography`` to be installed and it is not available."""
pass
| MissingCryptographyError |
python | cython__cython | tests/run/pep3135_class_cell.py | {
"start": 3914,
"end": 4075
} | class ____:
"""
>>> M().method()
'overwritten'
"""
def method(self):
__class__ = 'overwritten'
return __class__
@cython.cclass
| M |
python | mozilla__bleach | bleach/_vendor/html5lib/filters/inject_meta_charset.py | {
"start": 89,
"end": 2945
} | class ____(base.Filter):
"""Injects ``<meta charset=ENCODING>`` tag into head of document"""
def __init__(self, source, encoding):
"""Creates a Filter
:arg source: the source token stream
:arg encoding: the encoding to set
"""
base.Filter.__init__(self, source)
... | Filter |
python | django__django | tests/auth_tests/test_models.py | {
"start": 23971,
"end": 24105
} | class ____(SimpleTestCase):
def test_str(self):
g = Group(name="Users")
self.assertEqual(str(g), "Users")
| GroupTests |
python | nedbat__coveragepy | tests/test_context.py | {
"start": 8407,
"end": 8826
} | class ____(SomethingElse, Child):
pass
def no_arguments() -> str | None:
return get_qualname()
def plain_old_function(a: Any, b: Any) -> str | None:
return get_qualname()
def fake_out(self: Any) -> str | None:
return get_qualname()
def patch_meth(self: Any) -> str | None:
return get_qualname... | MultiChild |
python | fluentpython__example-code-2e | 15-more-types/cafeteria/invariant.py | {
"start": 160,
"end": 262
} | class ____(Juice):
"""Delicious juice from Brazilian oranges."""
T = TypeVar('T') # <2>
| OrangeJuice |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 74471,
"end": 74995
} | class ____(CType):
#
# C "void" type
#
is_void = 1
to_py_function = "__Pyx_void_to_None"
def __repr__(self):
return "<CVoidType>"
def declaration_code(self, entity_code,
for_display = 0, dll_linkage = None, pyrex = 0):
if pyrex or for_display:
bas... | CVoidType |
python | getsentry__sentry | tests/snuba/metrics/naming_layer/test_mri.py | {
"start": 218,
"end": 977
} | class ____(TestCase):
def test_format_mri_field(self) -> None:
assert format_mri_field("max(s:spans/user@none)") == "max(user)"
assert format_mri_field("sum(d:spans/exclusive_time@millisecond)") == "sum(exclusive_time)"
assert format_mri_field("invalid_mri_field") == "invalid_mri_field"
... | TestMRIUtils |
python | doocs__leetcode | solution/2900-2999/2960.Count Tested Devices After Test Operations/Solution.py | {
"start": 0,
"end": 187
} | class ____:
def countTestedDevices(self, batteryPercentages: List[int]) -> int:
ans = 0
for x in batteryPercentages:
ans += x > ans
return ans
| Solution |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/expressions/rolling.py | {
"start": 1279,
"end": 1420
} | class ____(UnaryOp):
policy: plc.replace.ReplacePolicy = plc.replace.ReplacePolicy.PRECEDING
@dataclass(frozen=True)
| FillNullWithStrategyOp |
python | PyCQA__bandit | tests/functional/test_runtime.py | {
"start": 122,
"end": 4469
} | class ____(testtools.TestCase):
def _test_runtime(self, cmdlist, infile=None):
process = subprocess.Popen(
cmdlist,
stdin=infile if infile else subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
close_fds=True,
)
std... | RuntimeTests |
python | pytorch__pytorch | torch/nn/parameter.py | {
"start": 10945,
"end": 12217
} | class ____(UninitializedTensorMixin, torch.Tensor):
r"""A buffer that is not initialized.
Uninitialized Buffer is a a special case of :class:`torch.Tensor`
where the shape of the data is still unknown.
Unlike a :class:`torch.Tensor`, uninitialized parameters
hold no data and attempting to access s... | UninitializedBuffer |
python | apache__airflow | devel-common/src/sphinx_exts/providers_extensions.py | {
"start": 14937,
"end": 15460
} | class ____(BaseJinjaReferenceDirective):
"""Generate list of classes supporting OpenLineage"""
def render_content(self, *, tags: set[str] | None, header_separator: str = DEFAULT_HEADER_SEPARATOR):
return _render_openlineage_supported_classes_content()
def setup(app):
"""Setup plugin"""
app.ad... | OpenLineageSupportedClassesDirective |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_backend.py | {
"start": 965,
"end": 14515
} | class ____(TestCase):
def setUp(self):
git_repo = make_test_git()
super().setUp()
self.eric = User(username="eric")
self.eric.set_password("test")
self.eric.save()
self.project = Project.objects.create(
name="Test Project",
repo_type="git",
... | TestGitBackend |
python | readthedocs__readthedocs.org | readthedocs/profiles/tests/test_views.py | {
"start": 1234,
"end": 36963
} | class ____(TestCase):
def setUp(self):
self.user = get(User)
self.social_account_github = get(
SocialAccount,
provider=GitHubProvider.id,
user=self.user,
uid="1234",
extra_data={"login": "user"},
)
get(
SocialTok... | TestMigrateToGitHubAppView |
python | jschneier__django-storages | tests/test_gcloud.py | {
"start": 549,
"end": 963
} | class ____(TestCase):
def setUp(self):
self.bucket_name = "test_bucket"
self.filename = "test_file.txt"
self.storage = gcloud.GoogleCloudStorage(bucket_name=self.bucket_name)
self.client_patcher = mock.patch("storages.backends.gcloud.Client")
self.client_patcher.start()
... | GCloudTestCase |
python | RaRe-Technologies__gensim | gensim/test/test_translation_matrix.py | {
"start": 3938,
"end": 5980
} | class ____(unittest.TestCase):
def setUp(self):
filename = datapath("alldata-id-10.txt")
train_docs = read_sentiment_docs(filename)
self.train_docs = train_docs
self.source_doc_vec = Doc2Vec(documents=train_docs[:5], vector_size=8, epochs=50, seed=1)
self.target_doc_vec = Doc... | TestBackMappingTranslationMatrix |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.