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
pytest-dev__pytest-django
tests/test_db_setup.py
{ "start": 10704, "end": 12718 }
class ____: db_settings: ClassVar = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": "db_name", "TEST": {"NAME": "test_custom_db_name"}, } } def test_db_with_tox_suffix( self, django_pytester: DjangoPytester, monkeypa...
TestSqliteWithTox
python
doocs__leetcode
solution/3300-3399/3317.Find the Number of Possible Ways for an Event/Solution.py
{ "start": 0, "end": 472 }
class ____: def numberOfWays(self, n: int, x: int, y: int) -> int: mod = 10**9 + 7 f = [[0] * (x + 1) for _ in range(n + 1)] f[0][0] = 1 for i in range(1, n + 1): for j in range(1, x + 1): f[i][j] = (f[i - 1][j] * j + f[i - 1][j - 1] * (x - (j - 1))) % mod...
Solution
python
python__mypy
mypyc/analysis/dataflow.py
{ "start": 13847, "end": 19519 }
class ____(BaseAnalysisVisitor[Value]): def visit_branch(self, op: Branch) -> GenAndKill[Value]: return non_trivial_sources(op), set() def visit_return(self, op: Return) -> GenAndKill[Value]: if not isinstance(op.value, (Integer, Float)): return {op.value}, set() else: ...
LivenessVisitor
python
ansible__ansible
lib/ansible/errors/__init__.py
{ "start": 5923, "end": 6027 }
class ____(AnsibleError): """The requested config entry is not defined."""
AnsibleUndefinedConfigEntry
python
jazzband__tablib
src/tablib/formats/_df.py
{ "start": 118, "end": 1112 }
class ____: title = 'df' extensions = ('df',) @classmethod def detect(cls, stream): """Returns True if given stream is a DataFrame.""" if DataFrame is None: return False elif isinstance(stream, DataFrame): return True try: DataFrame(st...
DataFrameFormat
python
getsentry__sentry
tests/sentry/sentry_metrics/consumers/test_last_seen_updater.py
{ "start": 2221, "end": 5060 }
class ____(TestCase): @staticmethod def processing_factory(): return LastSeenUpdaterStrategyFactory( ingest_profile="release-health", indexer_db="postgres", max_batch_time=1.0, max_batch_size=1, ) def setUp(self) -> None: self.org_id =...
TestLastSeenUpdaterEndToEnd
python
tensorflow__tensorflow
tensorflow/python/framework/errors_impl.py
{ "start": 8574, "end": 9389 }
class ____(OpError): """Raised when an operation is cancelled. For example, a long-running operation e.g.`tf.queue.QueueBase.enqueue`, or a `tf.function` call may be cancelled by either running another operation e.g. `tf.queue.QueueBase.close` or a remote worker failure. This long-running operation will fai...
CancelledError
python
huggingface__transformers
src/transformers/models/perception_lm/modular_perception_lm.py
{ "start": 4259, "end": 5768 }
class ____(LlavaCausalLMOutputWithPast): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction s...
PerceptionLMCausalLMOutputWithPast
python
kennethreitz__tablib
src/tablib/packages/dbfpy/fields.py
{ "start": 8761, "end": 9182 }
class ____(DbfFieldDef): """Definition of the integer field.""" typeCode = "I" length = 4 defaultValue = 0 def decodeValue(self, value): """Return an integer number decoded from ``value``.""" return struct.unpack("<i", value)[0] def encodeValue(self, value): """Return ...
DbfIntegerFieldDef
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/events.py
{ "start": 4722, "end": 5245 }
class ____(NodeEvent): __slots__ = 'tag', 'implicit', 'value', 'style' def __init__( self, anchor, tag, implicit, value, start_mark=None, end_mark=None, style=None, comment=None, ): # type: (Any, Any, Any, Any, Any, Any, Any, A...
ScalarEvent
python
Netflix__metaflow
metaflow/exception.py
{ "start": 3211, "end": 3291 }
class ____(MetaflowException): headline = "Tagging error"
MetaflowTaggingError
python
getsentry__sentry
src/sentry/sentry_metrics/querying/data/execution.py
{ "start": 20412, "end": 30456 }
class ____: """ Represents an executor that is responsible for scheduling execution of the supplied ScheduledQuery(s). """ def __init__(self, organization: Organization, projects: Sequence[Project], referrer: str): self._organization = organization self._projects = projects self...
QueryExecutor
python
doocs__leetcode
solution/0100-0199/0159.Longest Substring with At Most Two Distinct Characters/Solution.py
{ "start": 0, "end": 396 }
class ____: def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: cnt = Counter() ans = j = 0 for i, c in enumerate(s): cnt[c] += 1 while len(cnt) > 2: cnt[s[j]] -= 1 if cnt[s[j]] == 0: cnt.pop(s[j]) ...
Solution
python
huggingface__transformers
src/transformers/models/dinov2/modeling_dinov2.py
{ "start": 16741, "end": 18181 }
class ____(PreTrainedModel): config: Dinov2Config base_model_prefix = "dinov2" main_input_name = "pixel_values" input_modalities = ("image",) supports_gradient_checkpointing = True _no_split_modules = ["Dinov2Layer"] _supports_sdpa = True _supports_flash_attn = True _supports_flex_at...
Dinov2PreTrainedModel
python
huggingface__transformers
src/transformers/models/qwen2/modular_qwen2.py
{ "start": 9244, "end": 9525 }
class ____(LlamaForQuestionAnswering): pass __all__ = [ "Qwen2PreTrainedModel", "Qwen2Model", "Qwen2ForCausalLM", "Qwen2RMSNorm", "Qwen2ForSequenceClassification", "Qwen2ForTokenClassification", "Qwen2ForQuestionAnswering", ]
Qwen2ForQuestionAnswering
python
mlflow__mlflow
mlflow/models/evaluation/validation.py
{ "start": 5735, "end": 5992 }
class ____(MlflowException): def __init__(self, _message, **kwargs): message = "Could not instantiate MetricThreshold class: " + _message super().__init__(message, error_code=INVALID_PARAMETER_VALUE, **kwargs)
MetricThresholdClassException
python
scipy__scipy
scipy/io/_mmio.py
{ "start": 6555, "end": 32076 }
class ____: __slots__ = ('_rows', '_cols', '_entries', '_format', '_field', '_symmetry') @property def rows(self): return self._rows @property def cols(self): return self._cols @property d...
MMFile
python
ipython__ipython
IPython/lib/pretty.py
{ "start": 10434, "end": 14965 }
class ____(PrettyPrinter): """ Special pretty printer that has a `pretty` method that calls the pretty printer for a python object. This class stores processing data on `self` so you must *never* use this class in a threaded environment. Always lock it or reinstanciate it. Instances also ...
RepresentationPrinter
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/eks.py
{ "start": 6221, "end": 8574 }
class ____(EksBaseSensor): """ Check the state of an AWS Fargate profile until it reaches the target state or another terminal state. .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/sensor:EksFargateProfileStateSensor` :param cluster_n...
EksFargateProfileStateSensor
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 18877, "end": 19908 }
class ____: def setup_method(self): self.rng = np.random.default_rng(7836792223) def test_rvs(self): vals = stats.bernoulli.rvs(0.75, size=(2, 50), random_state=self.rng) assert_(np.all(vals >= 0) & np.all(vals <= 1)) assert_(np.shape(vals) == (2, 50)) assert_(vals.dtype...
TestBernoulli
python
django__django
django/core/mail/backends/smtp.py
{ "start": 398, "end": 7366 }
class ____(BaseEmailBackend): """ A wrapper that manages the SMTP network connection. """ def __init__( self, host=None, port=None, username=None, password=None, use_tls=None, fail_silently=False, use_ssl=None, timeout=None, ...
EmailBackend
python
has2k1__plotnine
plotnine/scales/scale_color.py
{ "start": 13237, "end": 13900 }
class ____(scale_datetime, scale_color_cmap): # pyright: ignore[reportIncompatibleVariableOverride] """ Datetime color scale See Also -------- plotnine.scale_color_cmap : The parent class. """ _: KW_ONLY guide: Literal["legend", "colorbar"] | None = "colorbar" def __post_init__( ...
scale_color_datetime
python
jazzband__django-model-utils
model_utils/models.py
{ "start": 5915, "end": 6215 }
class ____(models.Model): """ This abstract base class provides id field on any model that inherits from it which will be the primary key. """ id = UUIDField( primary_key=True, version=4, editable=False, ) class Meta: abstract = True
UUIDModel
python
Lightning-AI__lightning
tests/tests_pytorch/loggers/test_all.py
{ "start": 7388, "end": 7844 }
class ____(Callback): def setup(self, trainer, pl_module, stage=None): if trainer.global_rank > 0: return if isinstance(trainer.logger, MLFlowLogger): assert trainer.logger._mlflow_client elif isinstance(trainer.logger, NeptuneLogger): assert trainer.logge...
LazyInitExperimentCheck
python
django__django
tests/queries/tests.py
{ "start": 90331, "end": 91738 }
class ____(unittest.TestCase): """ Tests for the Queryset.ordered attribute. """ def test_no_default_or_explicit_ordering(self): self.assertIs(Annotation.objects.all().ordered, False) def test_cleared_default_ordering(self): self.assertIs(Tag.objects.all().ordered, True) se...
QuerysetOrderedTests
python
PyCQA__pylint
pylint/checkers/bad_chained_comparison.py
{ "start": 611, "end": 2238 }
class ____(BaseChecker): """Checks for unintentional usage of chained comparison.""" name = "bad-chained-comparison" msgs = { "W3601": ( "Suspicious %s-part chained comparison using semantically incompatible operators (%s)", "bad-chained-comparison", "Used when t...
BadChainedComparisonChecker
python
django__django
tests/admin_changelist/models.py
{ "start": 521, "end": 818 }
class ____(models.Model): parent = models.ForeignKey(Child, models.SET_NULL, editable=False, null=True) name = models.CharField(max_length=30, blank=True) def __str__(self): return self.name def __html__(self): return f'<h2 class="main">{self.name}</h2>'
GrandChild
python
realpython__materials
duck-typing-python/birds_v1.py
{ "start": 256, "end": 397 }
class ____: def swim(self): print("The albatross is swimming") def fly(self): print("The albatross is flying")
Albatross
python
getsentry__sentry
src/sentry/integrations/vsts/integration.py
{ "start": 15918, "end": 26962 }
class ____(IntegrationProvider): key = IntegrationProviderSlug.AZURE_DEVOPS.value name = "Azure DevOps" metadata = metadata api_version = "4.1" oauth_redirect_url = "/extensions/vsts/setup/" needs_default_identity = True integration_cls = VstsIntegration CURRENT_MIGRATION_VERSION = 1 ...
VstsIntegrationProvider
python
graphql-python__graphene
graphene/relay/node.py
{ "start": 3039, "end": 4359 }
class ____(AbstractNode): """An object with an ID""" @classmethod def Field(cls, *args, **kwargs): # noqa: N802 return NodeField(cls, *args, **kwargs) @classmethod def node_resolver(cls, only_type, root, info, id): return cls.get_node_from_global_id(info, id, only_type=only_type) ...
Node
python
astropy__astropy
astropy/io/votable/converters.py
{ "start": 32403, "end": 32565 }
class ____(Complex): """ Handle doubleComplex datatype. Pair of double-precision IEEE floating-point numbers. """ format = "c16"
DoubleComplex
python
tensorflow__tensorflow
tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py
{ "start": 71564, "end": 73170 }
class ____(test.TestCase): _PRNG = np.random.RandomState(341261) _SEED = 123456 def _GenerateUniqueRandomInputTensor(self, shape): num_elements = 1 for size in shape: num_elements *= size x = np.arange(num_elements, dtype=np.float32) self._PRNG.shuffle(x) return x.reshape(shape) def ...
FractionalMaxPoolGradTest
python
altair-viz__altair
tests/utils/test_core.py
{ "start": 1502, "end": 1630 }
class ____(FieldChannel, schemapi.SchemaBase): _schema = {json_schema_dict_str} _encoding_name = "strokeWidth"
StrokeWidth
python
neetcode-gh__leetcode
python/0417-pacific-atlantic-water-flow.py
{ "start": 0, "end": 1131 }
class ____: def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: ROWS, COLS = len(heights), len(heights[0]) pac, atl = set(), set() def dfs(r, c, visit, prevHeight): if ( (r, c) in visit or r < 0 or c < 0 ...
Solution
python
RobertCraigie__pyright-python
src/pyright/errors.py
{ "start": 54, "end": 216 }
class ____(Exception): message: str def __init__(self, message: str) -> None: super().__init__(message) self.message = message
PyrightError
python
realpython__materials
python-protocol/contents.py
{ "start": 358, "end": 648 }
class ____: def __init__(self): self.blog_posts = [] def create_content(self) -> str: return "Creating a post." def add_post(self, title: str, content: str) -> None: self.blog_posts.append(f"{title}: {content}") print(f"Post added: {title}")
Blog
python
falconry__falcon
falcon/response.py
{ "start": 53757, "end": 56547 }
class ____: """Defines a set of configurable response options. An instance of this class is exposed via :attr:`falcon.App.resp_options` and :attr:`falcon.asgi.App.resp_options` for configuring certain :class:`~.Response` behaviors. """ secure_cookies_by_default: bool """Set to ``False`` in...
ResponseOptions
python
ansible__ansible
lib/ansible/plugins/doc_fragments/default_callback.py
{ "start": 194, "end": 3308 }
class ____(object): DOCUMENTATION = r""" options: display_skipped_hosts: name: Show skipped hosts description: "Toggle to control displaying skipped task/host results in a task." type: bool default: yes env: - name: ANSIBLE_DISPLAY_SKIPPED_HOSTS i...
ModuleDocFragment
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol24.py
{ "start": 1185, "end": 1221 }
class ____(type): attr1: int
GMeta
python
google__flatbuffers
tests/service_test_generated.py
{ "start": 136, "end": 830 }
class ____(object): __slots__ = ['_tab'] @classmethod def GetRootAs(cls, buf, offset: int = 0): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = HelloRequest() x.Init(buf, n + offset) return x @classmethod def GetRootAsHelloRequest(cls, buf, offset=0): """This meth...
HelloRequest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/roles.py
{ "start": 6724, "end": 6846 }
class ____(FromClauseRole): __slots__ = () _role_name = "subject table for an INSERT, UPDATE or DELETE"
DMLTableRole
python
pallets__werkzeug
tests/test_datastructures.py
{ "start": 10577, "end": 10895 }
class ____(_ImmutableDictTests): storage_class = _ImmutableOrderedMultiDict def test_ordered_multidict_is_hashable(self): a = self.storage_class([("a", 1), ("b", 1), ("a", 2)]) b = self.storage_class([("a", 1), ("a", 2), ("b", 1)]) assert hash(a) != hash(b)
TestImmutableOrderedMultiDict
python
ray-project__ray
python/ray/serve/tests/test_model_composition.py
{ "start": 4016, "end": 4304 }
class ____: def __init__(self, s: str): self._s = s def __call__(self, *args): return self._s def test_single_node_deploy_success(serve_instance): m1 = Adder.bind(1) handle = serve.run(m1) assert handle.remote(41).result() == 42 @serve.deployment
Echo
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/array_ops_test.py
{ "start": 60684, "end": 61680 }
class ____(test_util.TensorFlowTestCase): @test_util.run_gpu_only def testEagerIdentity(self): with context.eager_mode(): def _test(x, y, device): self.assertAllEqual(x.numpy(), y.numpy()) self.assertIn(device, y.device.lower()) with test_util.force_gpu(): a = constant_op....
IdentityTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol1.py
{ "start": 2082, "end": 2619 }
class ____(ProtoBase2[_B], Protocol[_A, _B]): ... p5_1: Proto5[float, int] # This should generate an error because the second type argument # corresponds to _B, which is bound to int. p5_2: Proto5[int, float] def func1(): # This should generate an error because Protocol isn't # allowed in a type annotation...
Proto5
python
coleifer__peewee
tests/models.py
{ "start": 91689, "end": 91812 }
class ____(TestModel): timestamp = DateTimeField(constraints=[SQL('default (now())')]) @requires_postgresql
ServerDefault
python
python-pillow__Pillow
src/PIL/ImageFilter.py
{ "start": 8215, "end": 8406 }
class ____(BuiltinFilter): name = "Edge-enhance" # fmt: off filterargs = (3, 3), 2, 0, ( -1, -1, -1, -1, 10, -1, -1, -1, -1, ) # fmt: on
EDGE_ENHANCE
python
PyCQA__pylint
tests/functional/p/protocol_classes_abstract.py
{ "start": 908, "end": 1031 }
class ____(FooProtocol, metaclass=ABCMeta): """Doesn't subclass typing.Protocol but uses metaclass directly"""
AbcProtocol
python
cython__cython
Cython/Compiler/PyrexTypes.py
{ "start": 174132, "end": 175234 }
class ____(CType): def __init__(self, name, optional=False): self.name = name self.optional = optional def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if entity_code: return self.name + " " + entity_code else: ...
TemplatePlaceholderType
python
readthedocs__readthedocs.org
readthedocs/organizations/migrations/0011_add_stripe_subscription_field.py
{ "start": 182, "end": 1316 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("djstripe", "0010_alter_customer_balance"), ("organizations", "0010_add_stripe_customer"), ] operations = [ migrations.AddField( model_name="historicalorganization", name="stri...
Migration
python
jmcnamara__XlsxWriter
xlsxwriter/xmlwriter.py
{ "start": 586, "end": 7821 }
class ____: """ Simple XML writer class. """ def __init__(self) -> None: self.fh = None self.internal_fh = False def _set_filehandle(self, filehandle) -> None: # Set the writer filehandle directly. Mainly for testing. self.fh = filehandle self.internal_fh =...
XMLwriter
python
altair-viz__altair
tools/generate_schema_wrapper.py
{ "start": 14251, "end": 14635 }
class ____(SchemaGenerator): """Base template w/ an extra slot `{method_code}` after `{init_code}`.""" schema_class_template = textwrap.dedent( ''' class {classname}({basename}): """{docstring}""" _schema = {schema!r} {init_code} {method_code} ''' ) SchGe...
MethodSchemaGenerator
python
scipy__scipy
scipy/io/_harwell_boeing/_fortran_format_parser.py
{ "start": 723, "end": 2427 }
class ____: @classmethod def from_number(cls, n, min=None): """Given an integer, returns a "reasonable" IntFormat instance to represent any number between 0 and n if n > 0, -n and n if n < 0 Parameters ---------- n : int max number one wants to be able to rep...
IntFormat
python
huggingface__transformers
src/transformers/models/vit_mae/configuration_vit_mae.py
{ "start": 800, "end": 6372 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`ViTMAEModel`]. It is used to instantiate an ViT MAE model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar confi...
ViTMAEConfig
python
langchain-ai__langchain
libs/langchain/langchain_classic/agents/conversational_chat/output_parser.py
{ "start": 417, "end": 2320 }
class ____(AgentOutputParser): """Output parser for the conversational agent.""" format_instructions: str = FORMAT_INSTRUCTIONS """Default formatting instructions""" def get_format_instructions(self) -> str: """Returns formatting instructions for the given output parser.""" return self...
ConvoOutputParser
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/pipeline.py
{ "start": 9531, "end": 13141 }
class ____(Step): """ Pipeline step to update connector's metadata, acceptance-test-config and readme to manifest-only. """ context: ConnectorContext title = "Update Connector Metadata" async def _run(self) -> StepResult: connector = self.context.connector ## 1. Update the acc...
UpdateManifestOnlyFiles
python
readthedocs__readthedocs.org
readthedocs/builds/admin.py
{ "start": 699, "end": 883 }
class ____(admin.TabularInline): model = BuildCommandResult fields = ("command", "exit_code", "output") classes = ["collapse"] @admin.register(Build)
BuildCommandResultInline
python
giampaolo__psutil
tests/test_linux.py
{ "start": 19222, "end": 22664 }
class ____(PsutilTestCase): @staticmethod def meminfo_has_swap_info(): """Return True if /proc/meminfo provides swap metrics.""" with open("/proc/meminfo") as f: data = f.read() return 'SwapTotal:' in data and 'SwapFree:' in data def test_total(self): free_value ...
TestSystemSwapMemory
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-service-now/tests/test_snow_kb_reader.py
{ "start": 3619, "end": 24890 }
class ____: """Test class for ServiceNow Knowledge Base Reader.""" def test_initialization(self, mock_pysnc_imports): """Test that SnowKBReader initializes correctly.""" with patch( "llama_index.readers.service_now.base.ServiceNowClient", MockServiceNowClient, ):...
TestSnowKBReader
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/methodOverride3.py
{ "start": 1233, "end": 1301 }
class ____(F1[_T_F]): def do_stuff(self) -> Iterable[_T_F]: ...
F2
python
spyder-ide__spyder
spyder/plugins/shortcuts/tests/test_shortcuts.py
{ "start": 1326, "end": 10889 }
class ____(): def __init__(self, text): self.txt = text def text(self): return self.txt # ---- Tests ShortcutsTable @pytest.mark.skipif( sys.platform.startswith('linux') and running_in_ci(), reason="It fails on Linux due to the lack of a proper X server.") def test_shortcuts(shortcut_...
FilterTextMock
python
pytorch__pytorch
torch/utils/_pytree.py
{ "start": 25339, "end": 37889 }
class ____(tuple[_T_co, ...]): """A generic type stub for CPython's ``PyStructSequence`` type.""" __slots__: ClassVar[tuple[()]] = () n_fields: Final[int] # type: ignore[misc] n_sequence_fields: Final[int] # type: ignore[misc] n_unnamed_fields: Final[int] # type: ignore[misc] def __init_su...
structseq
python
kamyu104__LeetCode-Solutions
Python/path-sum-ii.py
{ "start": 181, "end": 841 }
class ____(object): # @param root, a tree node # @param sum, an integer # @return a list of lists of integers def pathSum(self, root, sum): return self.pathSumRecu([], [], root, sum) def pathSumRecu(self, result, cur, root, sum): if root is None: return result ...
Solution
python
apache__airflow
task-sdk/src/airflow/sdk/api/datamodels/_generated.py
{ "start": 14363, "end": 14703 }
class ____(BaseModel): """ Asset schema for responses with fields that are needed for Runtime. """ name: Annotated[str, Field(title="Name")] uri: Annotated[str, Field(title="Uri")] group: Annotated[str, Field(title="Group")] extra: Annotated[dict[str, JsonValue] | None, Field(title="Extra")...
AssetResponse
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F821_29.py
{ "start": 424, "end": 663 }
class ____(DeclarativeBase): some_mapping: Mapped[list[Bar]] | None = None # Should not trigger F821 (resolveable forward reference) simplified: list[Bar] | None = None # Should not trigger F821 (resolveable forward reference)
Base
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 206199, "end": 208245 }
class ____(GeneratedAirbyteSource): class OAuth20: @public def __init__(self, access_token: str, credentials: Optional[str] = None): self.credentials = check.opt_str_param(credentials, "credentials") self.access_token = check.str_param(access_token, "access_token") class...
ZendeskSupportSource
python
huggingface__transformers
tests/models/big_bird/test_modeling_big_bird.py
{ "start": 15715, "end": 24445 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( BigBirdModel, BigBirdForPreTraining, BigBirdForMaskedLM, BigBirdForCausalLM, BigBirdForMultipleChoice, BigBirdForQuestionAnswering, ...
BigBirdModelTest
python
walkccc__LeetCode
solutions/107. Binary Tree Level Order Traversal II/107.py
{ "start": 0, "end": 452 }
class ____: def levelOrderBottom(self, root: TreeNode | None) -> list[list[int]]: if not root: return [] ans = [] q = collections.deque([root]) while q: currLevel = [] for _ in range(len(q)): node = q.popleft() currLevel.append(node.val) if node.left: ...
Solution
python
sympy__sympy
sympy/functions/elementary/hyperbolic.py
{ "start": 18327, "end": 24595 }
class ____(HyperbolicFunction): r""" ``tanh(x)`` is the hyperbolic tangent of ``x``. The hyperbolic tangent function is $\frac{\sinh(x)}{\cosh(x)}$. Examples ======== >>> from sympy import tanh >>> from sympy.abc import x >>> tanh(x) tanh(x) See Also ======== sympy.f...
tanh
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_dashboard.py
{ "start": 6745, "end": 10556 }
class ____: @pytest.mark.parametrize( ("params", "expected"), [ ( {"start_date": "2023-01-01T00:00", "end_date": "2023-08-02T00:00"}, { "dag_run_states": {"failed": 1, "queued": 1, "running": 1, "success": 1}, "dag_r...
TestHistoricalMetricsDataEndpoint
python
doocs__leetcode
solution/2200-2299/2221.Find Triangular Sum of an Array/Solution.py
{ "start": 0, "end": 224 }
class ____: def triangularSum(self, nums: List[int]) -> int: for k in range(len(nums) - 1, 0, -1): for i in range(k): nums[i] = (nums[i] + nums[i + 1]) % 10 return nums[0]
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_commas/COM81.py
{ "start": 6907, "end": 7158 }
class ____[T,]: pass # t-string examples kwargs.pop("remove", t"this {trailing_comma}",) kwargs.pop("remove", t"this {f"{trailing_comma}"}",) t"""This is a test. { "Another sentence." if True else "Don't add a trailing comma here ->" }"""
C
python
pytorch__pytorch
test/dynamo/test_install_free_tensors.py
{ "start": 12786, "end": 20778 }
class ____(torch._dynamo.test_case.TestCase): @torch._dynamo.config.patch(inline_inbuilt_nn_modules=True) @torch._dynamo.config.patch(install_free_tensors=True) def check_export_matches_expectation( self, fn_to_export: Callable, expected_num_exported_inputs: int, example_inpu...
InstallParamsWhenExport
python
pytorch__pytorch
torch/distributed/pipelining/microbatch.py
{ "start": 1182, "end": 1430 }
class ____(_CustomReducer): pass sum_reducer = _LossReducer(torch.tensor(0.0), operator.add) # Default chunking dimension is 0. This is used for the case where the user did # not specify a chunking dimension. DEFAULT_CHUNK_DIM = 0
_LossReducer
python
run-llama__llama_index
llama-index-integrations/program/llama-index-program-guidance/llama_index/program/guidance/base.py
{ "start": 489, "end": 3070 }
class ____(BaseLLMFunctionProgram["GuidanceLLM"]): """ A guidance-based function that returns a pydantic model. Note: this interface is not yet stable. """ def __init__( self, output_cls: Type[BaseModel], prompt_template_str: str, guidance_llm: Optional["GuidanceLLM...
GuidancePydanticProgram
python
huggingface__transformers
src/transformers/models/instructblip/modeling_instructblip.py
{ "start": 11380, "end": 12480 }
class ____(GradientCheckpointingLayer): def __init__(self, config: InstructBlipConfig): super().__init__() self.embed_dim = config.hidden_size self.self_attn = InstructBlipAttention(config) self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) self.mlp = ...
InstructBlipEncoderLayer
python
pytorch__pytorch
torch/__init__.py
{ "start": 70529, "end": 70755 }
class ____(_LegacyStorage): @classproperty def dtype(self): _warn_typed_storage_removal(stacklevel=3) return self._dtype @classproperty def _dtype(self): return torch.double
DoubleStorage
python
getsentry__sentry
src/sentry/integrations/api/serializers/rest_framework/data_forwarder.py
{ "start": 1170, "end": 9796 }
class ____(Serializer): organization_id = serializers.IntegerField() is_enabled = serializers.BooleanField(default=True) enroll_new_projects = serializers.BooleanField(default=False) provider = serializers.ChoiceField( choices=[ (DataForwarderProviderSlug.SEGMENT, "Segment"), ...
DataForwarderSerializer
python
walkccc__LeetCode
solutions/2781. Length of the Longest Valid Substring/2781-2.py
{ "start": 569, "end": 1046 }
class ____: def longestValidSubstring(self, word: str, forbidden: list[str]) -> int: ans = 0 trie = Trie() for s in forbidden: trie.insert(s) # r is the rightmost index to make word[l..r] a valid substring. r = len(word) - 1 for l in range(len(word) - 1, -1, -1): for end in range...
Solution
python
jupyterlab__jupyterlab
jupyterlab/labapp.py
{ "start": 8983, "end": 9855 }
class ____(JupyterApp): version = version description = """ Print the configured paths for the JupyterLab application The application path can be configured using the JUPYTERLAB_DIR environment variable. The user settings path can be configured using the JUPYTERLAB_SETTINGS_DIR envi...
LabPathApp
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_constraints.py
{ "start": 1612, "end": 3696 }
class ____: def test___str__(self) -> None: prop = bcpc.TypeOfAttr(Instance(Parent), "p0", Instance(Child0)) assert str(prop) == "TypeOfAttr(Instance(Parent), 'p0', Instance(Child0))" def test_is_valid(self) -> None: prop0 = bcpc.TypeOfAttr(Instance(Parent), "p0", Instance(Child0)) ...
Test_TypeOfAttr
python
apache__airflow
helm-tests/tests/helm_tests/webserver/test_webserver.py
{ "start": 50458, "end": 51080 }
class ____: """Tests webserver secret key secret.""" def test_should_add_annotations_to_webserver_secret_key_secret(self): docs = render_chart( values={ "airflowVersion": "2.10.5", "webserverSecretAnnotations": {"test_annotation": "test_annotation_value"}, ...
TestWebserverSecretKeySecret
python
plotly__plotly.py
plotly/graph_objs/splom/_stream.py
{ "start": 233, "end": 3489 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "splom" _path_str = "splom.stream" _valid_props = {"maxpoints", "token"} @property def maxpoints(self): """ Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, on...
Stream
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/compiler.py
{ "start": 11213, "end": 11463 }
class ____(_BaseCompilerStackEntry, total=False): compile_state: CompileState need_result_map_for_nested: bool need_result_map_for_compound: bool select_0: ReturnsRows insert_from_select: Select[Unpack[TupleAny]]
_CompilerStackEntry
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/config_types.py
{ "start": 6793, "end": 7918 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneConfigType, GrapheneWrappingConfigType) name = "ArrayConfigType" def __init__( self, get_config_type: Callable[[str], ConfigTypeSnap], config_type_snap: ConfigTypeSnap, ): self._config_type_sn...
GrapheneArrayConfigType
python
doocs__leetcode
solution/2800-2899/2815.Max Pair Sum in an Array/Solution.py
{ "start": 0, "end": 284 }
class ____: def maxSum(self, nums: List[int]) -> int: ans = -1 for i, x in enumerate(nums): for y in nums[i + 1 :]: v = x + y if ans < v and max(str(x)) == max(str(y)): ans = v return ans
Solution
python
huggingface__transformers
src/transformers/utils/dummy_torchaudio_objects.py
{ "start": 129, "end": 312 }
class ____(metaclass=DummyObject): _backends = ["torchaudio"] def __init__(self, *args, **kwargs): requires_backends(self, ["torchaudio"])
GraniteSpeechFeatureExtractor
python
weaviate__weaviate-python-client
weaviate/collections/queries/near_object/generate/sync.py
{ "start": 316, "end": 465 }
class ____( Generic[Properties, References], _NearObjectGenerateExecutor[ConnectionSync, Properties, References], ): pass
_NearObjectGenerate
python
tensorflow__tensorflow
tensorflow/tools/ci_build/update_version.py
{ "start": 2026, "end": 11758 }
class ____(object): """Version class object that stores SemVer version information.""" def __init__(self, major, minor, patch, identifier_string, version_type): """Constructor. Args: major: major string eg. (1) minor: minor string eg. (3) patch: patch string eg. (1) identifier_stri...
Version
python
pytorch__pytorch
torch/distributed/checkpoint/_experimental/checkpoint_process.py
{ "start": 1213, "end": 1520 }
class ____: """ A dataclass for storing the command to be sent to the worker process. Note: This relies on pickling to send the command to the worker process. Handle backward compatibility accordingly. """ request_type: RequestType payload: dict[str, Any] @dataclass
WorkerRequest
python
pyinstaller__pyinstaller
PyInstaller/lib/modulegraph/modulegraph.py
{ "start": 3623, "end": 5194 }
class ____ (namedtuple("DependencyInfo", ["conditional", "function", "tryexcept", "fromlist"])): __slots__ = () def _merged(self, other): if (not self.conditional and not self.function and not self.tryexcept) \ or (not other.conditional and not other.function and not ot...
DependencyInfo
python
numba__numba
numba/cuda/cudadrv/driver.py
{ "start": 89811, "end": 92747 }
class ____(Linker): """ Linker supporting Minor Version Compatibility, backed by the cubinlinker package. """ def __init__(self, max_registers=None, lineinfo=False, cc=None): try: from cubinlinker import CubinLinker except ImportError as err: raise ImportError...
MVCLinker
python
has2k1__plotnine
plotnine/facets/facet_grid.py
{ "start": 567, "end": 11755 }
class ____(facet): """ Wrap 1D Panels onto 2D surface Parameters ---------- rows : Variable expressions along the rows of the facets/panels. Each expression is evaluated within the context of the dataframe. cols : Variable expressions along the columns of the facets/pane...
facet_grid
python
pytorch__pytorch
torch/_inductor/fx_passes/group_batch_fusion.py
{ "start": 44917, "end": 47700 }
class ____(BatchPointwiseOpsFusionFactory): """ Batch simple match related ops such as nan_to_num in pre grad pass. """ def __init__(self, op, **kwargs): super().__init__(op, **kwargs) self.op = op def match(self, node: torch.fx.Node): input = get_arg_value(node, 0, "input"...
BatchMathOpsPreGradFusion
python
google__jax
tests/mosaic/gpu_test.py
{ "start": 95266, "end": 100959 }
class ____(TestCase): def test_wg_communication(self): i32 = ir.IntegerType.get_signless(32) def kernel(ctx, dst, scratch): tmp, barriers = scratch del ctx # Unused. wg_idx = arith.divui(mgpu.warp_idx(), c(4, i32)) is_first_wg = arith.cmpi(arith.CmpIPredicate.eq, wg_idx, c(0, i32)) ...
BarrierTest
python
django-haystack__django-haystack
test_haystack/elasticsearch5_tests/test_backend.py
{ "start": 60925, "end": 61797 }
class ____(TestCase): def setUp(self): self.raw_es = elasticsearch.Elasticsearch( settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"] ) def test_recreate_index(self): clear_elasticsearch_index() sb = connections["elasticsearch"].get_backend() sb.silently_f...
RecreateIndexTestCase
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 31870, "end": 32622 }
class ____(unittest.TestCase): """Tests date_time in the ru_RU locale""" def setUp(self): self.fake = Faker("ru_RU") Faker.seed(0) def test_day(self): for _ in range(50): day = self.fake.day_of_week() assert isinstance(day, str) assert day in RuP...
TestRuRu
python
catalyst-team__catalyst
examples/detection/models/yolo_x.py
{ "start": 5144, "end": 5919 }
class ____(nn.Module): """Focus width and height information into channel space.""" def __init__(self, in_channels, out_channels, ksize=1, stride=1, act="silu"): super().__init__() self.conv = BaseConv(in_channels * 4, out_channels, ksize, stride, act=act) def forward(self, x): # s...
Focus
python
huggingface__transformers
src/transformers/models/unispeech_sat/modeling_unispeech_sat.py
{ "start": 43691, "end": 48538 }
class ____(UniSpeechSatPreTrainedModel): def __init__(self, config: UniSpeechSatConfig): super().__init__(config) self.unispeech_sat = UniSpeechSatModel(config) self.dropout_features = nn.Dropout(config.feat_quantizer_dropout) self.quantizer = UniSpeechSatGumbelVectorQuantizer(confi...
UniSpeechSatForPreTraining
python
numba__numba
numba/cuda/tests/cudadrv/test_context_stack.py
{ "start": 679, "end": 2149 }
class ____(CUDATestCase): def tearDown(self): super().tearDown() cuda.close() def test_context_memory(self): try: mem = cuda.current_context().get_memory_info() except NotImplementedError: self.skipTest('EMM Plugin does not implement get_memory_info()') ...
TestContextAPI