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
dabeaz-course__practical-python
Solutions/8_1/test_stock.py
{ "start": 47, "end": 714 }
class ____(unittest.TestCase): def test_create(self): s = stock.Stock('GOOG', 100, 490.1) self.assertEqual(s.name, 'GOOG') self.assertEqual(s.shares, 100) self.assertEqual(s.price, 490.1) def test_cost(self): s = stock.Stock('GOOG', 100, 490.1) self.assertEqual(s...
TestStock
python
ray-project__ray
python/ray/exceptions.py
{ "start": 22390, "end": 22892 }
class ____(ObjectLostError): """Indicates that an object fetch timed out. Args: object_ref_hex: Hex ID of the object. """ def __str__(self): return ( self._base_str() + "\n\n" + ( f"Fetch for object {self.object_ref_hex} timed out bec...
ObjectFetchTimedOutError
python
apache__airflow
airflow-core/tests/unit/utils/test_operator_helpers.py
{ "start": 940, "end": 4083 }
class ____: def setup_method(self): self.dag_id = "dag_id" self.task_id = "task_id" self.try_number = 1 self.logical_date = "2017-05-21T00:00:00" self.dag_run_id = "dag_run_id" self.owner = ["owner1", "owner2"] self.email = ["email1@test.com"] self.con...
TestOperatorHelpers
python
squidfunk__mkdocs-material
material/plugins/optimize/plugin.py
{ "start": 1931, "end": 14977 }
class ____(BasePlugin[OptimizeConfig]): supports_multiple_instances = True # Manifest manifest: dict[str, str] = {} # Initialize plugin def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Initialize incremental builds self.is_serve = False # Deter...
OptimizePlugin
python
pydantic__pydantic
pydantic/mypy.py
{ "start": 15625, "end": 50001 }
class ____: """Transform the BaseModel subclass according to the plugin settings. Attributes: tracked_config_fields: A set of field configs that the plugin has to track their value. """ tracked_config_fields: set[str] = { 'extra', 'frozen', 'from_attributes', 'p...
PydanticModelTransformer
python
allegroai__clearml
clearml/backend_api/services/v2_23/dataviews.py
{ "start": 47290, "end": 50413 }
class ____(Response): """ Response of dataviews.archive_many endpoint. :param succeeded: :type succeeded: Sequence[dict] :param failed: :type failed: Sequence[dict] """ _service = "dataviews" _action = "archive_many" _version = "2.23" _schema = { "definitions": {},...
ArchiveManyResponse
python
tiangolo__fastapi
fastapi/openapi/models.py
{ "start": 3561, "end": 8597 }
class ____(BaseModelWithConfig): # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu # Core Vocabulary schema_: Optional[str] = Field(default=None, alias="$schema") vocabulary: Optional[str] = Field(default=None, alias="$vocabulary") ...
Schema
python
pytorch__pytorch
test/inductor/test_block_analysis.py
{ "start": 579, "end": 4528 }
class ____(TestCase): @classmethod def setUpClass(cls): super().setUpClass() # Create a GraphLowering, so we can access V.graph. cls.graph = dummy_graph() @parametrize( "stride,symbol,expr", [ (5, x, Identity(5 * x)), (4, y, 4 * Identity(y)),...
BlockAnalysisTest
python
encode__django-rest-framework
tests/test_model_serializer.py
{ "start": 44621, "end": 44771 }
class ____(models.Model): target = models.OneToOneField(OneToOneTargetTestModel, primary_key=True, on_delete=models.CASCADE)
OneToOneSourceTestModel
python
mlflow__mlflow
dev/clint/src/clint/comments.py
{ "start": 309, "end": 1234 }
class ____: start: "Position" end: "Position" rules: set[str] @classmethod def from_token(cls, token: tokenize.TokenInfo) -> Self | None: # Import here to avoid circular dependency from clint.linter import Position if match := NOQA_REGEX.match(token.string): rul...
Noqa
python
wandb__wandb
wandb/vendor/pygments/lexers/rebol.py
{ "start": 10519, "end": 18617 }
class ____(RegexLexer): """ A `Red-language <http://www.red-lang.org/>`_ lexer. .. versionadded:: 2.0 """ name = 'Red' aliases = ['red', 'red/system'] filenames = ['*.red', '*.reds'] mimetypes = ['text/x-red', 'text/x-red-system'] flags = re.IGNORECASE | re.MULTILINE escape_re...
RedLexer
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 729392, "end": 729838 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("actor", "created_at", "discussion") actor = sgqlc.types.Field(Actor, graphql_name="actor") created_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graph...
ConvertedToDiscussionEvent
python
scipy__scipy
scipy/optimize/_trustregion_ncg.py
{ "start": 1431, "end": 4580 }
class ____(BaseQuadraticSubproblem): """Quadratic subproblem solved by a conjugate gradient method""" def solve(self, trust_radius): """ Solve the subproblem using a conjugate gradient method. Parameters ---------- trust_radius : float We are allowed to wande...
CGSteihaugSubproblem
python
realpython__materials
python-unittest/test_identity.py
{ "start": 18, "end": 366 }
class ____(unittest.TestCase): def test_list_aliases(self): a = ["Python", "unittest"] b = a self.assertIs(a, b) def test_list_objects(self): a = ["Python", "unittest"] b = ["Python", "unittest"] self.assertIsNot(a, b) if __name__ == "__main__": unittest.ma...
TestListIdentity
python
airbytehq__airbyte
airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py
{ "start": 565, "end": 1167 }
class ____: def get_generate_headers(self): headers = {"Accept": "application/json", "Content-Type": "application/json", **self._session.auth.get_auth_header()} return headers def generate_record( self, payload: Any, stream_slice: Optional[Mapping[str, Any]] = None, ...
GeneratorMixin
python
ApeWorX__ape
src/ape/exceptions.py
{ "start": 17479, "end": 17592 }
class ____(ApeException): """ Raised when a problem occurs from the configuration file. """
ConfigError
python
pypa__pipenv
pipenv/exceptions.py
{ "start": 1965, "end": 2666 }
class ____(ClickException): message = "[bold][red]ERROR[/red][/bold]: {}" def __init__(self, message=None, **kwargs): if not message: message = "Pipenv encountered a problem and had to exit." extra = kwargs.pop("extra", []) self.message = self.message.format(message) ...
PipenvException
python
PyCQA__pylint
tests/checkers/unittest_format.py
{ "start": 556, "end": 4819 }
class ____(CheckerTestCase): CHECKER_CLASS = FormatChecker def testCheckKeywordParensHandlesValidCases(self) -> None: cases = [ "if foo:", "if foo():", "if (x and y) or z:", "assert foo()", "assert ()", "if (1, 2) in (3, 4):", ...
TestSuperfluousParentheses
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/side_channel/float_properties_channel.py
{ "start": 139, "end": 2227 }
class ____(SideChannel): """ This is the SideChannel for float properties shared with Unity. You can modify the float properties of an environment with the commands set_property, get_property and list_properties. """ def __init__(self, channel_id: uuid.UUID = None) -> None: self._float_...
FloatPropertiesChannel
python
openai__openai-python
src/openai/types/beta/chatkit/chatkit_thread_item_list.py
{ "start": 1567, "end": 2322 }
class ____(BaseModel): id: str """Identifier of the thread item.""" created_at: int """Unix timestamp (in seconds) for when the item was created.""" heading: Optional[str] = None """Optional heading for the task. Defaults to null when not provided.""" object: Literal["chatkit.thread_item"...
DataChatKitTask
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_emulator.py
{ "start": 2587, "end": 3751 }
class ____(BaseChatModel): """Fake model for emulating tool responses.""" responses: list[str] = ["Emulated response"] response_index: int = 0 def _generate( self, messages: list[BaseMessage], stop: list[str] | None = None, run_manager: Any = None, **kwargs: Any...
FakeEmulatorModel
python
sympy__sympy
sympy/assumptions/predicates/sets.py
{ "start": 7608, "end": 8588 }
class ____(Predicate): """ Antihermitian predicate. Explanation =========== ``Q.antihermitian(x)`` is true iff ``x`` belongs to the field of antihermitian operators, i.e., operators in the form ``x*I``, where ``x`` is Hermitian. Examples ======== >>> from sympy import Q, ask,...
AntihermitianPredicate
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-toggl/llama_index/readers/toggl/dto.py
{ "start": 110, "end": 189 }
class ____(enum.Enum): json = "json" markdown = "markdown"
TogglOutFormat
python
joke2k__faker
faker/providers/date_time/zh_CN/__init__.py
{ "start": 46, "end": 714 }
class ____(DateTimeProvider): MONTH_NAMES = { "01": "一月", "02": "二月", "03": "三月", "04": "四月", "05": "五月", "06": "六月", "07": "七月", "08": "八月", "09": "九月", "10": "十月", "11": "十一月", "12": "十二月", } DAY_NAMES = { ...
Provider
python
getsentry__sentry
src/sentry/utils/circuit_breaker.py
{ "start": 588, "end": 2703 }
class ____(TypedDict, total=False): # The number of consecutive failures within a given window required to trigger the circuit breaker error_limit: int # The window of time in which those errors must happen error_limit_window: int # Allow a configurable subset of function calls to bypass the circuit...
CircuitBreakerConfig
python
ethereum__web3.py
web3/geth.py
{ "start": 3432, "end": 4215 }
class ____(Module): """ https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool """ is_async = True _content: Method[Callable[[], Awaitable[TxPoolContent]]] = Method( RPC.txpool_content, is_property=True, ) async def content(self) -> TxPoolContent: retur...
AsyncGethTxPool
python
great-expectations__great_expectations
tests/datasource/fluent/test_snowflake_datasource.py
{ "start": 44408, "end": 45150 }
class ____: """Test deprecation warnings for SnowflakeDatasource.""" def test_private_key_in_kwargs_connect_args_deprecated_warning(self): """Warn when private_key is in kwargs['connect_args'].""" with pytest.warns(DeprecationWarning, match="private_key.*deprecated"): SnowflakeDatas...
TestSnowflakeDatasourceDeprecationWarnings
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/classes8.py
{ "start": 397, "end": 1226 }
class ____( Iterator[DirEntry[AnyStr]], ContextManager["_ScandirIterator[AnyStr]"] ): def __iter__(self) -> Self: ... def __next__(self) -> DirEntry[AnyStr]: ... def close(self) -> None: ... def __enter__(self) -> Self: ... def __exit__( self, __exc_type: type[BaseException] ...
_ScandirIterator
python
python-excel__xlwt
xlwt/antlr.py
{ "start": 33621, "end": 35507 }
class ____: def __init__(self,string=None): if string: self.text = list(string) else: self.text = [] def setLength(self,sz): if not sz : self.text = [] return assert sz>0 if sz >= self.length(): return #...
StringBuffer
python
tensorflow__tensorflow
tensorflow/python/eager/wrap_function_test.py
{ "start": 13853, "end": 20932 }
class ____(test.TestCase): def testAddFunction(self): def fn(x): v = variables.Variable(3, name='v') v2 = variable_scope.get_variable( 'v', initializer=init_ops.Constant(4), shape=[], dtype=dtypes.int32) return v + v2 + x with self.cached_session() as sess: result = fn(con...
WrappedGraphTest
python
wandb__wandb
tests/system_tests/test_core/test_offline_sync_beta.py
{ "start": 583, "end": 11600 }
class ____: """A fake ServiceConnection for async testing.""" def __init__(self, mailbox: Mailbox) -> None: self._mailbox = mailbox self._cond = asyncio.Condition() self._init_sync_addrs: list[str] = [] self._sync_addrs: list[str] = [] self._sync_status_addrs: list[str]...
_Tester
python
dagster-io__dagster
python_modules/dagster-test/dagster_test/toys/external_execution/__init__.py
{ "start": 754, "end": 2291 }
class ____(Config): multiplier: int = Field(default=1) @asset def number_x( context: AssetExecutionContext, pipes_subprocess_client: PipesSubprocessClient, config: NumberConfig, ) -> None: extras = {**get_common_extras(context), "multiplier": config.multiplier} pipes_subprocess_client.run( ...
NumberConfig
python
pytorch__pytorch
test/distributed/test_inductor_collectives.py
{ "start": 2053, "end": 33418 }
class ____(DynamoDistributedMultiProcTestCase): """ Run correctness checks in multi-proc runner, mark with minimum # GPUs to run under """ device = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu" def get_world_trs(self): return { "tag": "", "...
TestCollectivesMultiProc
python
instagram__MonkeyType
monkeytype/db/base.py
{ "start": 576, "end": 1926 }
class ____(metaclass=ABCMeta): """An interface that all concrete calltrace storage backends must implement.""" @abstractmethod def add(self, traces: Iterable[CallTrace]) -> None: """Store the supplied call traces in the backing store""" pass @abstractmethod def filter( self...
CallTraceStore
python
huggingface__transformers
src/transformers/models/florence2/modular_florence2.py
{ "start": 64839, "end": 65129 }
class ____(LlavaPreTrainedModel): config_class = Florence2Config base_model_prefix = "model" _supports_attention_backend = False @auto_docstring( custom_intro=""" Florence-2 is a vision model for captioning, detection, and segmentation. """ )
Florence2PreTrainedModel
python
pyinstaller__pyinstaller
PyInstaller/utils/win32/icon.py
{ "start": 2534, "end": 2714 }
class ____(Structure): _names_ = ("bWidth", "bHeight", "bColorCount", "bReserved", "wPlanes", "wBitCount", "dwBytesInRes", "dwImageOffset") _format_ = "bbbbhhii"
ICONDIRENTRY
python
ray-project__ray
python/ray/tune/tests/test_integration_pytorch_lightning.py
{ "start": 331, "end": 548 }
class ____(Dataset): def __init__(self, values): self.values = values def __getitem__(self, index): return self.values[index] def __len__(self): return len(self.values)
_MockDataset
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-sec-filings/llama_index/readers/sec_filings/prepline_sec_filings/api/app.py
{ "start": 924, "end": 1337 }
class ____(logging.Filter): def filter(self, record: logging.LogRecord) -> bool: return record.getMessage().find("/healthcheck") == -1 logging.getLogger("uvicorn.access").addFilter(HealthCheckFilter()) @app.get("/healthcheck", status_code=status.HTTP_200_OK, include_in_schema=False) def healthcheck(requ...
HealthCheckFilter
python
tensorflow__tensorflow
tensorflow/compiler/mlir/quantization/tensorflow/python/integration_test/quantize_model_test.py
{ "start": 17953, "end": 155054 }
class ____(quantize_model_test_base.QuantizedModelTest): @parameterized.parameters( testing.parameter_combinations([{ 'shapes': [ ([3, 3], [3, 3]), ([3, None], [None, 3]), ([None, None], [None, None]), ([4, 3, 3], [4, 3, 3]), ([4, ...
StaticRangeQuantizationTest
python
PrefectHQ__prefect
src/prefect/server/utilities/database.py
{ "start": 25039, "end": 26090 }
class ____(functions.ReturnTypeFromArgs[T]): inherit_cache: bool = True @compiles(greatest, "sqlite") def sqlite_greatest_as_max( element: greatest[Any], compiler: SQLCompiler, **kwargs: Any ) -> str: # TODO: SQLite MAX() is very close to PostgreSQL GREATEST(), *except* when # it comes to nulls: SQLit...
greatest
python
sympy__sympy
sympy/polys/series/ringpython.py
{ "start": 29804, "end": 39380 }
class ____: """ Python implementation of power series ring over integers :ref:`ZZ`. This class provides comprehensive power series operations over the integer ring, supporting both series manipulations with precision handling and truncation. Parameters ========== prec : int, optional ...
PythonPowerSeriesRingZZ
python
donnemartin__system-design-primer
solutions/system_design/social_graph/social_graph_snippets.py
{ "start": 133, "end": 729 }
class ____(object): def bfs(self, source, dest): if source is None: return False queue = deque() queue.append(source) source.visit_state = State.visited while queue: node = queue.popleft() print(node) if dest is node: ...
Graph
python
openai__openai-python
src/openai/types/audio/transcription_text_done_event.py
{ "start": 834, "end": 1323 }
class ____(BaseModel): input_tokens: int """Number of input tokens billed for this request.""" output_tokens: int """Number of output tokens generated.""" total_tokens: int """Total number of tokens used (input + output).""" type: Literal["tokens"] """The type of the usage object. Alw...
Usage
python
getsentry__sentry
tests/sentry/integrations/cursor/test_client.py
{ "start": 276, "end": 5385 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.api_key = "test_api_key" self.webhook_secret = "test_webhook_secret" self.cursor_client = CursorAgentClient( api_key=self.api_key, webhook_secret=self.webhook_secret ) self.webhook_url = "...
CursorAgentClientTest
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 23969, "end": 24325 }
class ____(Dataset): def __init__(self, size, sleep_sec): self.size = size self.sleep_sec = sleep_sec self.slept = False def __getitem__(self, idx): if not self.slept: time.sleep(self.sleep_sec) self.slept = True return idx def __len__(self):...
SleepDataset
python
getsentry__sentry
src/sentry/preprod/pull_request/types.py
{ "start": 2218, "end": 2389 }
class ____(BaseModel): """ Error response for pull request operations. """ error: str message: str details: str | None = None
PullRequestErrorResponse
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 1014488, "end": 1015115 }
class ____( sgqlc.types.Type, Node, Comment, Deletable, Reactable, UniformResourceLocatable, Updatable, UpdatableComment, ): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("body_version", "discussion", "number") body_version...
TeamDiscussionComment
python
ray-project__ray
python/ray/tests/test_batch_node_provider_integration.py
{ "start": 742, "end": 3738 }
class ____(BatchingNodeProvider): """Class for e2e local testing of BatchingNodeProvider. Uses FakeMultiNodeProvider as a proxy for managing the nodes. This node provider requires the "available_node_types" section of the autoscaling config to be copied into the "provider" section. That's needed so...
FakeBatchingNodeProvider
python
facebook__pyre-check
client/language_server/daemon_connection.py
{ "start": 1053, "end": 1665 }
class ____(json_mixins.CamlCaseAndExcludeJsonMixin): error_message: str error_source: Optional[Exception] = None def send_raw_request(socket_path: Path, raw_request: str) -> str: with connections.connect(socket_path) as ( input_channel, output_channel, ): LOG.debug(f"Sending `{...
DaemonConnectionFailure
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/app_identity/incoming/main.py
{ "start": 819, "end": 1270 }
class ____(webapp2.RequestHandler): allowed_app_ids = ["other-app-id", "other-app-id-2"] def get(self): incoming_app_id = self.request.headers.get("X-Appengine-Inbound-Appid", None) if incoming_app_id not in self.allowed_app_ids: self.abort(403) self.response.write("This i...
MainPage
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 36220, "end": 36319 }
class ____(Operator): __slots__ = () _description = "less-or-equal" _op = operator.le
LtE
python
google__python-fire
fire/fire_import_test.py
{ "start": 695, "end": 1107 }
class ____(testutils.BaseTestCase): """Tests importing Fire.""" def testFire(self): with mock.patch.object(sys, 'argv', ['commandname']): fire.Fire() def testFireMethods(self): self.assertIsNotNone(fire.Fire) def testNoPrivateMethods(self): self.assertTrue(hasattr(fire, 'Fire')) self.as...
FireImportTest
python
django__django
tests/model_fields/models.py
{ "start": 3330, "end": 3416 }
class ____(models.Model): value = models.BigAutoField(primary_key=True)
BigAutoModel
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/if_stmt_min_max.py
{ "start": 1561, "end": 1706 }
class ____: def __init__(self): self.value = 13 A1 = A() if A1.value < 10: A1.value = 10 if A1.value > 10: A1.value = 10
A
python
viewflow__viewflow
viewflow/forms/renderers.py
{ "start": 14873, "end": 15418 }
class ____(InputRenderer): tag = "vf-field-autocomplete-multi" def create_root(self, context): root = super().create_root(context) field = self.bound_field.field initial_values = [ { 'value': field.label_from_instance(item), 'data': {'id': fi...
AjaxMultipleModelSelectRenderer
python
pypa__warehouse
tests/unit/admin/views/test_users.py
{ "start": 14298, "end": 17420 }
class ____: def test_deletes_user(self, db_request, monkeypatch): user = UserFactory.create() project = ProjectFactory.create() another_project = ProjectFactory.create() RoleFactory(project=project, user=user, role_name="Owner") deleted_user = UserFactory.create(username="del...
TestUserDelete
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/schedules/ticks.py
{ "start": 1334, "end": 1568 }
class ____(graphene.Union): class Meta: types = ( GrapheneScheduleTickSuccessData, GrapheneScheduleTickFailureData, ) name = "ScheduleTickSpecificData"
GrapheneScheduleTickSpecificData
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_resolver.py
{ "start": 25207, "end": 26357 }
class ____: def setUp(self): self.owner = create_user(username="owner", password="test") self.tester = create_user(username="tester", password="test") self.pip = fixture.get( Project, slug="pip", users=[self.owner], main_language_project=None, ...
ResolverAltSetUp
python
PyCQA__pylint
tests/functional/i/invalid/invalid_repr_returned.py
{ "start": 1126, "end": 1252 }
class ____: """Potential uninferable return value""" def __repr__(self): return str(Missing)
AnotherAmbiguousRepr
python
pypa__pip
tests/lib/wheel.py
{ "start": 6027, "end": 11825 }
class ____: """A wheel that can be saved or converted to several formats.""" def __init__(self, name: str, files: Iterable[File]) -> None: self._name = name self._files = files def save_to_dir(self, path: Path | str) -> str: """Generate wheel file with correct name and save into th...
WheelBuilder
python
doocs__leetcode
solution/0500-0599/0536.Construct Binary Tree from String/Solution.py
{ "start": 192, "end": 951 }
class ____: def str2tree(self, s: str) -> TreeNode: def dfs(s): if not s: return None p = s.find('(') if p == -1: return TreeNode(int(s)) root = TreeNode(int(s[:p])) start = p cnt = 0 for i in...
Solution
python
huggingface__transformers
src/transformers/models/prompt_depth_anything/modular_prompt_depth_anything.py
{ "start": 2555, "end": 3897 }
class ____(DepthAnythingFeatureFusionLayer): def __init__(self, config: PromptDepthAnythingConfig): super().__init__(config) self.prompt_depth_layer = PromptDepthAnythingLayer(config) def forward(self, hidden_state, residual=None, size=None, prompt_depth=None): if residual is not None: ...
PromptDepthAnythingFeatureFusionLayer
python
fluentpython__example-code
attic/concurrency/wikipedia/daypicts.py
{ "start": 1260, "end": 1350 }
class ____(Exception): '''No Picture of the Day found for {iso_date}'''
NoPictureForDate
python
getsentry__sentry-python
sentry_sdk/integrations/cohere.py
{ "start": 1976, "end": 9401 }
class ____(Integration): identifier = "cohere" origin = f"auto.ai.{identifier}" def __init__(self, include_prompts=True): # type: (CohereIntegration, bool) -> None self.include_prompts = include_prompts @staticmethod def setup_once(): # type: () -> None BaseCohere.c...
CohereIntegration
python
getsentry__sentry
src/sentry/api/endpoints/catchall.py
{ "start": 245, "end": 1308 }
class ____(Endpoint): permission_classes = () @csrf_exempt @allow_cors_options def dispatch(self, request: Request, *args, **kwargs) -> HttpResponse: """ This endpoint handles routes that did not match """ # Let the user know they may have forgotten a trailing slash ...
CatchallEndpoint
python
networkx__networkx
networkx/drawing/nx_pylab.py
{ "start": 54621, "end": 103405 }
class ____: """Draw arrows with `matplotlib.patches.FancyarrowPatch`""" class ConnectionStyleFactory: def __init__(self, connectionstyles, selfloop_height, ax=None): import matplotlib as mpl import matplotlib.path # call as mpl.path import numpy as np s...
FancyArrowFactory
python
huggingface__transformers
tests/models/paligemma/test_modeling_paligemma.py
{ "start": 13136, "end": 25656 }
class ____(unittest.TestCase): def setUp(self): self.processor = PaliGemmaProcessor.from_pretrained("google/paligemma-3b-pt-224") def tearDown(self): cleanup(torch_device, gc_collect=True) def test_small_model_integration_test(self): # Let' s make sure we test the preprocessing to ...
PaliGemmaForConditionalGenerationIntegrationTest
python
vyperlang__vyper
vyper/venom/context.py
{ "start": 569, "end": 849 }
class ____: label: IRLabel data_items: list[DataItem] = field(default_factory=list) def __str__(self): ret = [f"dbsection {self.label.value}:"] for item in self.data_items: ret.append(f" db {item}") return "\n".join(ret)
DataSection
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_M.py
{ "start": 11773, "end": 13040 }
class ____(Benchmark): r""" Mishra 6 objective function. This class defines the Mishra 6 [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Mishra06}}(x) = -\log{\left [ \sin^2 ((\cos(x_1) + \cos(x_2))^2) - \cos^2 ((\s...
Mishra06
python
gevent__gevent
src/gevent/tests/lock_tests.py
{ "start": 1507, "end": 1743 }
class ____(TimeAssertMixin, unittest.TestCase): def setUp(self): self._threads = support.threading_setup() def tearDown(self): support.threading_cleanup(*self._threads) support.reap_children()
BaseTestCase
python
kamyu104__LeetCode-Solutions
Python/maximum-calories-burnt-from-jumps.py
{ "start": 48, "end": 601 }
class ____(object): def maxCaloriesBurnt(self, heights): """ :type heights: List[int] :rtype: int """ heights.sort() left, right = 0, len(heights)-1 result = (0-heights[right])**2 while left != right: result += (heights[right]-heights[left]...
Solution
python
ray-project__ray
python/ray/data/tests/test_map.py
{ "start": 28356, "end": 33840 }
class ____: def __init__(self): self.data = large_object def __call__(self, batch): return batch ds = ray.data.range(1) ds = ds.map_batches(LargeUDF, concurrency=1) assert ds.take_all() == [{"id": 0}] """ output = run_string_as_driver(driver) assert "The UDF of operator MapBatches(...
LargeUDF
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/test_validators.py
{ "start": 6166, "end": 10947 }
class ____(BaseValidatorTest): def setUp(self) -> None: super().setUp() self.project = self.create_project() self.context = { "organization": self.project.organization, "project": self.project, "request": self.make_request(user=self.user), } ...
DetectorValidatorTest
python
getsentry__sentry
tests/sentry/incidents/test_logic.py
{ "start": 90099, "end": 91421 }
class ____(TestCase, BaseIncidentsTest): def setUp(self) -> None: self.alert_rule = self.create_alert_rule() def test_enable(self) -> None: with self.tasks(): disable_alert_rule(self.alert_rule) alert_rule = AlertRule.objects.get(id=self.alert_rule.id) assert...
EnableDisableAlertRuleTest
python
etianen__django-reversion
reversion/management/commands/__init__.py
{ "start": 209, "end": 2046 }
class ____(BaseCommand): def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "app_label", metavar="app_label", nargs="*", help="Optional app_label or app_label.model_name list.", ) parser.add_argument( ...
BaseRevisionCommand
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/data.py
{ "start": 13567, "end": 14377 }
class ____(SpanProperty): def __init__(self, spans: "Spans") -> None: super().__init__(spans) self.groups: dict[int, set[tuple[int, int]]] = defaultdict(set) def start_span(self, i: int, label_index: int) -> None: # TODO should we discard start == end cases? occurs for eg st.data() ...
_mutator_groups
python
huggingface__transformers
src/transformers/models/cohere/modeling_cohere.py
{ "start": 2347, "end": 3155 }
class ____(nn.Module): def __init__(self, hidden_size=None, eps=1e-5, bias=False): """The hidden size can be a tuple or an int. The tuple is used for QKNorm to normalize across head_dim""" super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = ...
CohereLayerNorm
python
pandas-dev__pandas
pandas/tests/indexes/test_setops.py
{ "start": 6154, "end": 23057 }
class ____: # Set operation tests shared by all indexes in the `index` fixture @pytest.mark.parametrize("case", [0.5, "xxx"]) @pytest.mark.parametrize( "method", ["intersection", "union", "difference", "symmetric_difference"] ) def test_set_ops_error_cases(self, case, method, index): ...
TestSetOps
python
huggingface__transformers
tests/quantization/bnb/test_4bit.py
{ "start": 25525, "end": 25766 }
class ____(Bnb4BitTest): model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" EXPECTED_RELATIVE_DIFFERENCE = 2.9461410686392764 @require_bitsandbytes @require_accelerate @require_torch @slow @apply_skip_if_not_implemented
Bnb4BitLlamaTest
python
fastai__fastai
fastai/torch_core.py
{ "start": 4954, "end": 5221 }
class ____(ArrayBase): "Base class for arrays representing images" _show_args = {'cmap':'viridis'} def show(self, ctx=None, **kwargs): return show_image(self, ctx=ctx, **{**self._show_args, **kwargs}) # %% ../nbs/00_torch_core.ipynb 29
ArrayImageBase
python
cython__cython
Cython/Tests/xmlrunner.py
{ "start": 1677, "end": 2937 }
class ____: """This class is used to keep useful information about the execution of a test method. """ # Possible test outcomes (SUCCESS, FAILURE, ERROR) = range(3) def __init__(self, test_result, test_method, outcome=SUCCESS, err=None): "Create a new instance of _TestInfo." se...
_TestInfo
python
django-import-export__django-import-export
tests/core/tests/test_resources/test_modelresource/test_fields.py
{ "start": 205, "end": 1879 }
class ____(TestCase): def setUp(self): self.resource = BookResource() self.book = Book.objects.create(name="Some book") self.dataset = tablib.Dataset(headers=["id", "name", "author_email", "price"]) row = [self.book.pk, "Some book", "test@example.com", "10.25"] self.dataset.a...
FieldHandlingTest
python
dask__distributed
distributed/worker_state_machine.py
{ "start": 19207, "end": 19469 }
class ____(StateMachineEvent): """:class:`GatherDep` instruction terminated (abstract base class)""" __slots__ = ("worker", "total_nbytes") worker: str total_nbytes: int # Must be the same as in GatherDep instruction @dataclass
GatherDepDoneEvent
python
automl__auto-sklearn
autosklearn/pipeline/components/regression/random_forest.py
{ "start": 582, "end": 6151 }
class ____( IterativeComponent, AutoSklearnRegressionAlgorithm, ): def __init__( self, criterion, max_features, max_depth, min_samples_split, min_samples_leaf, min_weight_fraction_leaf, bootstrap, max_leaf_nodes, min_impurity_de...
RandomForest
python
huggingface__transformers
src/transformers/trainer_callback.py
{ "start": 26124, "end": 29250 }
class ____(TrainerCallback): """ A [`TrainerCallback`] that displays the progress of training or evaluation. You can modify `max_str_len` to control how long strings are truncated when logging. """ def __init__(self, max_str_len: int = 100): """ Initialize the callback with optional...
ProgressCallback
python
numba__numba
numba/cuda/tests/cudadrv/test_cuda_ndarray.py
{ "start": 205, "end": 17652 }
class ____(CUDATestCase): def test_device_array_interface(self): dary = cuda.device_array(shape=100) devicearray.verify_cuda_ndarray_interface(dary) ary = np.empty(100) dary = cuda.to_device(ary) devicearray.verify_cuda_ndarray_interface(dary) ary = np.asarray(1.234...
TestCudaNDArray
python
walkccc__LeetCode
solutions/1910. Remove All Occurrences of a Substring/1910.py
{ "start": 0, "end": 298 }
class ____: def removeOccurrences(self, s: str, part: str) -> str: n = len(s) k = len(part) t = [' '] * n j = 0 # t's index for i, c in enumerate(s): t[j] = c j += 1 if j >= k and ''.join(t[j - k:j]) == part: j -= k return ''.join(t[:j])
Solution
python
scipy__scipy
scipy/integrate/_ivp/rk.py
{ "start": 10386, "end": 15417 }
class ____(RungeKutta): """Explicit Runge-Kutta method of order 5(4). This uses the Dormand-Prince pair of formulas [1]_. The error is controlled assuming accuracy of the fourth-order method accuracy, but steps are taken using the fifth-order accurate formula (local extrapolation is done). A quarti...
RK45
python
realpython__materials
python-sqlite-sqlalchemy/project/examples/example_3/app/albums/routes.py
{ "start": 707, "end": 2050 }
class ____(FlaskForm): artist = HiddenField("artist") title = StringField( label="Albums's Name", validators=[InputRequired(), does_album_exist] ) @albums_bp.route("/albums", methods=["GET", "POST"]) @albums_bp.route("/albums/<int:artist_id>", methods=["GET", "POST"]) def albums(artist_id=None): ...
CreateAlbumForm
python
yaml__pyyaml
tests/legacy_tests/test_recursive.py
{ "start": 14, "end": 357 }
class ____: def __init__(self, foo, bar): self.foo = foo self.bar = bar def __repr__(self): try: return "%s(foo=%r, bar=%r)" % (self.__class__.__name__, self.foo, self.bar) except RuntimeError: return "%s(foo=..., bar=...)" % self.__c...
AnInstance
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_ddl.py
{ "start": 6998, "end": 13010 }
class ____(fixtures.TestBase): """test the creation of a variety of DDL structures and ensure label length limits pass on backends """ __sparse_driver_backend__ = True def fk(self, metadata, connection): convention = { "fk": "foreign_key_%(table_name)s_" "%(column_...
LongNameBlowoutTest
python
pallets__click
src/click/_winconsole.py
{ "start": 3455, "end": 3671 }
class ____(io.RawIOBase): def __init__(self, handle: int | None) -> None: self.handle = handle def isatty(self) -> t.Literal[True]: super().isatty() return True
_WindowsConsoleRawIOBase
python
dask__dask
dask/array/_array_expr/_io.py
{ "start": 434, "end": 1373 }
class ____(IO): _parameters = ["layer", "_meta", "chunks", "keys", "name_prefix"] @functools.cached_property def _meta(self): return self.operand("_meta") @functools.cached_property def chunks(self): return self.operand("chunks") @functools.cached_property def _name(self):...
FromGraph
python
zarr-developers__zarr-python
tests/test_codecs/test_codecs.py
{ "start": 889, "end": 1112 }
class ____: array: AnyAsyncArray def __getitem__(self, selection: BasicSelection) -> _AsyncArraySelectionProxy: return _AsyncArraySelectionProxy(self.array, selection) @dataclass(frozen=True)
_AsyncArrayProxy
python
doocs__leetcode
solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution.py
{ "start": 0, "end": 130 }
class ____: def maxProfit(self, prices: List[int]) -> int: return sum(max(0, b - a) for a, b in pairwise(prices))
Solution
python
pypa__warehouse
tests/unit/captcha/test_recaptcha.py
{ "start": 7746, "end": 8833 }
class ____: def test_csp_policy(self): scheme = "https" request = pretend.stub( scheme=scheme, registry=pretend.stub( settings={ "recaptcha.site_key": "foo", "recaptcha.secret_key": "bar", } )...
TestCSPPolicy
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess3.py
{ "start": 192, "end": 263 }
class ____: pi = 3.1415 def __init__(self): self.x = 1
A
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/metrics_test.py
{ "start": 175587, "end": 177604 }
class ____(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() @test_util.run_deprecated_v1 def testVars(self): metrics.true_negatives_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0.15, 0.5, 0.85]) ...
TrueNegativesAtThresholdsTest
python
lazyprogrammer__machine_learning_examples
cnn_class2/tf_resnet_convblock.py
{ "start": 2310, "end": 6240 }
class ____: def __init__(self, mi, fm_sizes, stride=2, activation=tf.nn.relu): # conv1, conv2, conv3 # note: # feature maps shortcut = # feauture maps conv 3 assert(len(fm_sizes) == 3) # note: kernel size in 2nd conv is always 3 # so we won't bother including it as an arg # note: strid...
ConvBlock
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F821_0.py
{ "start": 1463, "end": 2320 }
class ____: field: Annotated[ int, "base64", arbitrary_callable(), 123, (1, 2, 3), ] field_with_stringified_type: Annotated[ "PEP593Test", 123, ] field_with_undefined_stringified_type: Annotated[ "PEP593Test123", 123, ] ...
PEP593Test