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
langchain-ai__langchain
libs/langchain_v1/langchain/agents/middleware/todo.py
{ "start": 649, "end": 905 }
class ____(TypedDict): """A single todo item with content and status.""" content: str """The content/description of the todo item.""" status: Literal["pending", "in_progress", "completed"] """The current status of the todo item."""
Todo
python
astropy__astropy
astropy/io/votable/converters.py
{ "start": 24994, "end": 25130 }
class ____(FloatingPoint): """ Handles the float datatype. Single-precision IEEE floating-point. """ format = "f4"
Float
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_header_image07.py
{ "start": 315, "end": 1046 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("header_image07.xlsx") self.ignore_elements = { "xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"] } def test_c...
TestCompareXLSXFiles
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/unit_tests/test_connector_runner.py
{ "start": 462, "end": 6711 }
class ____: @pytest.fixture def dev_image_name(self): return "airbyte/source-faker:dev" @pytest.fixture def released_image_name(self): return "airbyte/source-faker:latest" async def test_get_container_env_variable_value(self, source_faker_container): runner = connector_runn...
TestContainerRunner
python
apache__airflow
providers/http/src/airflow/providers/http/notifications/http.py
{ "start": 1128, "end": 3812 }
class ____(BaseNotifier): """ HTTP Notifier. Sends HTTP requests to notify external systems. :param http_conn_id: HTTP connection id that has the base URL and optional authentication credentials. :param endpoint: The endpoint to be called i.e. resource/v1/query? :param method: The HTTP method ...
HttpNotifier
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_build_notifications.py
{ "start": 12572, "end": 13683 }
class ____(TestCase): def setUp(self): self.project = get(Project) self.version = get(Version, project=self.project) self.build = get(Build, version=self.version) def test_webhook_form_url_length(self): form = WebHookForm( { "url": "https://foobar.com...
TestForms
python
pytransitions__transitions
tests/test_mermaid.py
{ "start": 710, "end": 6311 }
class ____(TestDiagrams): graph_engine = "mermaid" edge_re = re.compile(r"^\s+(?P<src>\w+)\s*-->\s*(?P<dst>\w+)\s*:\s*(?P<attr>.*)$") node_re = re.compile(r"^\s+state \"\S+(\s+(?P<attr>\[.*\]?))?\" as (?P<node>\S+)") def test_diagram(self): m = self.machine_cls(states=self.states, transitions=...
TestMermaidDiagrams
python
plotly__plotly.py
plotly/graph_objs/parcoords/line/colorbar/_tickfont.py
{ "start": 233, "end": 9954 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "parcoords.line.colorbar" _path_str = "parcoords.line.colorbar.tickfont" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weig...
Tickfont
python
ray-project__ray
python/ray/tune/tests/test_placeholder.py
{ "start": 270, "end": 343 }
class ____: def __init__(self, value): self.value = value
Dummy
python
jazzband__django-model-utils
model_utils/managers.py
{ "start": 11590, "end": 12399 }
class ____(Generic[ModelT]): @overload def __init__(self, *args: models.Q): ... @overload def __init__(self, **kwargs: object): ... def __init__(self, *args: models.Q, **kwargs: object): if args: self._q = args[0] else: self._q = models.Q(**...
QueryManagerMixin
python
pypa__wheel
src/wheel/_bdist_wheel.py
{ "start": 5053, "end": 21729 }
class ____(Command): description = "create a wheel distribution" supported_compressions = { "stored": ZIP_STORED, "deflated": ZIP_DEFLATED, } user_options = [ ("bdist-dir=", "b", "temporary directory for creating the distribution"), ( "plat-name=", ...
bdist_wheel
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_iban.py
{ "start": 749, "end": 1420 }
class ____(ColumnMapMetricProvider): condition_metric_name = "column_values.valid_iban" @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): return column.apply(is_valid_iban) @column_condition_partial(engine=SparkDFExecutionEngine) def _spark(cls, co...
ColumnValuesToBeValidIban
python
getsentry__sentry
src/sentry/charts/base.py
{ "start": 196, "end": 892 }
class ____(Service): """ The chart rendering service is used to translate arbitrary data into a image representation of that data, usually a chart. """ __all__ = ( "is_enabled", "generate_chart", ) def __init__(self, **options: Any) -> None: pass def is_enabled...
ChartRenderer
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/methods/test_astype.py
{ "start": 11399, "end": 12429 }
class ____: @pytest.mark.parametrize("tz", [None, "US/Central"]) def test_astype_category(self, tz): obj = date_range("2000", periods=2, tz=tz, name="idx", unit="ns") result = obj.astype("category") dti = DatetimeIndex(["2000-01-01", "2000-01-02"], tz=tz).as_unit("ns") expected =...
TestAstype
python
pydantic__pydantic
pydantic-core/tests/validators/test_complex.py
{ "start": 6370, "end": 6563 }
class ____: """Object that defines __float__() method""" def __init__(self, value): self.value = value def __float__(self): return float(self.value)
ComplexWithFloat
python
spack__spack
lib/spack/spack/spec.py
{ "start": 224604, "end": 224726 }
class ____(spack.error.SpecError): """Raised when a detected spec doesn't pass validation checks."""
InvalidSpecDetected
python
kamyu104__LeetCode-Solutions
Python/trim-a-binary-search-tree.py
{ "start": 29, "end": 518 }
class ____(object): def trimBST(self, root, L, R): """ :type root: TreeNode :type L: int :type R: int :rtype: TreeNode """ if not root: return None if root.val < L: return self.trimBST(root.right, L, R) if root.val > R: ...
Solution
python
sympy__sympy
sympy/physics/quantum/hilbert.py
{ "start": 7707, "end": 13022 }
class ____(HilbertSpace): """A tensor product of Hilbert spaces [1]_. The tensor product between Hilbert spaces is represented by the operator ``*`` Products of the same Hilbert space will be combined into tensor powers. A ``TensorProductHilbertSpace`` object takes in an arbitrary number of ``...
TensorProductHilbertSpace
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/plan/active.py
{ "start": 1800, "end": 29891 }
class ____: """State machine used to track progress through execution of an ExecutionPlan.""" def __init__( self, execution_plan: ExecutionPlan, retry_mode: RetryMode, sort_key_fn: Optional[Callable[[ExecutionStep], float]] = None, max_concurrent: Optional[int] = None, ...
ActiveExecution
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py
{ "start": 9288, "end": 9476 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneMessageEvent, GrapheneStepEvent, GrapheneErrorEvent) name = "HookErroredEvent"
GrapheneHookErroredEvent
python
kamyu104__LeetCode-Solutions
Python/number-of-integers-with-popcount-depth-equal-to-k-ii.py
{ "start": 1002, "end": 1900 }
class ____(object): def popcountDepth(self, nums, queries): """ :type nums: List[int] :type queries: List[List[int]] :rtype: List[int] """ def count(x): return D[popcount(x)]+1 if x != 1 else 0 bit = [BIT(len(nums)) for _ in xrange(MAX_K+1...
Solution
python
huggingface__transformers
src/transformers/models/gemma3n/modeling_gemma3n.py
{ "start": 79958, "end": 90930 }
class ____(Gemma3nPreTrainedModel): config: Gemma3nTextConfig input_modalities = ("text",) def __init__(self, config: Gemma3nTextConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size # Gemma3n downcasts the below to bfl...
Gemma3nTextModel
python
getsentry__sentry
tests/sentry/auth/test_helper.py
{ "start": 1563, "end": 1659 }
class ____(TypedDict): id: str email: str name: str data: dict[str, str]
_Identity
python
getsentry__sentry
src/sentry/interfaces/stacktrace.py
{ "start": 11512, "end": 19455 }
class ____(Interface): """ A stacktrace contains a list of frames, each with various bits (most optional) describing the context of that frame. Frames should be sorted from oldest to newest. The stacktrace contains an element, ``frames``, which is a list of hashes. Each hash must contain **at l...
Stacktrace
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_data_labels43.py
{ "start": 315, "end": 1906 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_data_labels43.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
numba__numba
numba/core/typed_passes.py
{ "start": 7176, "end": 7343 }
class ____(BaseTypeInference): _name = "partial_type_inference" _raise_errors = False @register_pass(mutates_CFG=False, analysis_only=False)
PartialTypeInference
python
apache__airflow
airflow-core/tests/unit/dag_processing/test_processor.py
{ "start": 38587, "end": 48181 }
class ____: """Test the _execute_task_callbacks function""" def test_execute_task_callbacks_failure_callback(self, spy_agency): """Test _execute_task_callbacks executes failure callbacks""" called = False context_received = None def on_failure(context): nonlocal cal...
TestExecuteTaskCallbacks
python
tensorflow__tensorflow
tensorflow/python/tpu/tests/tpu_embedding_v2_hd_valid_input_test.py
{ "start": 1241, "end": 4728 }
class ____(tpu_embedding_base_test.TPUEmbeddingBaseTest): def test_enqueue_dense_sparse_ragged(self): strategy, mid_level_api, _ = self._create_strategy_and_mid_level('sgd') dataset = self._create_high_dimensional_dense_dataset(strategy) dense_iter = iter( strategy.experimental_distribute_datase...
TPUEmbeddingTest
python
google__pytype
pytype/tools/analyze_project/pytype_runner_test.py
{ "start": 809, "end": 1002 }
class ____: output: str action: str input: str deps: Sequence[str] imports: str module: str # number of lines in the build.ninja preamble _PREAMBLE_LENGTH = 6
ExpectedBuildStatement
python
apache__airflow
providers/cncf/kubernetes/tests/unit/cncf/kubernetes/cli/test_kubernetes_command.py
{ "start": 2749, "end": 12918 }
class ____: label_selector = "dag_id,task_id,try_number,airflow_version" @classmethod def setup_class(cls): with conf_vars({("core", "executor"): "KubernetesExecutor"}): importlib.reload(executor_loader) importlib.reload(cli_parser) cls.parser = cli_parser.get_pa...
TestCleanUpPodsCommand
python
facelessuser__pymdown-extensions
tests/test_extensions/test_caret.py
{ "start": 40, "end": 5197 }
class ____(util.MdCase): """Test escaping cases for Caret with smart enabled.""" extension = [ 'pymdownx.caret' ] extension_configs = { "pymdownx.caret": { "smart_insert": True } } def test_case_1(self): """Test case 1.""" self.check_markdow...
TestCaretSmart
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py
{ "start": 149, "end": 191 }
class ____(Enum): ... @dataclass # Foobar
E
python
pandas-dev__pandas
asv_bench/benchmarks/inference.py
{ "start": 3952, "end": 4355 }
class ____: params = ([True, False], [50, 500, 5000, 100000]) param_names = ["cache", "count"] def setup(self, cache, count): rng = date_range(start="1/1/1971", periods=count) self.unique_date_strings = rng.strftime("%Y-%m-%d").tolist() def time_unique_date_strings(self, cache, count):...
ToDatetimeCacheSmallCount
python
joke2k__faker
faker/providers/isbn/__init__.py
{ "start": 131, "end": 2738 }
class ____(BaseProvider): """Generates fake ISBNs. See https://www.isbn-international.org/content/what-isbn for the format of ISBNs. See https://www.isbn-international.org/range_file_generation for the list of rules pertaining to each prefix/registration group. """ rules: Dict[str, Dict[st...
Provider
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py
{ "start": 118304, "end": 118974 }
class ____(GeneratedAirbyteDestination): @public def __init__(self, name: str, destination_path: str): """Airbyte Destination for Local Json. Documentation can be found at https://docs.airbyte.com/integrations/destinations/local-json Args: name (str): The name of the destin...
LocalJsonDestination
python
astropy__astropy
astropy/io/ascii/fixedwidth.py
{ "start": 15015, "end": 15339 }
class ____(FixedWidthHeader): """Header reader for fixed width tables splitting on whitespace. For fixed width tables with several header lines, there is typically a white-space delimited format line, so splitting on white space is needed. """ splitter_class = DefaultSplitter
FixedWidthTwoLineHeader
python
pytorch__pytorch
test/inductor/test_mkldnn_pattern_matcher.py
{ "start": 24249, "end": 160488 }
class ____(TestPatternMatcherBase): @reduced_f32_on_and_off() def test_linear_unary(self, device="cpu"): self.device = device class M(torch.nn.Module): def __init__( self, unary_fn, in_features, out_features, ...
TestPatternMatcher
python
py-pdf__pypdf
pypdf/constants.py
{ "start": 6319, "end": 6985 }
class ____: """Table 3.41 Entries in a file specification dictionary.""" Type = "/Type" FS = "/FS" # The name of the file system to be used to interpret this file specification F = "/F" # A file specification string of the form described in §3.10.1 UF = "/UF" # A Unicode string of the file as de...
FileSpecificationDictionaryEntries
python
plotly__plotly.py
plotly/graph_objs/barpolar/hoverlabel/_font.py
{ "start": 233, "end": 17148 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "barpolar.hoverlabel" _path_str = "barpolar.hoverlabel.font" _valid_props = { "color", "colorsrc", "family", "familysrc", "lineposition", "linepositionsrc", "shadow", "shadowsrc", ...
Font
python
encode__django-rest-framework
tests/test_atomic_requests.py
{ "start": 654, "end": 788 }
class ____(APIView): def post(self, request, *args, **kwargs): BasicModel.objects.create() raise Exception
ErrorView
python
pytorch__pytorch
test/jit/test_autodiff.py
{ "start": 270, "end": 5244 }
class ____(JitTestCase): def test_undefined_tensor_lists(self): def fn(tensor_list: List[torch.Tensor], add_tensor): cat = torch.cat(tensor_list, dim=1) r = torch.sin(cat + add_tensor) return r fn_s = torch.jit.script(fn) a = torch.rand((3, 6), requires_...
TestAutodiffJit
python
pytorch__pytorch
benchmarks/functional_autograd_benchmark/torchaudio_models.py
{ "start": 14581, "end": 16540 }
class ____(nn.Module): """Container module with an encoder, a recurrent or transformer module, and a decoder.""" def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5): super().__init__() try: from torch.nn import TransformerEncoder, TransformerEncoderLayer exce...
TransformerModel
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 7144, "end": 7550 }
class ____(_TestDCTBase): def test_definition_matlab(self): # Test correspondence with MATLAB (orthornomal mode). dt = np.result_type(np.float32, self.rdt) for xr, yr in zip(X, Y): x = np.array(xr, dtype=dt) y = dct(x, norm="ortho", type=2) assert_equal(y....
_TestDCTIIBase
python
Lightning-AI__lightning
tests/tests_pytorch/helpers/simple_models.py
{ "start": 2803, "end": 4439 }
class ____(LightningModule): def __init__(self): super().__init__() setattr(self, "layer_0", nn.Linear(16, 64)) setattr(self, "layer_0a", torch.nn.ReLU()) for i in range(1, 3): setattr(self, f"layer_{i}", nn.Linear(64, 64)) setattr(self, f"layer_{i}a", torch.n...
RegressionModel
python
ray-project__ray
rllib/offline/offline_policy_evaluation_runner.py
{ "start": 2261, "end": 6472 }
class ____(OfflinePreLearner): def __call__(self, batch: Dict[str, numpy.ndarray]) -> Dict[str, numpy.ndarray]: # If we directly read in episodes we just convert to list. if self.input_read_episodes: # Import `msgpack` for decoding. import msgpack import msgpack_n...
OfflinePolicyPreEvaluator
python
astropy__astropy
astropy/extern/ply/yacc.py
{ "start": 4886, "end": 5349 }
class ____(object): def __init__(self, f): self.f = f def debug(self, msg, *args, **kwargs): self.f.write((msg % args) + '\n') info = debug def warning(self, msg, *args, **kwargs): self.f.write('WARNING: ' + (msg % args) + '\n') def error(self, msg, *args, **kwargs): ...
PlyLogger
python
apache__airflow
airflow-core/tests/unit/api_fastapi/auth/managers/simple/test_user.py
{ "start": 822, "end": 1118 }
class ____: def test_get_id(self, test_admin): assert test_admin.get_id() == "test" def test_get_name(self, test_admin): assert test_admin.get_name() == "test" def test_get_role(self, test_admin): assert test_admin.get_role() == "admin"
TestSimpleAuthManagerUser
python
pdm-project__pdm
tests/cli/conftest.py
{ "start": 1713, "end": 3753 }
class ____: mock_pypi: MagicMock uploaded: list[Any] @pytest.fixture # @pytest.mark.usefixtures("mock_run_gpg", "prepare_packages") def mock_publish(mock_pypi, uploaded) -> PublishMock: return PublishMock( mock_pypi=mock_pypi, uploaded=uploaded, ) @pytest.fixture def _echo(project): ...
PublishMock
python
anthropics__anthropic-sdk-python
src/anthropic/types/web_search_tool_request_error_param.py
{ "start": 230, "end": 498 }
class ____(TypedDict, total=False): error_code: Required[ Literal["invalid_tool_input", "unavailable", "max_uses_exceeded", "too_many_requests", "query_too_long"] ] type: Required[Literal["web_search_tool_result_error"]]
WebSearchToolRequestErrorParam
python
huggingface__transformers
src/transformers/models/kyutai_speech_to_text/modeling_kyutai_speech_to_text.py
{ "start": 11197, "end": 14233 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: KyutaiSpeechToTextConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings ...
KyutaiSpeechToTextRotaryEmbedding
python
pyinstaller__pyinstaller
bootloader/waflib/Tools/c_tests.py
{ "start": 4164, "end": 5042 }
class ____(Task.Task): color = 'PINK' def run(self): txt = self.inputs[0].read(flags='rb').decode('latin-1') if txt.find('LiTTleEnDian') > -1: self.generator.tmp.append('little') elif txt.find('BIGenDianSyS') > -1: self.generator.tmp.append('big') else: ...
grep_for_endianness
python
jschneier__django-storages
tests/test_utils.py
{ "start": 436, "end": 1636 }
class ____(TestCase): def test_clean_name(self): """Test the base case of clean_name.""" path = utils.clean_name("path/to/somewhere") self.assertEqual(path, "path/to/somewhere") def test_clean_name_pathlib(self): """Test for pathlib.Path handling.""" path = pathlib.Path(...
CleanNameTests
python
kamyu104__LeetCode-Solutions
Python/three-divisors.py
{ "start": 35, "end": 330 }
class ____(object): def isThree(self, n): """ :type n: int :rtype: bool """ cnt = 0 i = 1 while i*i <= n and cnt <= 3: if n%i == 0: cnt += 1 if i*i == n else 2 i += 1 return cnt == 3
Solution
python
django__django
tests/check_framework/test_model_checks.py
{ "start": 5171, "end": 9243 }
class ____(SimpleTestCase): def test_collision_in_same_model(self): index = models.Index(fields=["id"], name="foo") class Model(models.Model): class Meta: indexes = [index, index] self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_conf...
IndexNameTests
python
simonw__datasette
datasette/permissions.py
{ "start": 293, "end": 847 }
class ____: """Context manager to temporarily skip permission checks. This is not a stable API and may change in future releases. Usage: with SkipPermissions(): # Permission checks are skipped within this block response = await datasette.client.get("/protected") """ ...
SkipPermissions
python
sphinx-doc__sphinx
tests/roots/test-add_enumerable_node/enumerable_node.py
{ "start": 72, "end": 242 }
class ____(nodes.figure): pass def visit_my_figure(self, node): self.visit_figure(node) def depart_my_figure(self, node): self.depart_figure(node)
my_figure
python
prabhupant__python-ds
data_structures/graphs/cycle_in_undirected_graph_iterative.py
{ "start": 654, "end": 1677 }
class ____: def __init__(self, vertices): self.graph = defaultdict(list) self.vertices = vertices def add_edge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) def dfs(self): visited = [False] * self.vertices parent = [-1] * self.vertices ...
Graph
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/methodOverride1.py
{ "start": 9161, "end": 9334 }
class ____(A): # This should generate error because list[int] is narrower # than Iterable[int]. def test(self, t: list[int]) -> Sequence[str]: ...
NarrowerArgument
python
google__python-fire
fire/test_components.py
{ "start": 5219, "end": 5434 }
class ____: def __eq__(self, other): raise ValueError('Instances of this class cannot be compared.') def __ne__(self, other): raise ValueError('Instances of this class cannot be compared.')
NonComparable
python
pytorch__pytorch
test/mobile/model_test/math_ops.py
{ "start": 13775, "end": 14384 }
class ____(torch.nn.Module): def forward(self): return self.spectral_ops() def spectral_ops(self): a = torch.randn(10) b = torch.randn(10, 8, 4, 2) return len( torch.stft(a, 8), torch.stft(a, torch.tensor(8)), torch.istft(b, 8), to...
SpectralOpsModule
python
PyCQA__pylint
tests/functional/i/invalid/invalid_bytes_returned.py
{ "start": 891, "end": 1075 }
class ____: """ __bytes__ returns node which does not have 'value' in AST """ def __bytes__(self): # [invalid-bytes-returned] return lambda: b"some bytes"
ThirdBadBytes
python
numba__numba
numba/core/imputils.py
{ "start": 275, "end": 3816 }
class ____(object): """ A registry of function and attribute implementations. """ def __init__(self, name='unspecified'): self.name = name self.functions = [] self.getattrs = [] self.setattrs = [] self.casts = [] self.constants = [] def lower(self, fu...
Registry
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/key_binding/key_bindings.py
{ "start": 16403, "end": 18132 }
class ____(_Proxy): """ Wraps around a `KeyBindings`. Disable/enable all the key bindings according to the given (additional) filter.:: @Condition def setting_is_true(): return True # or False registry = ConditionalKeyBindings(key_bindings, setting_is_true) When n...
ConditionalKeyBindings
python
pandas-dev__pandas
asv_bench/benchmarks/io/csv.py
{ "start": 3128, "end": 4224 }
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(rng) if freq == "D": self.default_fmt = ...
ToCSVPeriod
python
django-haystack__django-haystack
test_haystack/test_query.py
{ "start": 36829, "end": 38021 }
class ____(TestCase): fixtures = ["base_data"] def setUp(self): super().setUp() # Stow. self.old_unified_index = connections["default"]._index self.ui = UnifiedIndex() self.bmmsi = BasicMockModelSearchIndex() self.cpkmmsi = CharPKMockModelSearchIndex() se...
PickleSearchQuerySetTestCase
python
pydantic__pydantic
pydantic/mypy.py
{ "start": 3266, "end": 5666 }
class ____(Plugin): """The Pydantic mypy plugin.""" def __init__(self, options: Options) -> None: self.plugin_config = PydanticPluginConfig(options) self._plugin_data = self.plugin_config.to_data() super().__init__(options) def get_base_class_hook(self, fullname: str) -> Callable[[...
PydanticPlugin
python
catalyst-team__catalyst
catalyst/contrib/layers/pooling.py
{ "start": 5023, "end": 5861 }
class ____(nn.Module): """@TODO: Docs (add `Example`). Contribution is welcome.""" def __init__(self, in_features, activation_fn="Sigmoid"): """@TODO: Docs. Contribution is welcome.""" super().__init__() self.avg = GlobalAvgPool2d() self.max = GlobalMaxPool2d() self.attn...
GlobalConcatAttnPool2d
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/errors.py
{ "start": 17455, "end": 18871 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneError,) name = "UnsupportedOperationError" def __init__(self, message: Optional[str] = None): super().__init__() self.message = check.str_param(message, "message") or "Unsupported operation." types = [ Grap...
GrapheneUnsupportedOperationError
python
ray-project__ray
python/ray/util/collective/tests/single_node_cpu_tests/test_gloo_group_isolation.py
{ "start": 232, "end": 1724 }
class ____: def __init__(self): pass def init_gloo_group( self, world_size: int, rank: int, group_name: str, gloo_timeout: int = 30000 ): col.init_collective_group( world_size, rank, Backend.GLOO, group_name, gloo_timeout ) return True def get_gloo_t...
Worker
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/assets.py
{ "start": 442, "end": 651 }
class ____(graphene.ObjectType): assets = non_null_list(GrapheneAssetRecord) cursor = graphene.Field(graphene.String) class Meta: name = "AssetRecordConnection"
GrapheneAssetRecordConnection
python
python-markdown__markdown
markdown/inlinepatterns.py
{ "start": 13072, "end": 13342 }
class ____(Pattern): # pragma: no cover """ Return a simple text of `group(2)` of a Pattern. """ def handleMatch(self, m: re.Match[str]) -> str: """ Return string content of `group(2)` of a matching pattern. """ return m.group(2)
SimpleTextPattern
python
scipy__scipy
scipy/_lib/_array_api.py
{ "start": 24837, "end": 37757 }
class ____: cpu: bool | None # None if not applicable gpu: bool | None warnings: list[str] = dataclasses.field(default_factory=list) def _render(self, value): if value is None: return "n/a" if not value: return "⛔" if self.warnings: res = "⚠️...
_XPSphinxCapability
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 37323, "end": 37590 }
class ____(Base): """SQLAlchemy model of a saved search.""" name: Mapped[str] filters: Mapped[list[dict[str, Any]]] = mapped_column( JSON, server_default="[]", default=list ) __table_args__: Any = (sa.UniqueConstraint("name"),)
SavedSearch
python
pydata__xarray
xarray/tests/test_namedarray.py
{ "start": 5971, "end": 24338 }
class ____(NamedArraySubclassobjects): def cls(self, *args: Any, **kwargs: Any) -> NamedArray[Any, Any]: return NamedArray(*args, **kwargs) @pytest.fixture def target(self, data: np.ndarray[Any, Any]) -> NamedArray[Any, Any]: return NamedArray(["x", "y"], data) @pytest.mark.parametrize...
TestNamedArray
python
django__django
django/contrib/gis/gdal/geometries.py
{ "start": 26581, "end": 26630 }
class ____(GeometryCollection): pass
MultiPoint
python
jmcnamara__XlsxWriter
xlsxwriter/test/styles/test_styles08.py
{ "start": 380, "end": 4796 }
class ____(unittest.TestCase): """ Test assembling a complete Styles file. """ def test_assemble_xml_file(self): """Test for simple fills with a default solid pattern.""" self.maxDiff = None fh = StringIO() style = Styles() style._set_filehandle(fh) wo...
TestAssembleStyles
python
anthropics__anthropic-sdk-python
tests/api_resources/test_completions.py
{ "start": 384, "end": 4732 }
class ____: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create_overload_1(self, client: Anthropic) -> None: completion = client.completions.create( max_tokens_to_sample=256, model="claude...
TestCompletions
python
PrefectHQ__prefect
src/prefect/server/events/filters.py
{ "start": 8900, "end": 9035 }
class ____: simple: list[str] = field(default_factory=list) prefixes: list[str] = field(default_factory=list) @dataclass
LabelSet
python
getsentry__sentry
src/sentry/workflow_engine/handlers/condition/age_comparison_handler.py
{ "start": 469, "end": 2058 }
class ____(DataConditionHandler[WorkflowEventData]): group = DataConditionHandler.Group.ACTION_FILTER subgroup = DataConditionHandler.Subgroup.ISSUE_ATTRIBUTES comparison_json_schema = { "type": "object", "properties": { "comparison_type": { "type": "string", ...
AgeComparisonConditionHandler
python
Textualize__rich
rich/markdown.py
{ "start": 4425, "end": 5186 }
class ____(TextElement): """A code block with syntax highlighting.""" style_name = "markdown.code_block" @classmethod def create(cls, markdown: Markdown, token: Token) -> CodeBlock: node_info = token.info or "" lexer_name = node_info.partition(" ")[0] return cls(lexer_name or "...
CodeBlock
python
ansible__ansible
test/lib/ansible_test/_internal/commands/sanity/__init__.py
{ "start": 25215, "end": 25577 }
class ____(TestFailure): """Sanity test failure.""" def __init__( self, test: str, python_version: t.Optional[str] = None, messages: t.Optional[c.Sequence[SanityMessage]] = None, summary: t.Optional[str] = None, ) -> None: super().__init__(COMMAND, test, pyth...
SanityFailure
python
doocs__leetcode
solution/3000-3099/3072.Distribute Elements Into Two Arrays II/Solution2.py
{ "start": 0, "end": 690 }
class ____: def resultArray(self, nums: List[int]) -> List[int]: arr1 = [nums[0]] arr2 = [nums[1]] sl1 = SortedList(arr1) sl2 = SortedList(arr2) for x in nums[2:]: i = sl1.bisect_right(x) j = sl2.bisect_right(x) if len(sl1) - i > len(sl2) -...
Solution
python
getsentry__sentry
src/sentry/api/endpoints/organization_sdk_updates.py
{ "start": 4112, "end": 4687 }
class ____(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PRIVATE, } owner = ApiOwner.TELEMETRY_EXPERIENCE def get(self, request: Request, organization: Organization) -> Response: try: sdks = get_sdk_index() except Exception as e: sentr...
OrganizationSdksEndpoint
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 106356, "end": 108132 }
class ____(Request): """ get task scalar metrics and variants :param task: task ID :type task: str :param model_events: If set then the retrieving model events. Otherwise task events :type model_events: bool """ _service = "events" _action = "get_scalar_metrics_and_variants...
GetScalarMetricsAndVariantsRequest
python
huggingface__transformers
tests/models/owlvit/test_modeling_owlvit.py
{ "start": 1567, "end": 4434 }
class ____: def __init__( self, parent, batch_size=12, image_size=32, patch_size=2, num_channels=3, is_training=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, dropout=0.1, ...
OwlViTVisionModelTester
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/control_flow/control_flow_ops_py_test.py
{ "start": 182009, "end": 183849 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testGuardedAssertDoesNotCopyWhenTrue(self): if test_util.is_gpu_available(): self.skipTest("b/128646478 fails in opensource") with self.session() as sess: with ops.device(test.gpu_device_name()): value = constant_op.constant(1...
AssertTest
python
altair-viz__altair
tools/generate_schema_wrapper.py
{ "start": 14019, "end": 14251 }
class ____(codegen.SchemaGenerator): schema_class_template = textwrap.dedent( ''' class {classname}({basename}): """{docstring}""" _schema = {schema!r} {init_code} ''' )
SchemaGenerator
python
langchain-ai__langchain
libs/partners/perplexity/tests/unit_tests/test_chat_models_standard.py
{ "start": 207, "end": 512 }
class ____(ChatModelUnitTests): @property def chat_model_class(self) -> type[BaseChatModel]: return ChatPerplexity @property def init_from_env_params(self) -> tuple[dict, dict, dict]: return ({"PPLX_API_KEY": "api_key"}, {}, {"pplx_api_key": "api_key"})
TestPerplexityStandard
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/db_io_manager.py
{ "start": 1932, "end": 3061 }
class ____(Generic[T]): @staticmethod @abstractmethod def delete_table_slice( context: OutputContext, table_slice: TableSlice, connection: T ) -> None: ... @staticmethod @abstractmethod def get_select_statement(table_slice: TableSlice) -> str: ... @staticmethod def get_tabl...
DbClient
python
encode__django-rest-framework
tests/test_throttling.py
{ "start": 14381, "end": 16288 }
class ____(TestCase): def setUp(self): SimpleRateThrottle.scope = 'anon' def test_get_rate_raises_error_if_scope_is_missing(self): throttle = SimpleRateThrottle() with pytest.raises(ImproperlyConfigured): throttle.scope = None throttle.get_rate() def test_t...
SimpleRateThrottleTests
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_batch.py
{ "start": 24313, "end": 26775 }
class ____: warn_message = "The `status_retries` parameter is unused and should be removed" def test_template_fields(self): environment_name = "environment_name" compute_resources = {} service_role = "test_role" environment_type = "environment_type" environment_state = "...
TestBatchCreateComputeEnvironmentOperator
python
pytorch__pytorch
torch/ao/nn/intrinsic/modules/fused.py
{ "start": 6805, "end": 7405 }
class ____(_FusedModule): r"""This is a sequential container which calls the BatchNorm 2d and ReLU modules. During quantization this will be replaced with the corresponding fused module.""" def __init__(self, batch_norm, relu): assert ( type_before_parametrizations(batch_norm) == BatchN...
BNReLU2d
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_header_image16.py
{ "start": 315, "end": 1348 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("header_image16.xlsx") self.ignore_elements = { "xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"], "xl/worksheet...
TestCompareXLSXFiles
python
scipy__scipy
scipy/fft/_pocketfft/tests/test_basic.py
{ "start": 4399, "end": 5100 }
class ____: def test_1_argument_real(self): x1 = np.array([1, 2, 3, 4], dtype=np.float16) y = fft(x1, n=4) assert_equal(y.dtype, np.complex64) assert_equal(y.shape, (4, )) assert_array_almost_equal(y, direct_dft(x1.astype(np.float32))) def test_n_argument_real(self): ...
TestFloat16FFT
python
tartley__colorama
colorama/ansitowin32.py
{ "start": 343, "end": 2236 }
class ____: ''' Wraps a stream (such as stdout), acting as a transparent proxy for all attribute access apart from method 'write()', which is delegated to our Converter instance. ''' def __init__(self, wrapped, converter): # double-underscore everything to prevent clashes with names of ...
StreamWrapper
python
urllib3__urllib3
test/test_queue_monkeypatch.py
{ "start": 254, "end": 761 }
class ____: """ Test that connection pool works even with a monkey patched Queue module, see obspy/obspy#1599, psf/requests#3742, urllib3/urllib3#1061. """ def test_queue_monkeypatching(self) -> None: with mock.patch.object(queue, "Empty", BadError): with HTTPConnectionPool(host...
TestMonkeypatchResistance
python
gevent__gevent
src/gevent/exceptions.py
{ "start": 162, "end": 1607 }
class ____(Exception): """ Exception thrown when the hub finishes running (`gevent.hub.Hub.run` would return). In a normal application, this is never thrown or caught explicitly. The internal implementation of functions like :meth:`gevent.hub.Hub.join` and :func:`gevent.joinall` may catch it, b...
LoopExit
python
keon__algorithms
tests/test_strings.py
{ "start": 2609, "end": 2941 }
class ____(unittest.TestCase): """[summary] Test for the file decode_string.py Arguments: unittest {[type]} -- [description] """ def test_decode_string(self): self.assertEqual("aaabcbc", decode_string("3[a]2[bc]")) self.assertEqual("accaccacc", decode_string("3[a2[c]]"))
TestDecodeString
python
python-openxml__python-docx
tests/oxml/unitdata/section.py
{ "start": 590, "end": 893 }
class ____(BaseBuilder): __tag__ = "w:type" __nspfxs__ = ("w",) __attrs__ = ("w:val",) def a_pgMar(): return CT_PageMarBuilder() def a_pgSz(): return CT_PageSzBuilder() def a_sectPr(): return CT_SectPrBuilder() def a_type(): return CT_SectTypeBuilder()
CT_SectTypeBuilder
python
django__django
tests/urlpatterns_reverse/tests.py
{ "start": 68070, "end": 70013 }
class ____(SimpleTestCase): def test_valid_resolve(self): test_urls = [ "/lookahead-/a-city/", "/lookbehind-/a-city/", "/lookahead+/a-city/", "/lookbehind+/a-city/", ] for test_url in test_urls: with self.subTest(url=test_url): ...
LookaheadTests