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
pytorch__pytorch
test/dynamo/test_subclasses.py
{ "start": 125374, "end": 131583 }
class ____(torch.nn.Module): def forward( self, primals_8: "Sym(s51)", # SubclassSizeAOTInput(base=PlainAOTInput(idx=3), idx=0) primals_10: "Sym(s55)", # SubclassStrideAOTInput(base=PlainAOTInput(idx=3), idx=1) add_2: "Sym(2*s55)", tangents_1: "f64[s64, 2*s55]", # Subclass...
GraphModule
python
huggingface__transformers
tests/models/mm_grounding_dino/test_modeling_mm_grounding_dino.py
{ "start": 9847, "end": 25966 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (MMGroundingDinoModel, MMGroundingDinoForObjectDetection) if is_torch_available() else () is_encoder_decoder = True test_missing_keys = False pipeline_model_mapping = ( { "image-feature-extract...
MMGroundingDinoModelTest
python
numpy__numpy
numpy/tests/test_numpy_config.py
{ "start": 235, "end": 1317 }
class ____: REQUIRED_CONFIG_KEYS = [ "Compilers", "Machine Information", "Python Information", ] @patch("numpy.__config__._check_pyyaml") @pytest.mark.thread_unsafe(reason="unittest.mock.patch updates global state") def test_pyyaml_not_found(self, mock_yaml_importer): ...
TestNumPyConfigs
python
tiangolo__fastapi
fastapi/openapi/models.py
{ "start": 9278, "end": 9557 }
class ____(BaseModelWithConfig): schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") example: Optional[Any] = None examples: Optional[Dict[str, Union[Example, Reference]]] = None encoding: Optional[Dict[str, Encoding]] = None
MediaType
python
PrefectHQ__prefect
src/prefect/server/orchestration/core_policy.py
{ "start": 32882, "end": 34907 }
class ____(TaskRunOrchestrationRule): """ Rejects running states if a completed state has been cached. This rule rejects transitions into a running state with a cache key if the key has already been associated with a completed state in the cache table. The client will be instructed to transition in...
CacheRetrieval
python
mlflow__mlflow
examples/llama_index/workflow/workflow/events.py
{ "start": 905, "end": 1000 }
class ____(Event): """Event for triggering the final query step""" context: str
QueryEvent
python
pandas-dev__pandas
asv_bench/benchmarks/attrs_caching.py
{ "start": 177, "end": 441 }
class ____: def setup(self): self.df = DataFrame(np.random.randn(10, 6)) self.cur_index = self.df.index def time_get_index(self): self.df.index def time_set_index(self): self.df.index = self.cur_index
DataFrameAttributes
python
pytorch__pytorch
torch/testing/_internal/common_subclass.py
{ "start": 10654, "end": 12086 }
class ____(torch.Tensor): @staticmethod def __new__(cls, src): shape = src.shape kwargs = {} kwargs["strides"] = src.stride() kwargs["storage_offset"] = src.storage_offset() kwargs["device"] = src.device kwargs["layout"] = src.layout kwargs["requires_grad"...
SubclassWithTensorFactory
python
pyinstaller__pyinstaller
bootloader/waflib/Build.py
{ "start": 30013, "end": 30209 }
class ____(BuildContext): fun = cmd = None def execute(self): self.restore() if not self.all_envs: self.load_envs() self.recurse([self.run_dir])
EnvContext
python
celery__celery
t/unit/tasks/test_result.py
{ "start": 34096, "end": 36218 }
class ____: def test_AsyncResult(self): x = self.app.AsyncResult(uuid()) assert x, result_from_tuple(x.as_tuple() == self.app) assert x, result_from_tuple(x == self.app) def test_with_parent(self): x = self.app.AsyncResult(uuid()) x.parent = self.app.AsyncResult(uuid())...
test_tuples
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-sheets/components.py
{ "start": 1439, "end": 2395 }
class ____(SinglePartitionRouter): """ Create ranges to request rows data to google sheets api. """ parameters: Mapping[str, Any] def __init__(self, parameters: Mapping[str, Any]) -> None: super().__init__(parameters) self.parameters = parameters self.sheet_row_count = para...
RangePartitionRouter
python
huggingface__transformers
tests/models/llava_onevision/test_video_processing_llava_onevision.py
{ "start": 1049, "end": 2931 }
class ____: def __init__( self, parent, batch_size=7, num_frames=8, num_channels=3, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_normalize=True, image_mean=OPENAI_CLIP_MEAN, image_std=OPENAI_CLIP_...
LlavaOnevisionVideoProcessingTester
python
pypa__warehouse
tests/unit/accounts/test_views.py
{ "start": 69611, "end": 72416 }
class ____: @pytest.mark.parametrize("next_url", [None, "/foo/bar/", "/wat/"]) def test_get_returns_empty(self, pyramid_request, next_url): if next_url is not None: pyramid_request.GET["next"] = next_url pyramid_request.user = pretend.stub() assert views.logout(pyramid_requ...
TestLogout
python
tensorflow__tensorflow
tensorflow/python/ops/numpy_ops/np_random_test.py
{ "start": 1217, "end": 1399 }
class ____(test.TestCase): def test(self): np_random.seed(1) np_random.seed(np_dtypes.int32(1)) with self.assertRaises(ValueError): np_random.seed((1, 3))
SeedTest
python
bokeh__bokeh
src/bokeh/models/expressions.py
{ "start": 7733, "end": 8561 }
class ____(CoordinateTransform): """ Transform from polar to cartesian coordinates. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) radius = NumberSpec(default=field("radius"), help=""" The radial c...
PolarTransform
python
google__jax
jax/experimental/jax2tf/tests/cross_compilation_check.py
{ "start": 2305, "end": 7400 }
class ____: """Abstracts a few IO operation over standard "open" vs. gfile.""" def __init__(self, use_gfile=False): self.use_gfile = use_gfile if use_gfile: from tensorflow.io import gfile self.gfile = gfile else: self.gfile = None def exists(self, filename: str) -> bool: if sel...
Io
python
dagster-io__dagster
python_modules/libraries/dagstermill/dagstermill/examples/repository.py
{ "start": 7676, "end": 16021 }
class ____: # This is not thread- or anything else-safe def __init__(self, path): self.closed = False self.id = str(uuid.uuid4())[-6:] self.path = path self.list = [] if not os.path.exists(self.path): self.write() self.read() self.open() d...
FilePickleList
python
numba__numba
numba/core/typing/setdecl.py
{ "start": 2387, "end": 2669 }
class ____(AbstractTemplate): def generic(self, args, kws): if len(args) != 2: return a, b = args if (isinstance(a, types.Set) and isinstance(b, types.Set) and a.dtype == b.dtype): return signature(a, *args)
SetOperator
python
pyinstaller__pyinstaller
bootloader/waflib/Logs.py
{ "start": 2048, "end": 2560 }
class ____(logging.Filter): def __init__(self, name=''): logging.Filter.__init__(self, name) def filter(self, rec): rec.zone = rec.module if rec.levelno >= logging.INFO: return True m = re_log.match(rec.msg) if m: rec.zone = m.group(1) ...
log_filter
python
doocs__leetcode
lcof/面试题62. 圆圈中最后剩下的数字/Solution.py
{ "start": 0, "end": 220 }
class ____: def lastRemaining(self, n: int, m: int) -> int: def f(n, m): if n == 1: return 0 x = f(n - 1, m) return (m + x) % n return f(n, m)
Solution
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
{ "start": 4061, "end": 25805 }
class ____(Qwen3OmniMoePreTrainedModel): input_modalities = ("image", "video", "audio", "text") def _prepare_4d_causal_attention_mask_with_cache_position( self, attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, device: to...
Qwen3OmniMoePreTrainedModelForConditionalGeneration
python
huggingface__transformers
src/transformers/models/efficientloftr/image_processing_efficientloftr_fast.py
{ "start": 3427, "end": 12189 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BILINEAR size = {"height": 480, "width": 640} default_to_square = False do_resize = True do_rescale = True rescale_factor = 1 / 255 do_normalize = None valid_kwargs = EfficientLoFTRImageProcessorKwargs def __init__(se...
EfficientLoFTRImageProcessorFast
python
pydata__xarray
asv_bench/benchmarks/datatree.py
{ "start": 64, "end": 429 }
class ____: def setup(self): run1 = DataTree.from_dict({"run1": xr.Dataset({"a": 1})}) self.d_few = {"run1": run1} self.d_many = {f"run{i}": xr.Dataset({"a": 1}) for i in range(100)} def time_from_dict_few(self): DataTree.from_dict(self.d_few) def time_from_dict_many(self):...
Datatree
python
ray-project__ray
python/ray/llm/tests/common/utils/test_callback_base.py
{ "start": 290, "end": 1338 }
class ____(CallbackBase): def __init__(self, llm_config, raise_error_on_callback: bool = True, **kwargs): super().__init__(llm_config, raise_error_on_callback, **kwargs) self.before_init_called = False self.after_init_called = False self.before_init_ctx = None self.after_init...
TestingCallback
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1574019, "end": 1574222 }
class ____(VegaLiteSchema): """Vector12string schema wrapper.""" _schema = {"$ref": "#/definitions/Vector12<string>"} def __init__(self, *args): super().__init__(*args)
Vector12string
python
django__django
django/db/backends/sqlite3/_functions.py
{ "start": 14351, "end": 14418 }
class ____(ListAggregate): finalize = statistics.pstdev
StdDevPop
python
gevent__gevent
src/gevent/greenlet.py
{ "start": 3857, "end": 5525 }
class ____(object): __slots__ = ('f_code', 'f_lineno', 'f_back') def __init__(self): self.f_code = None self.f_back = None self.f_lineno = 0 @property def f_globals(self): return None def _extract_stack(limit): try: frame = sys_getframe() except Value...
_Frame
python
huggingface__transformers
tests/models/hubert/test_modeling_hubert.py
{ "start": 21162, "end": 22199 }
class ____(unittest.TestCase): def test_compute_mask_indices(self): batch_size = 4 sequence_length = 60 mask_prob = 0.5 mask_length = 1 mask = _compute_mask_indices((batch_size, sequence_length), mask_prob, mask_length) mask = torch.from_numpy(mask).to(torch_device) ...
HubertUtilsTest
python
kamyu104__LeetCode-Solutions
Python/output-contest-matches.py
{ "start": 29, "end": 353 }
class ____(object): def findContestMatch(self, n): """ :type n: int :rtype: str """ matches = map(str, range(1, n+1)) while len(matches)/2: matches = ["({},{})".format(matches[i], matches[-i-1]) for i in xrange(len(matches)/2)] return matches[0]
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/event_api.py
{ "start": 3166, "end": 4782 }
class ____(NamedTuple): """Internal representation of an event record, as stored in a :py:class:`~dagster._core.storage.event_log.EventLogStorage`. Users should not instantiate this class directly. """ storage_id: PublicAttr[int] event_log_entry: PublicAttr[EventLogEntry] @property de...
EventLogRecord
python
langchain-ai__langchain
libs/core/langchain_core/runnables/passthrough.py
{ "start": 1465, "end": 10210 }
class ____(RunnableSerializable[Other, Other]): """Runnable to passthrough inputs unchanged or with additional keys. This `Runnable` behaves almost like the identity function, except that it can be configured to add additional keys to the output, if the input is a dict. The examples below demonstr...
RunnablePassthrough
python
huggingface__transformers
src/transformers/models/vitdet/modeling_vitdet.py
{ "start": 1201, "end": 8664 }
class ____(nn.Module): """ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial `hidden_states` (patch embeddings) to be consumed by a Transformer. """ def __init__(self, config): super().__init__() image_size, patch_size = config.pre...
VitDetEmbeddings
python
django__django
tests/migrations/migrations_test_apps/unspecified_app_with_conflict/migrations/0002_second.py
{ "start": 43, "end": 512 }
class ____(migrations.Migration): dependencies = [("unspecified_app_with_conflict", "0001_initial")] operations = [ migrations.DeleteModel("Tribble"), migrations.RemoveField("Author", "silly_field"), migrations.AddField("Author", "rating", models.IntegerField(default=0)), migrat...
Migration
python
pypa__warehouse
tests/unit/test_static.py
{ "start": 1838, "end": 5433 }
class ____: def test_no_config(self): app = pretend.stub() config = pretend.stub(registry=pretend.stub(settings={})) assert static._create_whitenoise(app, config) is app def test_creates(self, monkeypatch): app = pretend.stub() config = pretend.stub( registry...
TestCreateWhitenoise
python
spyder-ide__spyder
external-deps/python-lsp-server/pylsp/lsp.py
{ "start": 836, "end": 898 }
class ____: Unnecessary = 1 Deprecated = 2
DiagnosticTag
python
numpy__numpy
numpy/_core/tests/test_numeric.py
{ "start": 31370, "end": 32513 }
class ____: def test_default(self): err = np.geterr() assert_equal(err, {'divide': 'warn', 'invalid': 'warn', 'over': 'warn', 'under': 'ignore'} ) def test_set(self): ...
TestSeterr
python
Textualize__textual
docs/examples/themes/colored_text.py
{ "start": 155, "end": 469 }
class ____(App[None]): CSS = "\n".join(f".text-{color} {{color: $text-{color};}}" for color in COLORS) def compose(self) -> ComposeResult: for color in COLORS: yield Label(f"$text-{color}", classes=f"text-{color}") app = ColoredText() if __name__ == "__main__": app.run()
ColoredText
python
pytorch__pytorch
test/inductor/test_perf.py
{ "start": 21454, "end": 24997 }
class ____(TestCase): def test_partitioning_full_remat(self): def f(x): return x.cos().cos().cos() inp = (T(10, grad=True),) self.assertExpectedInline(count_numel_train(f, *inp), """50""") def test_partitioning_partial_remat(self): def f(a, b, c, d): x =...
MinCutPartitioningTests
python
getsentry__sentry
tests/sentry/web/frontend/test_release_webhook.py
{ "start": 3595, "end": 4205 }
class ____(ReleaseWebhookTestBase): def setUp(self) -> None: super().setUp() self.plugin_id = "builtin" def test_invalid_params(self) -> None: resp = self.client.post(self.path, content_type="application/json") assert resp.status_code == 400 def test_valid_params(self) -> N...
BuiltinReleaseWebhookTest
python
doocs__leetcode
solution/1400-1499/1462.Course Schedule IV/Solution.py
{ "start": 0, "end": 472 }
class ____: def checkIfPrerequisite( self, n: int, prerequisites: List[List[int]], queries: List[List[int]] ) -> List[bool]: f = [[False] * n for _ in range(n)] for a, b in prerequisites: f[a][b] = True for k in range(n): for i in range(n): ...
Solution
python
mwaskom__seaborn
seaborn/_core/scales.py
{ "start": 4134, "end": 7338 }
class ____(Scale): """ A scale with a discrete domain of True and False values. The behavior is similar to the :class:`Nominal` scale, but property mappings and legends will use a [True, False] ordering rather than a sort using numeric rules. Coordinate variables accomplish this by inverting ax...
Boolean
python
jina-ai__jina
tests/unit/orchestrate/flow/flow-orchestrate/test_flow_before_after.py
{ "start": 465, "end": 2629 }
class ____(Executor): @requests def foo(self, **kwargs): pass @pytest.mark.slow @pytest.mark.parametrize('protocol', ['websocket', 'grpc', 'http']) def test_flow_before(protocol): docs = random_docs(10) f = Flow(protocol=protocol).add(uses_before=MyExec, name='p1', shards=2) with f: ...
MyExec
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefault3.py
{ "start": 491, "end": 525 }
class ____(dict[T2, T1]): ...
ClassB
python
rushter__MLAlgorithms
mla/ensemble/random_forest.py
{ "start": 1687, "end": 2841 }
class ____(RandomForest): def __init__( self, n_estimators=10, max_features=None, min_samples_split=10, max_depth=None, criterion="entropy", ): super(RandomForestClassifier, self).__init__( n_estimators=n_estimators, max_features=ma...
RandomForestClassifier
python
sqlalchemy__sqlalchemy
test/sql/test_types.py
{ "start": 25328, "end": 31306 }
class ____(_UserDefinedTypeFixture, fixtures.TablesTest): __sparse_driver_backend__ = True def _data_fixture(self, connection): users = self.tables.users connection.execute( users.insert(), dict( user_id=2, goofy="jack", go...
UserDefinedRoundTripTest
python
pytorch__pytorch
torch/_inductor/comms.py
{ "start": 5387, "end": 48363 }
class ____: """ Debug info describing how an individual snode was reordered """ limiting_factor: str = "None" moves: int = 0 grouped: int = 0 grouped_info: str = "" comm_time: float = -1.0 comp_time: float = -1.0 initial_exposed: float = -1.0 final_exposed: float = -1.0 ...
ReorderInfo
python
pypa__hatch
tests/cli/build/test_build.py
{ "start": 313, "end": 44175 }
class ____: def test_standard(self, hatch, temp_dir, helpers): project_name = "My.App" with temp_dir.as_cwd(): result = hatch("new", project_name) assert result.exit_code == 0, result.output path = temp_dir / "my-app" data_path = temp_dir / "data" da...
TestOtherBackend
python
PrefectHQ__prefect
src/prefect/server/events/messaging.py
{ "start": 749, "end": 2582 }
class ____(Publisher): _publisher: Publisher def __init__(self, publisher: Publisher | None = None): self._publisher = publisher or create_publisher( topic="events", deduplicate_by="id" ) async def __aenter__(self) -> Self: await self._publisher.__aenter__() ret...
EventPublisher
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/expressions/string.py
{ "start": 1591, "end": 43647 }
class ____(Expr): class Name(IntEnum): """Internal and picklable representation of polars' `StringFunction`.""" Base64Decode = auto() Base64Encode = auto() ConcatHorizontal = auto() ConcatVertical = auto() Contains = auto() ContainsAny = auto() CountM...
StringFunction
python
huggingface__transformers
src/transformers/models/donut/modeling_donut_swin.py
{ "start": 6141, "end": 10157 }
class ____(nn.Module): """ Construct the patch and position embeddings. Optionally, also the mask token. """ def __init__(self, config, use_mask_token=False): super().__init__() self.patch_embeddings = DonutSwinPatchEmbeddings(config) num_patches = self.patch_embeddings.num_pat...
DonutSwinEmbeddings
python
bokeh__bokeh
src/bokeh/models/ui/ui_element.py
{ "start": 3864, "end": 5017 }
class ____(StyledElement): """ Base class for user interface elements. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) visible = Bool(default=True, help=""" Whether the component should be displ...
UIElement
python
Netflix__metaflow
test/test_config/config_simple2.py
{ "start": 270, "end": 1500 }
class ____(FlowSpec): cfg = Config("cfg", default_value=default_config) cfg_req = Config("cfg_req2", required=True) blur = Parameter("blur", default=cfg.blur) blur2 = Parameter("blur2", default=cfg_req.blur) cfg_non_req = Config("cfg_non_req") cfg_empty_default = Config("cfg_empty_default", def...
ConfigSimple
python
apache__airflow
task-sdk/tests/task_sdk/execution_time/test_context.py
{ "start": 6608, "end": 9983 }
class ____: def test_getattr_connection(self, mock_supervisor_comms): """ Test that the connection is fetched when accessed via __getattr__. The __getattr__ method is used for template rendering. Example: ``{{ conn.mysql_conn.host }}``. """ accessor = ConnectionAccessor() ...
TestConnectionAccessor
python
pypa__installer
src/installer/destinations.py
{ "start": 588, "end": 2935 }
class ____: """Handles writing the unpacked files, script generation and ``RECORD`` generation. Subclasses provide the concrete script generation logic, as well as the RECORD file (re)writing. """ def write_script( self, name: str, module: str, attr: str, section: "ScriptSection" ) -> ...
WheelDestination
python
django__django
tests/max_lengths/tests.py
{ "start": 129, "end": 987 }
class ____(unittest.TestCase): def verify_max_length(self, model, field, length): self.assertEqual(model._meta.get_field(field).max_length, length) def test_default_max_lengths(self): self.verify_max_length(PersonWithDefaultMaxLengths, "email", 254) self.verify_max_length(PersonWithDefa...
MaxLengthArgumentsTests
python
django__django
tests/template_tests/filter_tests/test_rjust.py
{ "start": 856, "end": 1159 }
class ____(SimpleTestCase): def test_rjust(self): self.assertEqual(rjust("test", 10), " test") def test_less_than_string_length(self): self.assertEqual(rjust("test", 3), "test") def test_non_string_input(self): self.assertEqual(rjust(123, 4), " 123")
FunctionTests
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py
{ "start": 2923, "end": 2969 }
class ____[**P, *Ts, T]: pass
TestTypeParams
python
pytorch__pytorch
torch/distributed/tensor/experimental/_context_parallel/_load_balancer.py
{ "start": 7778, "end": 13773 }
class ____(_LoadBalancer): def __init__( self, seq_length_per_doc: list[list[int]], world_size: int, device: str | torch.device, ): """ `seq_length_per_doc` has size (B, seq_len) if the load-balancing should vary within the batch. Otherwise `seq_length_per...
_PerDocumentHeadTailLoadBalancer
python
wandb__wandb
wandb/vendor/pygments/lexers/asm.py
{ "start": 12787, "end": 18297 }
class ____(RegexLexer): """ For LLVM assembly code. """ name = 'LLVM' aliases = ['llvm'] filenames = ['*.ll'] mimetypes = ['text/x-llvm'] #: optional Comment or Whitespace string = r'"[^"]*?"' identifier = r'([-a-zA-Z$._][\w\-$.]*|' + string + ')' tokens = { 'root':...
LlvmLexer
python
fsspec__filesystem_spec
fsspec/tests/abstract/get.py
{ "start": 192, "end": 20755 }
class ____: def test_get_file_to_existing_directory( self, fs, fs_join, fs_bulk_operations_scenario_0, local_fs, local_join, local_target, ): # Copy scenario 1a source = fs_bulk_operations_scenario_0 target = local_target l...
AbstractGetTests
python
walkccc__LeetCode
solutions/2422. Merge Operations to Turn Array Into a Palindrome/2422.py
{ "start": 0, "end": 492 }
class ____: def minimumOperations(self, nums: list[int]) -> int: ans = 0 l = 0 r = len(nums) - 1 leftSum = nums[0] rightSum = nums[-1] while l < r: if leftSum < rightSum: l += 1 leftSum += nums[l] ans += 1 elif leftSum > rightSum: r -= 1 rig...
Solution
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify_buffer.py
{ "start": 844, "end": 3055 }
class ____(BaseThread): """A wrapper for `Inotify` that holds events for `delay` seconds. During this time, IN_MOVED_FROM and IN_MOVED_TO events are paired. """ delay = 0.5 def __init__(self, path, recursive=False): BaseThread.__init__(self) self._queue = DelayedQueue(self.delay) ...
InotifyBuffer
python
pytorch__pytorch
test/distributed/test_functional_api.py
{ "start": 22899, "end": 24150 }
class ____( TestCollectivesWithDistributedBackend ): @property def world_size(self): return 4 @with_comms() def test_permute_tensor_with_sub_group(self, device): exit_if_lt_x_accelerators(self.world_size) mesh_dim_names = ["dp", "tp"] mesh_2d = dt.init_device_mesh( ...
TestDistributedBackendCollectivesWithWorldSize4
python
django__django
tests/middleware_exceptions/middleware.py
{ "start": 2534, "end": 2749 }
class ____(BaseMiddleware): async def process_template_response(self, request, response): response.context_data["mw"].append(self.__class__.__name__) return response
AsyncTemplateResponseMiddleware
python
crytic__slither
slither/tools/mutator/mutators/UOR.py
{ "start": 470, "end": 4001 }
class ____(AbstractMutator): # pylint: disable=too-few-public-methods NAME = "UOR" HELP = "Unary Operator Replacement" def _mutate(self) -> Dict: result: Dict = {} for ( # pylint: disable=too-many-nested-blocks function ) in self.contract.functions_and_modifiers_decla...
UOR
python
pypa__warehouse
tests/unit/admin/views/test_banners.py
{ "start": 4813, "end": 6953 }
class ____: def test_404_if_banner_does_not_exist(self, db_request): db_request.matchdict["banner_id"] = str(uuid.uuid4()) with pytest.raises(HTTPNotFound): views.delete_banner(db_request) def test_delete_banner(self, db_request): banner = BannerFactory.create() db_...
TestDeleteBanner
python
python-openxml__python-docx
src/docx/oxml/xmlchemy.py
{ "start": 15275, "end": 17317 }
class ____(_BaseChildElement): """Defines a child element belonging to a group, only one of which may appear as a child.""" @property def nsptagname(self): return self._nsptagname def populate_class_members( # pyright: ignore[reportIncompatibleMethodOverride] self, element_cls...
Choice
python
getsentry__sentry
src/sentry/sentry_apps/models/sentry_app_installation.py
{ "start": 2760, "end": 10409 }
class ____(ReplicatedControlModel, ParanoidModel): __relocation_scope__ = RelocationScope.Global category = OutboxCategory.SENTRY_APP_INSTALLATION_UPDATE sentry_app = FlexibleForeignKey("sentry.SentryApp", related_name="installations") # SentryApp's are installed and scoped to an Organization. They wi...
SentryAppInstallation
python
lxml__lxml
src/lxml/tests/test_elementtree.py
{ "start": 149660, "end": 166469 }
class ____(unittest.TestCase): etree = None maxDiff = None if not hasattr(unittest.TestCase, 'subTest'): @contextmanager def subTest(self, name, **kwargs): try: yield except unittest.SkipTest: raise except Exception as e: ...
_C14NTest
python
ray-project__ray
rllib/examples/envs/classes/recommender_system_envs_with_recsim.py
{ "start": 2552, "end": 3386 }
class ____(iev.IEvVideo): def __init__(self, doc_id, features, video_length=None, quality=None): super(SingleClusterIEvVideo, self).__init__( doc_id=doc_id, features=features, cluster_id=0, # single cluster. video_length=video_length, quality=qual...
SingleClusterIEvVideo
python
MongoEngine__mongoengine
mongoengine/base/utils.py
{ "start": 619, "end": 939 }
class ____(list): """Simple utility class to compare lists without considering order (useful in context of indexes)""" def __eq__(self, other): if isinstance(other, list): # Compare sorted versions of the lists return sorted(self) == sorted(other) return False
NonOrderedList
python
getsentry__sentry
tests/sentry/data_export/endpoints/test_data_export_details.py
{ "start": 355, "end": 5807 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-data-export-details" def setUp(self) -> None: self.user = self.create_user() self.organization = self.create_organization(owner=self.user) self.login_as(user=self.user) self.data_export = ExportedData.objects.create(...
DataExportDetailsTest
python
numpy__numpy
numpy/_core/tests/test_defchararray.py
{ "start": 4430, "end": 4623 }
class ____: def test_it(self): A = np.array('abc1', dtype='c').view(np.char.chararray) assert_equal(A.shape, (4,)) assert_equal(A.upper()[:2].tobytes(), b'AB')
TestChar
python
pytorch__pytorch
torch/_dynamo/source.py
{ "start": 31514, "end": 32045 }
class ____(ChainedSource): def __post_init__(self) -> None: assert self.base is not None def reconstruct(self, codegen: "PyCodegen") -> None: codegen.add_push_null(lambda: codegen.load_import_from("builtins", "type")) codegen(self.base) codegen.extend_output(create_call_function...
TypeSource
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/asset.py
{ "start": 1136, "end": 1275 }
class ____(BaseModel): """Asset alias schema with fields that are needed for Runtime.""" name: str group: str
AssetAliasResponse
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 188694, "end": 193662 }
class ____(rv_continuous): r"""An asymmetric Laplace continuous random variable. %(before_notes)s See Also -------- laplace : Laplace distribution Notes ----- The probability density function for `laplace_asymmetric` is .. math:: f(x, \kappa) &= \frac{1}{\kappa+\kappa^{-1...
laplace_asymmetric_gen
python
django__django
django/forms/widgets.py
{ "start": 15741, "end": 18445 }
class ____(FileInput): clear_checkbox_label = _("Clear") initial_text = _("Currently") input_text = _("Change") template_name = "django/forms/widgets/clearable_file_input.html" checked = False use_fieldset = True def clear_checkbox_name(self, name): """ Given the name of the...
ClearableFileInput
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 109231, "end": 109354 }
class ____(BaseModel, extra="forbid"): scalar: "ScalarQuantizationConfig" = Field(..., description="")
ScalarQuantization
python
ansible__ansible
lib/ansible/module_utils/facts/hardware/hpux.py
{ "start": 8345, "end": 8504 }
class ____(HardwareCollector): _fact_class = HPUXHardware _platform = 'HP-UX' required_facts = set(['platform', 'distribution'])
HPUXHardwareCollector
python
langchain-ai__langchain
libs/core/tests/unit_tests/test_tools.py
{ "start": 23282, "end": 33106 }
class ____(BaseTool): name: str = "exception" description: str = "an exception-throwing tool" exception: Exception = ToolException() def _run(self) -> str: raise self.exception async def _arun(self) -> str: raise self.exception def test_exception_handling_bool() -> None: tool...
_FakeExceptionTool
python
pennersr__django-allauth
tests/apps/socialaccount/providers/foursquare/tests.py
{ "start": 248, "end": 2716 }
class ____(OAuth2TestsMixin, TestCase): provider_id = FoursquareProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """ {"notifications": [{"item": {"unreadCount": 0}, "type": "notificationTray"}], "meta": {"code": 200...
FoursquareTests
python
python-openxml__python-docx
src/docx/text/tabstops.py
{ "start": 134, "end": 2445 }
class ____(ElementProxy): """A sequence of |TabStop| objects providing access to the tab stops of a paragraph or paragraph style. Supports iteration, indexed access, del, and len(). It is accesed using the :attr:`~.ParagraphFormat.tab_stops` property of ParagraphFormat; it is not intended to be con...
TabStops
python
jmcnamara__XlsxWriter
xlsxwriter/shape.py
{ "start": 326, "end": 13639 }
class ____: """ A class for to represent Excel XLSX shape objects. """ ########################################################################### # # Public API. # ########################################################################### def __init__(self, shape_type, name: st...
Shape
python
Netflix__metaflow
metaflow/package/__init__.py
{ "start": 1384, "end": 26384 }
class ____(object): def __init__( self, flow, environment, echo, suffixes: Optional[List[str]] = DEFAULT_SUFFIXES_LIST, user_code_filter: Optional[Callable[[str], bool]] = None, flow_datastore: Optional["metaflow.datastore.FlowDataStore"] = None, mfcon...
MetaflowPackage
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_dlp.py
{ "start": 2398, "end": 51534 }
class ____: def setup_method(self): with mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__", new=mock_base_gcp_hook_no_default_project_id, ): self.hook = CloudDLPHook(gcp_conn_id="test") @mock.patch("airflow.providers.goog...
TestCloudDLPHook
python
xlwings__xlwings
xlwings/constants.py
{ "start": 111964, "end": 112195 }
class ____: xlLocalSessionChanges = 2 # from enum XlSaveConflictResolution xlOtherSessionChanges = 3 # from enum XlSaveConflictResolution xlUserResolution = 1 # from enum XlSaveConflictResolution
SaveConflictResolution
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 24513, "end": 24765 }
class ____(Structure): _fields_ = ( ("name", lc_str), ("timestamp", mach_timestamp_helper), ("current_version", mach_version_helper), ("compatibility_version", mach_version_helper), ) # merged dylib structure
dylib
python
mwaskom__seaborn
seaborn/_core/exceptions.py
{ "start": 180, "end": 1179 }
class ____(RuntimeError): """ Error class raised from seaborn.objects.Plot for compile-time failures. In the declarative Plot interface, exceptions may not be triggered immediately by bad user input (and validation at input time may not be possible). This class is used to signal that indirect depen...
PlotSpecError
python
xlwings__xlwings
xlwings/constants.py
{ "start": 16066, "end": 16489 }
class ____: xlDiagonalDown = 5 # from enum XlBordersIndex xlDiagonalUp = 6 # from enum XlBordersIndex xlEdgeBottom = 9 # from enum XlBordersIndex xlEdgeLeft = 7 # from enum XlBordersIndex xlEdgeRight = 10 # from enum XlBordersIndex xlEdgeTop = 8 # from enum XlBordersIndex xlInsideHoriz...
BordersIndex
python
pypa__warehouse
tests/unit/forklift/test_legacy.py
{ "start": 3775, "end": 6384 }
class ____: def test_exc_with_message(self): exc = legacy._exc_with_message(HTTPBadRequest, "My Test Message.") assert isinstance(exc, HTTPBadRequest) assert exc.status_code == 400 assert exc.status == "400 My Test Message." def test_exc_with_exotic_message(self): exc = ...
TestExcWithMessage
python
joblib__joblib
joblib/_store_backends.py
{ "start": 1349, "end": 4290 }
class ____(metaclass=ABCMeta): """Helper Abstract Base Class which defines all methods that a StorageBackend must implement.""" location = None @abstractmethod def _open_item(self, f, mode): """Opens an item on the store and return a file-like object. This method is private and on...
StoreBackendBase
python
streamlit__streamlit
lib/tests/streamlit/elements/pydeck_test.py
{ "start": 7606, "end": 13888 }
class ____(DeltaGeneratorTestCase): """Test pydeck_chart width parameter functionality.""" @parameterized.expand( [ # width, expected_width_spec, expected_width_value ("stretch", "use_stretch", True), (500, "pixel_width", 500), ] ) def test_width_para...
PyDeckChartWidthTest
python
apache__airflow
airflow-core/src/airflow/utils/operator_helpers.py
{ "start": 948, "end": 4455 }
class ____: """ Wrapper representing ``**kwargs`` to a callable. The actual ``kwargs`` can be obtained by calling either ``unpacking()`` or ``serializing()``. They behave almost the same and are only different if the containing ``kwargs`` is an Airflow Context object, and the calling function u...
KeywordParameters
python
getsentry__sentry
src/sentry/integrations/slack/integration.py
{ "start": 4378, "end": 8103 }
class ____(IntegrationProvider): key = IntegrationProviderSlug.SLACK.value name = "Slack" metadata = metadata features = frozenset([IntegrationFeatures.CHAT_UNFURL, IntegrationFeatures.ALERT_RULE]) integration_cls = SlackIntegration # some info here: https://api.slack.com/authentication/quickst...
SlackIntegrationProvider
python
django__django
tests/model_inheritance/models.py
{ "start": 3760, "end": 3834 }
class ____(Base): sub_id = models.IntegerField(primary_key=True)
SubBase
python
google__jax
tests/custom_partitioning_sharding_rule_test.py
{ "start": 952, "end": 3794 }
class ____(jtu.JaxTestCase): def test_compound_factor_not_enough_factors(self): with self.assertRaisesRegex(ValueError, "A compound factor should contain at least two factors"): CompoundFactor("i") def test_compound_factor_batching_now_allowed(self): with self.assertRaisesRegex(ValueError, "Ellipsis ...
SdyShardingRuleTest
python
plotly__plotly.py
plotly/graph_objs/scatterpolar/marker/colorbar/_tickfont.py
{ "start": 233, "end": 9979 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterpolar.marker.colorbar" _path_str = "scatterpolar.marker.colorbar.tickfont" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", ...
Tickfont
python
sphinx-doc__sphinx
sphinx/ext/apidoc/_shared.py
{ "start": 1909, "end": 2908 }
class ____: """Default values for apidoc options.""" exclude_patterns: list[str] automodule_options: frozenset[str] max_depth: int follow_links: bool separate_modules: bool include_private: bool no_headings: bool module_first: bool implicit_namespaces: bool @classmethod ...
ApidocDefaults
python
huggingface__transformers
src/transformers/models/led/modeling_led.py
{ "start": 47912, "end": 48671 }
class ____(PreTrainedModel): config: LEDConfig base_model_prefix = "led" supports_gradient_checkpointing = True @property def dummy_inputs(self): pad_token = self.config.pad_token_id input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device) d...
LEDPreTrainedModel
python
ray-project__ray
python/ray/serve/_private/common.py
{ "start": 23779, "end": 25501 }
class ____: replica_id: ReplicaID node_id: Optional[str] node_ip: Optional[str] availability_zone: Optional[str] actor_name: str max_ongoing_requests: int is_cross_language: bool = False multiplexed_model_ids: List[str] = field(default_factory=list) routing_stats: Dict[str, Any] = fi...
RunningReplicaInfo