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
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/schema.py
{ "start": 139715, "end": 140482 }
class ____(ColumnDefault): """default generator for a SQL expression .. versionadded:: 2.0 """ is_clause_element = True has_arg = True arg: _SQLExprDefault def __init__( self, arg: _SQLExprDefault, for_update: bool = False, ) -> None: self.for_update =...
ColumnElementColumnDefault
python
huggingface__transformers
tests/models/llama4/test_modeling_llama4.py
{ "start": 1094, "end": 5205 }
class ____(unittest.TestCase): model_id = "meta-llama/Llama-4-Scout-17B-16E" @classmethod def setUpClass(cls): cls.model = Llama4ForConditionalGeneration.from_pretrained( "meta-llama/Llama-4-Scout-17B-16E", device_map="auto", dtype=torch.float32, attn...
Llama4IntegrationTest
python
huggingface__transformers
src/transformers/models/mobilenet_v2/modeling_mobilenet_v2.py
{ "start": 8918, "end": 12939 }
class ____(MobileNetV2PreTrainedModel): def __init__(self, config: MobileNetV2Config, add_pooling_layer: bool = True): r""" add_pooling_layer (bool, *optional*, defaults to `True`): Whether to add a pooling layer """ super().__init__(config) self.config = config ...
MobileNetV2Model
python
jazzband__django-polymorphic
src/polymorphic/admin/childadmin.py
{ "start": 325, "end": 427 }
class ____(RuntimeError): "The admin site for the model is not registered."
ParentAdminNotRegistered
python
huggingface__transformers
src/transformers/models/deepseek_v2/modular_deepseek_v2.py
{ "start": 21821, "end": 22073 }
class ____(LlamaForSequenceClassification): pass __all__ = [ "DeepseekV2PreTrainedModel", "DeepseekV2Model", "DeepseekV2ForCausalLM", "DeepseekV2ForSequenceClassification", "DeepseekV2Config", ]
DeepseekV2ForSequenceClassification
python
openai__openai-python
tests/test_transform.py
{ "start": 3609, "end": 3925 }
class ____(TypedDict): bar: Annotated[str, PropertyInfo(alias="Bar")] @parametrize @pytest.mark.asyncio async def test_includes_unknown_keys(use_async: bool) -> None: assert await transform({"bar": "bar", "baz_": {"FOO": 1}}, Foo6, use_async) == { "Bar": "bar", "baz_": {"FOO": 1}, }
Foo6
python
huggingface__transformers
src/transformers/models/edgetam_video/modeling_edgetam_video.py
{ "start": 52243, "end": 55035 }
class ____(nn.Module): def __init__(self, config: EdgeTamVideoConfig): super().__init__() self.config = config self.hidden_size = config.perceiver_resampler_hidden_size self.num_attention_heads = config.perceiver_resampler_num_attention_heads self.head_dim = config.perceiver_...
EdgeTamVideoPerceiverAttention
python
pytorch__pytorch
torch/cuda/_sanitizer.py
{ "start": 4408, "end": 4689 }
class ____(Exception): """Wrapper class for errors reported by CUDA Sanitizer.""" def __init__(self, errors: list[SynchronizationError]): self.errors = errors def __str__(self): return f"detected {len(self.errors)} errors" @dataclass
CUDASanitizerErrors
python
ZoranPandovski__al-go-rithms
machine_learning/cluster_analysis/k-means/python/model/k_point.py
{ "start": 24, "end": 582 }
class ____: def __init__(self, x: float, y: float): self.x=x self.y=y self.centroid = None def distance_to(self,point): return sqrt(pow(self.x-point.x,2)+pow(self.y-point.y,2)) def set_centroid(self,centroid): self.centroid=centroid def __repr__(self): ...
KPoint2D
python
PrefectHQ__prefect
tests/server/orchestration/api/test_workers.py
{ "start": 16440, "end": 34158 }
class ____: async def test_update_work_pool(self, client, session, work_pool): response = await client.patch( f"/work_pools/{work_pool.name}", json=dict(is_paused=True, concurrency_limit=5), ) assert response.status_code == status.HTTP_204_NO_CONTENT, response.text ...
TestUpdateWorkPool
python
crytic__slither
slither/utils/halstead.py
{ "start": 4882, "end": 7911 }
class ____: """Class to hold the Halstead metrics for all contracts. Contains methods useful for reporting. There are 3 sections in the report: 1. Core metrics (n1, n2, N1, N2) 2. Extended metrics 1 (n, N, S, V) 3. Extended metrics 2 (D, E, T, B) """ contracts: List[Contract] = field(defa...
HalsteadMetrics
python
scipy__scipy
scipy/signal/tests/test_signaltools.py
{ "start": 71852, "end": 94744 }
class ____: def generate(self, shape, xp): prodshape = shape if isinstance(shape, int) else math.prod(shape) x = xp.linspace(0, prodshape - 1, prodshape) if not isinstance(shape, int): x = xp.reshape(x, shape) return self.convert_dtype(x, xp) def convert_dtype(self, ...
_TestLinearFilter
python
pyca__cryptography
src/cryptography/hazmat/primitives/asymmetric/dh.py
{ "start": 2422, "end": 3912 }
class ____(metaclass=abc.ABCMeta): @property @abc.abstractmethod def key_size(self) -> int: """ The bit length of the prime modulus. """ @abc.abstractmethod def public_key(self) -> DHPublicKey: """ The DHPublicKey associated with this private key. """...
DHPrivateKey
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-mcp/llama_index/tools/mcp/base.py
{ "start": 512, "end": 8240 }
class ____( BaseToolSpec, TypeResolutionMixin, TypeCreationMixin, FieldExtractionMixin ): """ MCPToolSpec will get the tools from MCP Client (only need to implement ClientSession) and convert them to LlamaIndex's FunctionTool objects. Args: client: An MCP client instance implementing ClientSess...
McpToolSpec
python
django__django
tests/apps/apps.py
{ "start": 530, "end": 612 }
class ____(AppConfig): name = "apps" label = "relabeled"
RelabeledAppsConfig
python
getsentry__sentry
src/sentry/integrations/gitlab/webhooks.py
{ "start": 3307, "end": 5012 }
class ____(SCMWebhook, ABC): @property def provider(self) -> str: return IntegrationProviderSlug.GITLAB.value def get_repo( self, integration: RpcIntegration, organization: RpcOrganization, event: Mapping[str, Any] ): """ Given a webhook payload, get the associated Repos...
GitlabWebhook
python
plotly__plotly.py
plotly/graph_objs/layout/scene/_yaxis.py
{ "start": 235, "end": 76693 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.scene" _path_str = "layout.scene.yaxis" _valid_props = { "autorange", "autorangeoptions", "autotypenumbers", "backgroundcolor", "calendar", "categoryarray", "categoryarraysrc", "c...
YAxis
python
Lightning-AI__lightning
tests/tests_pytorch/checkpointing/test_model_checkpoint.py
{ "start": 35120, "end": 35229 }
class ____(BoringModel): def on_fit_end(self): raise RuntimeError("Trouble!")
TroubledModelOnFitEnd
python
huggingface__transformers
src/transformers/models/markuplm/modeling_markuplm.py
{ "start": 34640, "end": 39769 }
class ____(MarkupLMPreTrainedModel): # Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification.__init__ with bert->markuplm, Bert->MarkupLM def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.config = config self...
MarkupLMForSequenceClassification
python
Pylons__pyramid
tests/test_view.py
{ "start": 30596, "end": 32030 }
class ____(unittest.TestCase): def test_it(self): from pyramid.view import view_defaults @view_defaults(route_name='abc', renderer='def') class Foo: pass self.assertEqual(Foo.__view_defaults__['route_name'], 'abc') self.assertEqual(Foo.__view_defaults__['rendere...
Test_view_defaults
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
{ "start": 71433, "end": 73558 }
class ____(GradientCheckpointingLayer): def __init__(self, config, layer_idx): super().__init__() self.self_attn = Qwen3OmniMoeThinkerTextAttention(config, layer_idx) if (layer_idx not in config.mlp_only_layers) and ( config.num_experts > 0 and (layer_idx + 1) % config.decoder_sp...
Qwen3OmniMoeThinkerTextDecoderLayer
python
pyparsing__pyparsing
tests/test_examples.py
{ "start": 115, "end": 1637 }
class ____(unittest.TestCase): def _run(self, name): mod = import_module("examples." + name) # use pyparsing context to reset each test to clean # pyparsing settings with ppt.reset_pyparsing_context(): getattr(mod, "main", lambda *args, **kwargs: None)() def test_nu...
TestExamples
python
mlflow__mlflow
mlflow/system_metrics/metrics/cpu_monitor.py
{ "start": 138, "end": 776 }
class ____(BaseMetricsMonitor): """Class for monitoring CPU stats.""" def collect_metrics(self): # Get CPU metrics. cpu_percent = psutil.cpu_percent() self._metrics["cpu_utilization_percentage"].append(cpu_percent) system_memory = psutil.virtual_memory() self._metrics["...
CPUMonitor
python
pytorch__pytorch
tools/linter/adapters/pyproject_linter.py
{ "start": 536, "end": 8081 }
class ____(NamedTuple): path: str | None line: int | None char: int | None code: str severity: LintSeverity name: str original: str | None replacement: str | None description: str | None def format_error_message( filename: str, error: Exception | None = None, *, mes...
LintMessage
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_theme01.py
{ "start": 315, "end": 1326 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("theme01.xlsx") def test_create_file(self): """Test the addition of a theme file.""" workbook = Workbook(self.got_filename) ...
TestCompareXLSXFiles
python
Lightning-AI__lightning
tests/tests_pytorch/callbacks/test_early_stopping.py
{ "start": 20348, "end": 25650 }
class ____(BoringModel): def __init__(self): super().__init__() self.epoch_losses = [5.0, 4.0, 3.0, 2.0, 1.0] def on_validation_epoch_end(self): loss = self.epoch_losses[self.current_epoch] if self.current_epoch < len(self.epoch_losses) else 0.1 self.log("val_loss", loss) @pyt...
ModelWithImprovingLoss
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/datacatalog.py
{ "start": 7421, "end": 12688 }
class ____(GoogleCloudBaseOperator): """ Creates an EntryGroup. The newly created entry group ID are saved under the ``entry_group_id`` key in XCOM. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDataCatalogCreateEntry...
CloudDataCatalogCreateEntryGroupOperator
python
pandas-dev__pandas
pandas/io/json/_json.py
{ "start": 7711, "end": 8661 }
class ____(Writer): _default_orient = "columns" @property def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]: if not self.index and self.orient == "split": obj_to_write = self.obj.to_dict(orient="split") del obj_to_write["index"] else: obj_to_wr...
FrameWriter
python
psf__requests
tests/test_requests.py
{ "start": 87587, "end": 90221 }
class ____: def test_stream_timeout(self, httpbin): try: requests.get(httpbin("delay/10"), timeout=2.0) except requests.exceptions.Timeout as e: assert "Read timed out" in e.args[0].args[0] @pytest.mark.parametrize( "timeout, error_text", ( ((...
TestTimeout
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 602209, "end": 602534 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("RepositoryTopic", graphql_name="node")
RepositoryTopicEdge
python
walkccc__LeetCode
solutions/30. Substring with Concatenation of All Words/30.py
{ "start": 0, "end": 531 }
class ____: def findSubstring(self, s: str, words: list[str]) -> list[int]: if len(s) == 0 or words == []: return [] k = len(words) n = len(words[0]) ans = [] count = collections.Counter(words) for i in range(len(s) - k * n + 1): seen = collections.defaultdict(int) j = 0 ...
Solution
python
geekcomputers__Python
venv/Lib/site-packages/pip/_internal/resolution/resolvelib/provider.py
{ "start": 2804, "end": 9935 }
class ____(_ProviderBase): """Pip's provider implementation for resolvelib. :params constraints: A mapping of constraints specified by the user. Keys are canonicalized project names. :params ignore_dependencies: Whether the user specified ``--no-deps``. :params upgrade_strategy: The user-specif...
PipProvider
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_validation__property.py
{ "start": 2929, "end": 11283 }
class ____: # test_Any unnecessary (no validation) # TODO (bev) test_Image def test_Angle(self) -> None: p = Angle() with pytest.raises(ValueError) as e: p.validate("junk") assert matches(str(e.value), r"expected a value of type Real, got junk of type str") def test...
TestValidateDetailDefault
python
pytorch__pytorch
test/backends/xeon/test_launch.py
{ "start": 231, "end": 2572 }
class ____(TestCase): def setUp(self): super().setUp() self._test_dir = tempfile.mkdtemp(prefix=self.__class__.__name__) def tearDown(self): shutil.rmtree(self._test_dir) def test_cpu_info(self): lscpu_info = """# The following is the parsable format, which can be fed to ot...
TestTorchrun
python
dask__distributed
distributed/worker_state_machine.py
{ "start": 15550, "end": 15678 }
class ____(SendMessageToScheduler): op = "add-keys" __slots__ = ("keys",) keys: Collection[Key] @dataclass
AddKeysMsg
python
davidhalter__parso
parso/tree.py
{ "start": 11736, "end": 11923 }
class ____(Leaf): __slots__ = ('type',) def __init__(self, type, value, start_pos, prefix=''): super().__init__(value, start_pos, prefix) self.type = type
TypedLeaf
python
jina-ai__jina
jina/orchestrate/pods/__init__.py
{ "start": 662, "end": 9852 }
class ____(ABC): """ :class:`BasePod` is an interface from which all the classes managing the lifetime of a Runtime inside a local process, container must inherit. It exposes the required APIs so that the `BasePod` can be handled by the `cli` api as a context manager or by a `Deployment`. What mak...
BasePod
python
ray-project__ray
rllib/env/wrappers/dm_control_wrapper.py
{ "start": 7595, "end": 8025 }
class ____(gym.ActionWrapper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._low = -1.0 self._high = 1.0 self.action_space = gym.spaces.Box( self._low, self._high, self.action_space.shape, self.action_spac...
ActionClip
python
doocs__leetcode
solution/3400-3499/3494.Find the Minimum Amount of Time to Brew Potions/Solution.py
{ "start": 0, "end": 434 }
class ____: def minTime(self, skill: List[int], mana: List[int]) -> int: max = lambda a, b: a if a > b else b n = len(skill) f = [0] * n for x in mana: tot = 0 for i in range(n): tot = max(tot, f[i]) + skill[i] * x f[-1] = tot ...
Solution
python
ansible__ansible
test/lib/ansible_test/_internal/cli/parsers/key_value_parsers.py
{ "start": 8395, "end": 9270 }
class ____(KeyValueParser): """Composite argument parser for POSIX SSH host key/value pairs.""" def get_parsers(self, state: ParserState) -> dict[str, Parser]: """Return a dictionary of key names and value parsers.""" return dict( python=PythonParser(versions=list(SUPPORTED_PYTHON_V...
PosixSshKeyValueParser
python
HIPS__autograd
autograd/builtins.py
{ "start": 3390, "end": 3502 }
class ____(tuple_, metaclass=TupleMeta): def __new__(cls, xs): return make_sequence(tuple_, *xs)
tuple
python
pymupdf__PyMuPDF
src/table.py
{ "start": 12729, "end": 13714 }
class ____: """ A TextMap maps each unicode character in the text to an individual `char` object (or, in the case of layout-implied whitespace, `None`). """ def __init__(self, tuples=None) -> None: self.tuples = tuples self.as_string = "".join(map(itemgetter(0), tuples)) def ma...
TextMap
python
apache__airflow
task-sdk/src/airflow/sdk/bases/decorator.py
{ "start": 5358, "end": 11850 }
class ____(BaseOperator): """ Wraps a Python callable and captures args/kwargs when called for execution. :param python_callable: A reference to an object that is callable :param op_kwargs: a dictionary of keyword arguments that will get unpacked in your function (templated) :param op_args:...
DecoratedOperator
python
psf__black
tests/data/cases/preview_long_strings__regression.py
{ "start": 6071, "end": 10353 }
class ____: def xxxx_xxx_xx_xxxxxxxxxx_xxxx_xxxxxxxxx(xxxx): xxxxxxxx = [ xxxxxxxxxxxxxxxx( 'xxxx', xxxxxxxxxxx={ 'xxxx' : 1.0, }, xxxxxx={'xxxxxx 1' : xxxxxx(xxxx='xxxxxx 1', xxxxxx=600.0)}, xxxx...
A
python
pytorch__pytorch
torch/compiler/_cache.py
{ "start": 496, "end": 1768 }
class ____(ABC): """ Data for each cache artifact that will be serialized and deserialized """ key: str content: bytes = dataclasses.field(repr=False) # Do not display potential binary @staticmethod def serialize(writer: BytesWriter, cls: "CacheArtifact") -> None: writer.write_str...
CacheArtifact
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 861554, "end": 862324 }
class ____(sgqlc.types.relay.Connection): """The connection type for ProjectV2SortByField.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("ProjectV2SortByFieldEdge"), graphql_name="edges") """A list of edg...
ProjectV2SortByFieldConnection
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 17053, "end": 17310 }
class ____(DagsterError): """Indicates the resolved executor is incompatible with the state of other systems such as the :py:class:`~dagster._core.instance.DagsterInstance` or system storage configuration. """
DagsterUnmetExecutorRequirementsError
python
spack__spack
lib/spack/spack/test/spec_semantics.py
{ "start": 3980, "end": 100097 }
class ____: """Test satisfies(), intersects(), constrain() and other semantic operations on specs.""" @pytest.mark.parametrize( "lhs,rhs,expected", [ ("libelf@0.8.13", "@0:1", "libelf@0.8.13"), ("libdwarf^libelf@0.8.13", "^libelf@0:1", "libdwarf^libelf@0.8.13"), ...
TestSpecSemantics
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_test.py
{ "start": 4248, "end": 6591 }
class ____(test.TestCase): def test_prune_unconnected_ops(self): with ops.Graph().as_default(): a = array_ops.placeholder(dtype=dtypes.float32, name="a") b = array_ops.placeholder(dtype=dtypes.float32, name="b") constant_op.constant(1.0, name="constant") x = variable_scope.get_variable( ...
TPUGraphPruneTest
python
ray-project__ray
rllib/env/policy_client.py
{ "start": 883, "end": 6615 }
class ____: """REST client to interact with an RLlib policy server.""" def __init__( self, address: str, inference_mode: str = "local", update_interval: float = 10.0, session: Optional[requests.Session] = None, ): self.address = address self.session =...
PolicyClient
python
astropy__astropy
astropy/io/fits/verify.py
{ "start": 566, "end": 3809 }
class ____: """ Shared methods for verification. """ def run_option( self, option="warn", err_text="", fix_text="Fixed.", fix=None, fixable=True ): """ Execute the verification with selected option. """ text = err_text if option in ["warn", "exceptio...
_Verify
python
walkccc__LeetCode
solutions/2451. Odd String Difference/2451.py
{ "start": 0, "end": 465 }
class ____: def oddString(self, words: list[str]) -> str: def getDiff(s: str) -> list[int]: return [ord(b) - ord(a) for a, b in zip(s, s[1:])] wordAndDiffTuples = [(word, tuple(getDiff(word))) for word in words] diffTupleCount = collections.Counter() for _, diffTuple in wordAndDiffTuples: ...
Solution
python
apache__avro
lang/py/avro/codecs.py
{ "start": 2835, "end": 3133 }
class ____(Codec): @staticmethod def compress(data: bytes) -> Tuple[bytes, int]: return data, len(data) @staticmethod def decompress(readers_decoder: avro.io.BinaryDecoder) -> avro.io.BinaryDecoder: readers_decoder.skip_long() return readers_decoder
NullCodec
python
ansible__ansible
lib/ansible/plugins/inventory/advanced_host_list.py
{ "start": 905, "end": 2273 }
class ____(BaseInventoryPlugin): NAME = 'advanced_host_list' # advanced_host_list does not set vars, so needs no special trust assistance from the inventory API def verify_file(self, host_list): valid = False b_path = to_bytes(host_list, errors='surrogate_or_strict') if not os.pa...
InventoryModule
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-litellm/llama_index/llms/litellm/base.py
{ "start": 1854, "end": 21207 }
class ____(FunctionCallingLLM): """ LiteLLM. Examples: `pip install llama-index-llms-litellm` ```python import os from llama_index.core.llms import ChatMessage from llama_index.llms.litellm import LiteLLM # Set environment variables os.environ["OPEN...
LiteLLM
python
realpython__materials
oop-in-java-vs-python/car.py
{ "start": 334, "end": 521 }
class ____: """The Device class defines objects which have a battery.""" def __init__(self): """Define the base voltage for our device.""" self._voltage = 12
Device
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1023269, "end": 1024033 }
class ____(sgqlc.types.Type): """Autogenerated return type of UpdateEnterpriseMembersCanMakePurchasesSetting """ __schema__ = github_schema __field_names__ = ("client_mutation_id", "enterprise", "message") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A ...
UpdateEnterpriseMembersCanMakePurchasesSettingPayload
python
tiangolo__fastapi
docs_src/handling_errors/tutorial003.py
{ "start": 82, "end": 626 }
class ____(Exception): def __init__(self, name: str): self.name = name app = FastAPI() @app.exception_handler(UnicornException) async def unicorn_exception_handler(request: Request, exc: UnicornException): return JSONResponse( status_code=418, content={"message": f"Oops! {exc.name} d...
UnicornException
python
django__django
tests/middleware/tests.py
{ "start": 16823, "end": 21023 }
class ____(SimpleTestCase): rf = RequestFactory() def setUp(self): self.req = self.rf.get("/regular_url/that/does/not/exist") def get_response(self, req): return self.client.get(req.path) def test_404_error_reporting(self): self.req.META["HTTP_REFERER"] = "/another/url/" ...
BrokenLinkEmailsMiddlewareTest
python
getsentry__sentry
src/sentry/management/commands/generate_controlsilo_urls.py
{ "start": 604, "end": 1495 }
class ____: callable: Callable pattern: str name: str | None @property def url_name(self) -> str: return self.name or "" def describe_pattern(pattern): return str(pattern.pattern) # Matches (?P<name>[pattern]) style expressions. named_group_matcher = re.compile(r"\(\?P(<\w+>)([^\)]+...
PatternInfo
python
fluentpython__example-code
16-coroutine/taxi_sim0.py
{ "start": 2297, "end": 10112 }
class ____: def __init__(self, procs_map): self.events = queue.PriorityQueue() self.procs = dict(procs_map) def run(self, end_time): # <1> """Schedule and display events until time is up""" # schedule the first event for each cab for _, proc in sorted(self.procs.items...
Simulator
python
econchick__interrogate
src/interrogate/visit.py
{ "start": 1441, "end": 9301 }
class ____(ast.NodeVisitor): """NodeVisitor for a Python file to find docstrings. :param str filename: filename to parse coverage. :param config.InterrogateConfig config: configuration. """ def __init__(self, filename: str, config: InterrogateConfig): self.filename = filename self....
CoverageVisitor
python
facebook__pyre-check
client/language_server/protocol.py
{ "start": 1086, "end": 1217 }
class ____(json_rpc.JSONRPCException): @override def error_code(self) -> int: return -32002
ServerNotInitializedError
python
huggingface__transformers
src/transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py
{ "start": 27658, "end": 28501 }
class ____(Wav2Vec2ConformerPreTrainedModel, Wav2Vec2Model): def __init__(self, config: Wav2Vec2ConformerConfig): Wav2Vec2ConformerPreTrainedModel.__init__(self, config) self.config = config self.feature_extractor = Wav2Vec2ConformerFeatureEncoder(config) self.feature_projection = Wa...
Wav2Vec2ConformerModel
python
streamlit__streamlit
lib/tests/streamlit/runtime/websocket_session_manager_test.py
{ "start": 924, "end": 1833 }
class ____(SessionStorage): """A simple SessionStorage implementation used for testing. Essentially just a thin wrapper around a dict. This class exists so that we don't accidentally have our WebsocketSessionManager tests rely on a real SessionStorage implementation. """ def __init__(self): ...
MockSessionStorage
python
getsentry__sentry
src/sentry_plugins/sessionstack/plugin.py
{ "start": 6575, "end": 6645 }
class ____(ContextType): type = "sessionstack"
SessionStackContextType
python
PrefectHQ__prefect
src/integrations/prefect-sqlalchemy/prefect_sqlalchemy/credentials.py
{ "start": 4970, "end": 7359 }
class ____(BaseModel): """ Parameters to use to create a SQLAlchemy engine URL. Attributes: driver: The driver name to use. database: The name of the database to use. username: The user name used to authenticate. password: The password used to authenticate. host: The...
ConnectionComponents
python
readthedocs__readthedocs.org
readthedocs/integrations/migrations/0013_set_timestamp_fields_as_no_null.py
{ "start": 184, "end": 1071 }
class ____(migrations.Migration): safe = Safe.always() dependencies = [ ("integrations", "0012_migrate_timestamp_fields"), ] operations = [ migrations.AlterField( model_name="integration", name="created", field=django_extensions.db.fields.CreationDat...
Migration
python
sympy__sympy
sympy/integrals/manualintegrate.py
{ "start": 15523, "end": 15875 }
class ____(OrthogonalPolyRule): a: Expr b: Expr def eval(self) -> Expr: n, a, b, x = self.n, self.a, self.b, self.variable return Piecewise( (2*jacobi(n + 1, a - 1, b - 1, x)/(n + a + b), Ne(n + a + b, 0)), (x, Eq(n, 0)), ((a + b + 2)*x**2/4 + (a - b)*x/2...
JacobiRule
python
pytorch__pytorch
torch/distributed/pipelining/schedules.py
{ "start": 55636, "end": 73793 }
class ____(_PipelineSchedule): """ Base class for multi-stage schedules. Implements the `step` method. Gradients are scaled by num_microbatches depending on the `scale_grads` argument, defaulting to True. This setting should match the configuration of your loss_fn, which may either average losses ...
PipelineScheduleMulti
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/file_manager.py
{ "start": 748, "end": 1507 }
class ____(ABC): """A reference to a file as manipulated by a FileManager. Subclasses may handle files that are resident on the local file system, in an object store, or in any arbitrary place where a file can be stored. This exists to handle the very common case where you wish to write a computation ...
FileHandle
python
django__django
tests/migrations/test_migrations_squashed_partially_applied/0001_initial.py
{ "start": 43, "end": 967 }
class ____(migrations.Migration): operations = [ migrations.CreateModel( name="MyModel1", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, ...
Migration
python
pypa__warehouse
warehouse/organizations/services.py
{ "start": 1230, "end": 28708 }
class ____: def __init__(self, db_session): self.db = db_session def get_organization(self, organization_id): """ Return the organization object that represents the given organizationid, or None if there is no organization for that ID. """ return self.db.get(Orga...
DatabaseOrganizationService
python
justquick__django-activity-stream
actstream/tests/test_drf.py
{ "start": 5166, "end": 6515 }
class ____(BaseDRFTestCase): def test_follow(self): body = { 'content_type_id': self.site_ct.id, 'object_id': self.comment.id } post = self.auth_client.post(reverse('follow-follow'), body) assert post.status_code == 201 follow = Follow.objects.order_by...
DRFFollowTestCase
python
crytic__slither
slither/detectors/shadowing/state.py
{ "start": 1052, "end": 2870 }
class ____(AbstractDetector): """ Shadowing of state variable """ ARGUMENT = "shadowing-state" HELP = "State variables shadowing" IMPACT = DetectorClassification.HIGH CONFIDENCE = DetectorClassification.HIGH WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#state-va...
StateShadowing
python
joke2k__faker
tests/providers/test_ssn.py
{ "start": 44781, "end": 45101 }
class ____(unittest.TestCase): num_sample_runs = 10 def setUp(self): self.fake = Faker("az_AZ") self.samples = [self.fake.ssn() for _ in range(self.num_sample_runs)] Faker.seed(0) def check_length(self): for sample in self.samples: assert len(sample) == 7
TestAzAz
python
PyCQA__pylint
tests/functional/a/attribute_defined_outside_init.py
{ "start": 661, "end": 774 }
class ____: def __init__(self): i = self._init i() def _init(self): self.z = 44
E
python
django__django
django/contrib/gis/db/backends/spatialite/models.py
{ "start": 1349, "end": 1930 }
class ____(models.Model, SpatialRefSysMixin): """ The 'spatial_ref_sys' table from SpatiaLite. """ srid = models.IntegerField(primary_key=True) auth_name = models.CharField(max_length=256) auth_srid = models.IntegerField() ref_sys_name = models.CharField(max_length=256) proj4text = mode...
SpatialiteSpatialRefSys
python
python-attrs__attrs
tests/test_make.py
{ "start": 42186, "end": 43174 }
class ____: """ Tests for `fields_dict`. """ @given(simple_classes()) def test_instance(self, C): """ Raises `TypeError` on non-classes. """ with pytest.raises(TypeError) as e: fields_dict(C()) assert "Passed object must be a class." == e.value.a...
TestFieldsDict
python
apache__airflow
providers/teradata/src/airflow/providers/teradata/operators/teradata_compute_cluster.py
{ "start": 1719, "end": 2319 }
class ____(Enum): SETUP = 1 STATE = 2 # Handler to handle single result set of a SQL query def _single_result_row_handler(cursor): records = cursor.fetchone() if isinstance(records, list): return records[0] if records is None: return records raise TypeError(f"Unexpected results...
_Operation
python
python-attrs__attrs
tests/test_converters.py
{ "start": 4365, "end": 5873 }
class ____: def test_missing_default(self): """ Raises TypeError if neither default nor factory have been passed. """ with pytest.raises(TypeError, match="Must pass either"): default_if_none() def test_too_many_defaults(self): """ Raises TypeError if ...
TestDefaultIfNone
python
xlwings__xlwings
xlwings/constants.py
{ "start": 45622, "end": 46153 }
class ____: xlDMYFormat = 4 # from enum XlColumnDataType xlDYMFormat = 7 # from enum XlColumnDataType xlEMDFormat = 10 # from enum XlColumnDataType xlGeneralFormat = 1 # from enum XlColumnDataType xlMDYFormat = 3 # from enum XlColumnDataType xlMYDFormat = 6 # from enum XlColumnDataType ...
ColumnDataType
python
huggingface__transformers
src/transformers/models/lxmert/modeling_lxmert.py
{ "start": 17671, "end": 18089 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) self.intermediate_act_fn = ACT2FN[config.hidden_act] def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hid...
LxmertIntermediate
python
redis__redis-py
tests/test_command_policies.py
{ "start": 3115, "end": 6711 }
class ____: def test_resolves_correctly_policies(self, r, monkeypatch): # original nodes selection method determine_nodes = r._determine_nodes determined_nodes = [] primary_nodes = r.get_primaries() calls = iter(list(range(len(primary_nodes)))) def wrapper(*args, req...
TestClusterWithPolicies
python
streamlit__streamlit
lib/tests/streamlit/elements/camera_input_test.py
{ "start": 4032, "end": 6985 }
class ____(DeltaGeneratorTestCase): def test_camera_input_with_width_pixels(self): """Test that camera_input can be displayed with a specific width in pixels.""" st.camera_input("Label", width=500) c = self.get_delta_from_queue().new_element assert ( c.width_config.WhichO...
CameraInputWidthTest
python
scikit-learn__scikit-learn
sklearn/externals/_arff.py
{ "start": 12564, "end": 12945 }
class ____(ArffException): '''Error raised when an attribute name is provided twice the attribute declaration.''' def __init__(self, value, value2): super().__init__() self.message = ( ('Bad @ATTRIBUTE name %s at line' % value) + ' %d, this name is already in use in ...
BadAttributeName
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/inheritance.py
{ "start": 541, "end": 622 }
class ____(list): # NoQA: FURB189 def meth(self): """docstring"""
MyList
python
mlflow__mlflow
mlflow/server/graphql/graphql_no_batching.py
{ "start": 343, "end": 2959 }
class ____(NamedTuple): root_fields: int max_aliases: int def scan_query(ast_node: DocumentNode) -> QueryInfo: """ Scan a GraphQL query and return its information. """ root_fields = 0 max_aliases = 0 total_selections = 0 for definition in ast_node.definitions: if selection...
QueryInfo
python
huggingface__transformers
tests/models/rwkv/test_modeling_rwkv.py
{ "start": 7592, "end": 14205 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (RwkvModel, RwkvForCausalLM) if is_torch_available() else () pipeline_model_mapping = ( {"feature-extraction": RwkvModel, "text-generation": RwkvForCausalLM} if is_torch_available() else {} ...
RwkvModelTest
python
huggingface__transformers
src/transformers/models/big_bird/modeling_big_bird.py
{ "start": 95732, "end": 99697 }
class ____(BigBirdPreTrainedModel, GenerationMixin): _tied_weights_keys = { "cls.predictions.decoder.bias": "cls.predictions.bias", "cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight", } def __init__(self, config): super().__init__(config) if not conf...
BigBirdForCausalLM
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/anno.py
{ "start": 2357, "end": 5919 }
class ____(NoValue): """Container for static analysis annotation keys. The enum values are used strictly for documentation purposes. """ # Symbols # These flags are boolean. IS_PARAM = 'Symbol is a parameter to the function being analyzed.' # Scopes # Scopes are represented by objects of type activit...
Static
python
pytorch__pytorch
torch/_functorch/_aot_autograd/autograd_cache.py
{ "start": 14335, "end": 20541 }
class ____(FxGraphCachePickler): def __init__(self, gm: torch.fx.GraphModule): super().__init__(gm) # pyrefly: ignore [bad-override] self.dispatch_table: dict self.dispatch_table.update( { AOTConfig: functools.partial(self._reduce_aot_config), ...
AOTAutogradCachePickler
python
pandas-dev__pandas
asv_bench/benchmarks/multiindex_object.py
{ "start": 5030, "end": 5382 }
class ____: params = ["int64", "Int64"] param_names = ["dtype"] def setup(self, dtype): a = array(np.tile(np.arange(100), 1000), dtype=dtype) b = array(np.tile(np.arange(1000), 100), dtype=dtype) self.mi = MultiIndex.from_arrays([a, b]) def time_sort_values(self, dtype): ...
SortValues
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_datacatalog.py
{ "start": 36883, "end": 38596 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook") def test_assert_valid_hook_call(self, mock_hook) -> None: mock_hook.return_value.update_tag_template.return_value.name = TEST_TAG_TEMPLATE_LINK.format( project_id=TEST_PROJECT_ID, ...
TestCloudDataCatalogUpdateTagTemplateOperator
python
walkccc__LeetCode
solutions/2416. Sum of Prefix Scores of Strings/2416.py
{ "start": 103, "end": 636 }
class ____: def sumPrefixScores(self, words: list[str]) -> list[int]: root = TrieNode() def insert(word: str) -> None: node: TrieNode = root for c in word: node = node.children.setdefault(c, TrieNode()) node.count += 1 for word in words: insert(word) def getScore(w...
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor33.py
{ "start": 325, "end": 498 }
class ____: def __new__(cls, *args: Any, **kwargs: Any) -> Self: ... def __init__(self, base: list[str], joined: str) -> None: ... A(temp := ["x"], " ".join(temp))
A
python
numba__numba
numba/core/typeinfer.py
{ "start": 34811, "end": 36307 }
class ____(dict): def set_context(self, context): self.context = context def __getitem__(self, name): if name not in self: self[name] = TypeVar(self.context, name) return super(TypeVarMap, self).__getitem__(name) def __setitem__(self, name, value): assert isinst...
TypeVarMap
python
astropy__astropy
astropy/utils/masked/tests/test_masked.py
{ "start": 20263, "end": 22817 }
class ____(MaskedArraySetup): def test_reshape(self): ma_reshape = self.ma.reshape((6,)) expected_data = self.a.reshape((6,)) expected_mask = self.mask_a.reshape((6,)) assert ma_reshape.shape == expected_data.shape assert_array_equal(ma_reshape.unmasked, expected_data) ...
TestMaskedArrayShaping
python
pandas-dev__pandas
pandas/tests/groupby/test_libgroupby.py
{ "start": 3377, "end": 3999 }
class ____(GroupVarTestMixin): __test__ = True algo = staticmethod(group_var) dtype = np.float64 rtol = 1e-5 def test_group_var_large_inputs(self): prng = np.random.default_rng(2) out = np.array([[np.nan]], dtype=self.dtype) counts = np.array([0], dtype="int64") va...
TestGroupVarFloat64
python
falconry__falcon
tests/test_httperror.py
{ "start": 4698, "end": 4855 }
class ____: def on_get(self, req, resp): raise falcon.HTTPMethodNotAllowed(['PUT'], headers={'x-ping': 'pong'})
MethodNotAllowedResourceWithHeaders