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
walkccc__LeetCode
solutions/906. Super Palindromes/906.py
{ "start": 0, "end": 919 }
class ____: def superpalindromesInRange(self, left: str, right: str) -> int: def nextPalindrome(num: int) -> int: s = str(num) n = len(s) half = s[0:(n + 1) // 2] reversedHalf = half[:n // 2][::-1] candidate = int(half + reversedHalf) if candidate >= num: return candid...
Solution
python
allegroai__clearml
clearml/automation/parameters.py
{ "start": 9561, "end": 10604 }
class ____(Parameter): """ Discrete randomly sampled hyperparameter object. """ def __init__(self, name: str, values: Sequence[Any] = ()) -> (): """ Uniformly sample values form a list of discrete options. :param str name: The parameter name. Match the task hyperparameter name....
DiscreteParameterRange
python
huggingface__transformers
src/transformers/models/prophetnet/tokenization_prophetnet.py
{ "start": 7919, "end": 10152 }
class ____: """Runs WordPiece tokenization.""" def __init__(self, vocab, unk_token, max_input_chars_per_word=100): self.vocab = vocab self.unk_token = unk_token self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text): """ Tokenizes a piece ...
WordpieceTokenizer
python
ansible__ansible
test/lib/ansible_test/_internal/debugging.py
{ "start": 995, "end": 3709 }
class ____(metaclass=abc.ABCMeta): """Common debugger settings.""" port: int = 5678 """ The port on the origin host which is listening for incoming connections from the debugger. SSH port forwarding will be automatically configured for non-local hosts to connect to this port as needed. """ ...
DebuggerSettings
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/initVar1.py
{ "start": 144, "end": 411 }
class ____: init_var1: InitVarAlias[int] init_var2: InitVar[int] not_init_var1: int c = Container(1, 2, 3) reveal_type(c.not_init_var1, expected_text="int") # This should generate an error c.init_var1 # This should generate an error c.init_var2
Container
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/eradicate/ERA001.py
{ "start": 263, "end": 1537 }
class ____(): pass # b = c dictionary = { # "key1": 123, # noqa: ERA001 # "key2": 456, # "key3": 789, # test } #import os # noqa # case 1: # try: # try: # with comment # try: print() # except: # except Foo: # except Exception as e: print(e) # Script tag without an opening tag (Error) # re...
A
python
ApeWorX__ape
src/ape_ethereum/ecosystem.py
{ "start": 11295, "end": 11537 }
class ____(BaseEthereumConfig): mainnet: NetworkConfig = create_network_config(block_time=13) holesky: NetworkConfig = create_network_config(block_time=13) sepolia: NetworkConfig = create_network_config(block_time=15)
EthereumConfig
python
astropy__astropy
astropy/io/votable/exceptions.py
{ "start": 48570, "end": 48758 }
class ____(VOWarning, ValueError): """ All ``TIMESYS`` elements must have an ``ID`` attribute. """ message_template = "ID attribute is required for all TIMESYS elements"
E22
python
getsentry__sentry
src/sentry/models/groupowner.py
{ "start": 1711, "end": 1802 }
class ____(TypedDict): type: str owner: str date_added: datetime
OwnersSerialized
python
cython__cython
docs/examples/tutorial/clibraries/queue3.py
{ "start": 75, "end": 2303 }
class ____: """A queue class for C integer values. >>> q = Queue() >>> q.append(5) >>> q.peek() 5 >>> q.pop() 5 """ _c_queue = cython.declare(cython.pointer[cqueue.Queue]) def __cinit__(self): self._c_queue = cqueue.queue_new() if self._c_queue is cython.NULL: ...
Queue
python
bokeh__bokeh
tests/unit/bokeh/util/test_strings.py
{ "start": 1436, "end": 2198 }
class ____: def test_no_argument(self) -> None: doc__ = "hello world" assert bus.format_docstring(doc__) == doc__ doc__ = None assert bus.format_docstring(doc__) is None def test_arguments_unused(self) -> None: doc__ = "hello world" assert bus.format_docstring(do...
Test_format_docstring
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 220212, "end": 220523 }
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("CheckRun", graphql_name="node")
CheckRunEdge
python
chroma-core__chroma
chromadb/server/fastapi/types.py
{ "start": 648, "end": 908 }
class ____(BaseModel): embeddings: Optional[List[Any]] = None metadatas: Optional[List[Optional[Dict[Any, Any]]]] = None documents: Optional[List[Optional[str]]] = None uris: Optional[List[Optional[str]]] = None ids: List[str]
UpdateEmbedding
python
gevent__gevent
src/gevent/tests/known_failures.py
{ "start": 3952, "end": 4249 }
class ____(_Definition): __slots__ = ( 'reason', ) def __init__(self, reason='', when=ALWAYS, run_alone=NEVER, ignore_coverage=NEVER, options=None): _Definition.__init__(self, when, run_alone, ignore_coverage, options) self.reason = reason
_Action
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/alloy_db.py
{ "start": 21752, "end": 27934 }
class ____(AlloyDBWriteBaseOperator): """ Create an Instance in an Alloy DB cluster. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:AlloyDBCreateInstanceOperator` :param cluster_id: Required. ID of the cluster for creating ...
AlloyDBCreateInstanceOperator
python
tiangolo__fastapi
docs_src/response_model/tutorial002.py
{ "start": 114, "end": 350 }
class ____(BaseModel): username: str password: str email: EmailStr full_name: Union[str, None] = None # Don't do this in production! @app.post("/user/") async def create_user(user: UserIn) -> UserIn: return user
UserIn
python
doocs__leetcode
solution/2600-2699/2644.Find the Maximum Divisibility Score/Solution.py
{ "start": 0, "end": 347 }
class ____: def maxDivScore(self, nums: List[int], divisors: List[int]) -> int: ans, mx = divisors[0], 0 for div in divisors: cnt = sum(x % div == 0 for x in nums) if mx < cnt: mx, ans = cnt, div elif mx == cnt and ans > div: ans = ...
Solution
python
google__jax
jax/_src/monitoring.py
{ "start": 1050, "end": 1212 }
class ____(Protocol): def __call__(self, event: str, duration_secs: float, **kwargs: str | int) -> None: ...
EventDurationListenerWithMetadata
python
davidhalter__jedi
test/completion/recursion.py
{ "start": 1240, "end": 1340 }
class ____: def a(self, b): for x in [self.a(i) for i in b]: #? x
A
python
kamyu104__LeetCode-Solutions
Python/minimum-area-rectangle.py
{ "start": 992, "end": 1467 }
class ____(object): def minAreaRect(self, points): """ :type points: List[List[int]] :rtype: int """ lookup = set() result = float("inf") for x1, y1 in points: for x2, y2 in lookup: if (x1, y2) in lookup and (x2, y1) in lookup: ...
Solution2
python
protocolbuffers__protobuf
src/google/protobuf/util/python/field_mask_util_test.py
{ "start": 805, "end": 5420 }
class ____(parameterized.TestCase): def test_merge_message_to_simple(self): source = timestamp_pb2.Timestamp(seconds=1, nanos=2) mask = field_mask_pb2.FieldMask(paths=["seconds"]) destination = timestamp_pb2.Timestamp(seconds=3, nanos=4) result = field_mask_util.FieldMaskUtil.MergeMessageTo( ...
FieldMaskUtilTest
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 95480, "end": 96900 }
class ____(fixtures.DeclarativeMappedTest): run_define_tables = None run_create_tables = None run_inserts = None run_deletes = None @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class Foo(Base): __tablename__ = "foo" id = Column(Integ...
OnlyRelationshipTest
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/ops.py
{ "start": 469, "end": 4273 }
class ____(Config): connection_id: str = Field( ..., description=( "Parsed json dictionary representing the details of the Airbyte connector after the" " sync successfully completes. See the [Airbyte API" " Docs](https://airbyte-public-api-docs.s3.us-east-2.amazon...
AirbyteSyncConfig
python
doocs__leetcode
solution/1500-1599/1519.Number of Nodes in the Sub-Tree With the Same Label/Solution.py
{ "start": 0, "end": 514 }
class ____: def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]: def dfs(i, fa): ans[i] -= cnt[labels[i]] cnt[labels[i]] += 1 for j in g[i]: if j != fa: dfs(j, i) ans[i] += cnt[labels[i]] ...
Solution
python
kamyu104__LeetCode-Solutions
Python/cracking-the-safe.py
{ "start": 2387, "end": 3121 }
class ____(object): def crackSafe(self, n, k): """ :type n: int :type k: int :rtype: str """ result = [str(k-1)]*(n-1) lookup = set() total = k**n while len(lookup) < total: node = result[len(result)-n+1:] for i in xrang...
Solution4
python
google__jax
jax/_src/config.py
{ "start": 7474, "end": 7542 }
class ____: pass no_default = NoDefault() config_states = {}
NoDefault
python
getsentry__sentry
src/sentry/hybridcloud/rpc/pagination.py
{ "start": 672, "end": 2007 }
class ____(RpcModel): encoded_cursor: str | None = None per_page: int = -1 @classmethod def from_endpoint_request(cls, e: "Endpoint", request: Request) -> "RpcPaginationArgs": return RpcPaginationArgs( encoded_cursor=request.GET.get(e.cursor_name), per_page=e.get_per_page(request) ...
RpcPaginationArgs
python
huggingface__transformers
src/transformers/models/dpr/tokenization_dpr_fast.py
{ "start": 15274, "end": 16103 }
class ____(CustomDPRReaderTokenizerMixin, BertTokenizer): r""" Constructs a "fast" DPRReader tokenizer (backed by HuggingFace's *tokenizers* library). [`DPRReaderTokenizerFast`] is almost identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation splitting and wordpiece. The differenc...
DPRReaderTokenizerFast
python
coleifer__peewee
peewee.py
{ "start": 187159, "end": 187538 }
class ____(object): def __init__(self): self._refs = [] def set_field(self, model, field, name): self._refs.append((model, field, name)) def set_model(self, through_model): for src_model, m2mfield, name in self._refs: m2mfield.through_model = through_model s...
DeferredThroughModel
python
django__django
django/forms/fields.py
{ "start": 10674, "end": 12682 }
class ____(Field): widget = NumberInput default_error_messages = { "invalid": _("Enter a whole number."), } re_decimal = _lazy_re_compile(r"\.0*\s*$") def __init__(self, *, max_value=None, min_value=None, step_size=None, **kwargs): self.max_value, self.min_value, self.step_size = ma...
IntegerField
python
django__django
django/db/models/functions/comparison.py
{ "start": 5709, "end": 6409 }
class ____(Func): """ Return the minimum expression. If any expression is null the return value is database-specific: On PostgreSQL, return the minimum not-null expression. On MySQL, Oracle, and SQLite, if any expression is null, return null. """ function = "LEAST" def __init__(self, ...
Least
python
huggingface__transformers
src/transformers/models/grounding_dino/processing_grounding_dino.py
{ "start": 3433, "end": 3906 }
class ____(ProcessingKwargs, total=False): _defaults = { "text_kwargs": { "add_special_tokens": True, "padding": False, "stride": 0, "return_overflowing_tokens": False, "return_special_tokens_mask": False, "return_offsets_mapping": Fals...
GroundingDinoProcessorKwargs
python
huggingface__transformers
tests/models/roformer/test_modeling_roformer.py
{ "start": 14065, "end": 18956 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( RoFormerModel, RoFormerForMaskedLM, RoFormerForCausalLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassific...
RoFormerModelTest
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 98553, "end": 99224 }
class ____(Structure): pass # opaque handle c_nvmlGpuInstance_t = POINTER(struct_c_nvmlGpuInstance_t) NVML_COMPUTE_INSTANCE_PROFILE_1_SLICE = 0x0 NVML_COMPUTE_INSTANCE_PROFILE_2_SLICE = 0x1 NVML_COMPUTE_INSTANCE_PROFILE_3_SLICE = 0x2 NVML_COMPUTE_INSTANCE_PROFILE_4_SLICE = 0x3 NVML_COMPUTE_INST...
struct_c_nvmlGpuInstance_t
python
pytorch__pytorch
functorch/examples/maml_omniglot/support/omniglot_loaders.py
{ "start": 1040, "end": 4639 }
class ____(data.Dataset): urls = [ "https://github.com/brendenlake/omniglot/raw/master/python/images_background.zip", "https://github.com/brendenlake/omniglot/raw/master/python/images_evaluation.zip", ] raw_folder = "raw" processed_folder = "processed" training_file = "training.pt" ...
Omniglot
python
doocs__leetcode
solution/1100-1199/1143.Longest Common Subsequence/Solution.py
{ "start": 0, "end": 451 }
class ____: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m, n = len(text1), len(text2) f = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if text1[i - 1] == text2[j - 1]: f[i][j] ...
Solution
python
python__mypy
mypy/fscache.py
{ "start": 1241, "end": 11102 }
class ____: def __init__(self) -> None: # The package root is not flushed with the caches. # It is set by set_package_root() below. self.package_root: list[str] = [] self.flush() def set_package_root(self, package_root: list[str]) -> None: self.package_root = package_roo...
FileSystemCache
python
django__django
tests/timezones/admin.py
{ "start": 138, "end": 339 }
class ____(admin.ModelAdmin): readonly_fields = ("created", "updated") site = admin.AdminSite(name="admin_tz") site.register(Event, EventAdmin) site.register(Timestamp, TimestampAdmin)
TimestampAdmin
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/config.py
{ "start": 9296, "end": 12586 }
class ____: def __init__(self, db, db_opts, options, file_config): self._set_name(db) self.db = db self.db_opts = db_opts self.options = options self.file_config = file_config self.test_schema = "test_schema" self.test_schema_2 = "test_schema_2" self....
Config
python
scipy__scipy
benchmarks/benchmarks/test_functions.py
{ "start": 7101, "end": 7418 }
class ____: target_E = -959.6407 solution = [512, 404.2319] xmin = np.array([-512., -512]) xmax = np.array([512., 512]) def fun(self, x): a = -(x[1] + 47) * np.sin(np.sqrt(abs(x[1] + x[0]/2. + 47))) b = -x[0] * np.sin(np.sqrt(abs(x[0] - (x[1] + 47)))) return a + b
EggHolder
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/policy/checkpoint_manager.py
{ "start": 284, "end": 456 }
class ____: steps: int file_path: str reward: Optional[float] creation_time: float auxillary_file_paths: List[str] = attr.ib(factory=list)
ModelCheckpoint
python
django__django
tests/queries/models.py
{ "start": 6086, "end": 6185 }
class ____(models.Model): custom = models.ForeignKey(CustomPk, models.CASCADE, null=True)
Related
python
pytorch__pytorch
test/ao/sparsity/test_sparsity_utils.py
{ "start": 778, "end": 5854 }
class ____(TestCase): def test_module_to_fqn(self): """ Tests that module_to_fqn works as expected when compared to known good module.get_submodule(fqn) function """ for model_class in model_list: model = model_class() list_of_modules = [m for _, m in ...
TestSparsityUtilFunctions
python
tensorflow__tensorflow
tensorflow/python/framework/subscribe.py
{ "start": 2346, "end": 13004 }
class ____(object): """Helper class to manage calculating and caching control_outputs in graph.""" __slots__ = ['cache'] def __init__(self): self.cache = {} def calc_control_outputs(self, graph): """Returns the map of control_outputs for a given graph. Args: graph: The graph to parse. ...
_ControlOutputCache
python
python__mypy
mypy/types.py
{ "start": 52831, "end": 63144 }
class ____(ProperType): """An instance type of form C[T1, ..., Tn]. The list of type variables may be empty. Several types have fallbacks to `Instance`, because in Python everything is an object and this concept is impossible to express without intersection types. We therefore use fallbacks for al...
Instance
python
numpy__numpy
benchmarks/benchmarks/bench_ma.py
{ "start": 8474, "end": 9209 }
class ____(Benchmark): param_names = ["size"] params = [["small", "large"]] def setup(self, size): # Set the proportion of masked values. prop_mask = 0.2 # Set up a "small" array with 10 vars and 10 obs. rng = np.random.default_rng() data = rng.random((10, 10), dtype...
Cov
python
tensorflow__tensorflow
tensorflow/python/eager/polymorphic_function/polymorphic_function.py
{ "start": 5560, "end": 7972 }
class ____(object): """Class keeping track of how many recent calls triggered tracing.""" __slots__ = ["_calls_per_tracings", "_call_count", "_total_warning_count"] def __init__(self): self._calls_per_tracings = [] self._total_warning_count = 0 self._call_count = 0 def called_with_tracing(self, f...
_FrequentTracingDetector
python
kubernetes-client__python
kubernetes/base/config/kube_config.py
{ "start": 25970, "end": 34423 }
class ____: """Reads and merges configuration from one or more kube-config's. The property `config` can be passed to the KubeConfigLoader as config_dict. It uses a path attribute from ConfigNode to store the path to kubeconfig. This path is required to load certs from relative paths. A method `sa...
KubeConfigMerger
python
django__django
tests/generic_views/test_edit.py
{ "start": 2709, "end": 3180 }
class ____(SimpleTestCase): def test_get_form(self): form_class = views.AuthorGetQuerySetFormView().get_form_class() self.assertEqual(form_class._meta.model, Author) def test_get_form_checks_for_object(self): mixin = ModelFormMixin() mixin.request = RequestFactory().get("/") ...
ModelFormMixinTests
python
Lightning-AI__lightning
src/lightning/fabric/plugins/environments/xla.py
{ "start": 904, "end": 4004 }
class ____(ClusterEnvironment): """Cluster environment for training on a TPU Pod with the `PyTorch/XLA <https://pytorch.org/xla>`_ library. A list of environment variables set by XLA can be found `here <https://github.com/pytorch/xla/blob/master/torch_xla/core/xla_env_vars.py>`_. """ def __init__...
XLAEnvironment
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_be_edtf_parseable.py
{ "start": 1294, "end": 3366 }
class ____(ColumnMapMetricProvider): condition_metric_name = "column_values.edtf_parseable" @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, level=None, **kwargs): def is_parseable(val): try: if type(val) != str: # noqa: E721 ...
ColumnValuesEdtfParseable
python
PrefectHQ__prefect
src/prefect/_internal/concurrency/threads.py
{ "start": 4683, "end": 11026 }
class ____(Portal): """ A portal to a worker running on a thread with an event loop. """ def __init__( self, name: str = "EventLoopThread", daemon: bool = False, run_once: bool = False, ): self.thread = threading.Thread( name=name, daemon=daemon, ...
EventLoopThread
python
ApeWorX__ape
src/ape/exceptions.py
{ "start": 16855, "end": 17278 }
class ____(ProviderError): """ Raised when connecting a provider to the wrong network. """ def __init__(self, chain_id: int, network: "NetworkAPI"): message = ( f"Provider connected to chain ID '{chain_id}', which does not match " f"network chain ID '{network.chain_id}'....
NetworkMismatchError
python
pyca__cryptography
tests/hazmat/primitives/test_x963_vectors.py
{ "start": 659, "end": 2077 }
class ____: _algorithms_dict: typing.ClassVar[ typing.Dict[str, typing.Type[hashes.HashAlgorithm]] ] = { "SHA-1": hashes.SHA1, "SHA-224": hashes.SHA224, "SHA-256": hashes.SHA256, "SHA-384": hashes.SHA384, "SHA-512": hashes.SHA512, } def test_x963(self, ba...
TestX963
python
ApeWorX__ape
src/ape/api/networks.py
{ "start": 2787, "end": 24079 }
class ____(ExtraAttributesMixin, BaseInterfaceModel): """ A set of related networks, such as Ethereum. """ name: str """ The name of the ecosystem. This should be set the same name as the plugin. """ # TODO: In 0.9, make @property that returns value from config, # and use REQUEST...
EcosystemAPI
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 2577, "end": 2883 }
class ____(tzinfo): """ UTC implementation taken from Python's docs. """ def __repr__(self): return "<UTC>" def utcoffset(self, dt): return timedelta(0) def tzname(self, dt): return "UTC" def dst(self, dt): return timedelta(0) utc = UTC()
UTC
python
getsentry__sentry
src/sentry/rules/conditions/event_attribute.py
{ "start": 10787, "end": 11102 }
class ____(AttributeHandler): minimum_path_length = 2 @classmethod def _handle(cls, path: list[str], event: GroupEvent) -> list[str]: if path[1] != "name": return [] return [event.data.get("sdk", {}).get(path[1])] @attribute_registry.register("stacktrace")
SdkAttributeHandler
python
pytorch__pytorch
torch/_export/db/examples/fn_with_kwargs.py
{ "start": 41, "end": 731 }
class ____(torch.nn.Module): """ Keyword arguments are not supported at the moment. """ def forward(self, pos0, tuple0, *myargs, mykw0, **mykwargs): out = pos0 for arg in tuple0: out = out * arg for arg in myargs: out = out * arg out = out * mykw0...
FnWithKwargs
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_tensor_dense_matmul_op_d9m_test.py
{ "start": 3860, "end": 4892 }
class ____(test.TestCase): """Test that SparseTensorDenseMatul operates reproducibly (on CPU only).""" @test_util.run_in_graph_and_eager_modes def testForward(self): for data_type in [ np.float16, np.float32, np.float64, np.complex64, np.complex128 ]: # skipping int32 and bfloat16 sparse_i...
SparseTensorDenseMatmulOpDeterministicTest
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/stateful.py
{ "start": 11807, "end": 20702 }
class ____(metaclass=StateMachineMeta): """A RuleBasedStateMachine gives you a structured way to define state machines. The idea is that a state machine carries the system under test and some supporting data. This data can be stored in instance variables or divided into Bundles. The state machine has a...
RuleBasedStateMachine
python
ray-project__ray
python/ray/tune/stopper/experiment_plateau.py
{ "start": 121, "end": 3208 }
class ____(Stopper): """Early stop the experiment when a metric plateaued across trials. Stops the entire experiment when the metric has plateaued for more than the given amount of iterations specified in the patience parameter. Args: metric: The metric to be monitored. std: The mi...
ExperimentPlateauStopper
python
scipy__scipy
scipy/interpolate/tests/test_bsplines.py
{ "start": 36347, "end": 45276 }
class ____: # # Test that FITPACK-based spl* functions can deal with BSpline objects # def setup_method(self): xx = np.linspace(0, 4.*np.pi, 41) yy = np.cos(xx) b = make_interp_spline(xx, yy) self.tck = (b.t, b.c, b.k) self.xx, self.yy, self.b = xx, yy, b ...
TestInterop
python
pydantic__pydantic
pydantic/warnings.py
{ "start": 1951, "end": 2269 }
class ____(PydanticDeprecationWarning): """A specific `PydanticDeprecationWarning` subclass defining functionality deprecated since Pydantic 2.0.""" def __init__(self, message: str, *args: object) -> None: super().__init__(message, *args, since=(2, 0), expected_removal=(3, 0))
PydanticDeprecatedSince20
python
pytorch__pytorch
test/dynamo/test_higher_order_ops.py
{ "start": 182384, "end": 185277 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[3, 3, 3]", L_y_: "f32[3, 3, 3]"): l_x_ = L_x_ l_y_ = L_y_ _saved_tensors_hooks_disable = torch._C._autograd._saved_tensors_hooks_disable("torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. Please open an is...
GraphModule
python
FactoryBoy__factory_boy
tests/test_mongoengine.py
{ "start": 667, "end": 851 }
class ____(MongoEngineFactory): class Meta: model = Person name = factory.Sequence(lambda n: 'name%d' % n) address = factory.SubFactory(AddressFactory)
PersonFactory
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/side_channel/outgoing_message.py
{ "start": 122, "end": 1961 }
class ____: """ Utility class for forming the message that is written to a SideChannel. All data is written in little-endian format using the struct module. """ def __init__(self): """ Create an OutgoingMessage with an empty buffer. """ self.buffer = bytearray() ...
OutgoingMessage
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_tool_param.py
{ "start": 413, "end": 661 }
class ____(TypedDict, total=False): type: Required[Literal["object"]] properties: Optional[Dict[str, object]] required: Optional[SequenceNotStr[str]] InputSchema: TypeAlias = Union[InputSchemaTyped, Dict[str, object]]
InputSchemaTyped
python
apache__airflow
providers/standard/src/airflow/providers/standard/operators/branch.py
{ "start": 1302, "end": 2919 }
class ____(SkipMixin): """Utility helper which handles the branching as one-liner.""" def do_branch( self, context: Context, branches_to_execute: str | Iterable[str] | None ) -> str | Iterable[str] | None: """Implement the handling of branching including logging.""" self.log.info("B...
BranchMixIn
python
doocs__leetcode
lcci/08.02.Robot in a Grid/Solution.py
{ "start": 0, "end": 543 }
class ____: def pathWithObstacles(self, obstacleGrid: List[List[int]]) -> List[List[int]]: def dfs(i, j): if i >= m or j >= n or obstacleGrid[i][j] == 1: return False ans.append([i, j]) obstacleGrid[i][j] = 1 if (i == m - 1 and j == n - 1) or d...
Solution
python
weaviate__weaviate-python-client
weaviate/auth.py
{ "start": 2515, "end": 3975 }
class ____: @staticmethod def api_key(api_key: str) -> _APIKey: return _APIKey(api_key) @staticmethod def client_credentials( client_secret: str, scope: Optional[SCOPES] = None ) -> _ClientCredentials: return _ClientCredentials(client_secret, scope) @staticmethod de...
Auth
python
kamyu104__LeetCode-Solutions
Python/basic-calculator.py
{ "start": 1373, "end": 2396 }
class ____(object): # @param {string} s # @return {integer} def calculate(self, s): operands, operators = [], [] operand = "" for i in reversed(xrange(len(s))): if s[i].isdigit(): operand += s[i] if i == 0 or not s[i-1].isdigit(): ...
Solution2
python
pola-rs__polars
py-polars/src/polars/io/cloud/credential_provider/_providers.py
{ "start": 9782, "end": 15947 }
class ____(CachingCredentialProvider): """ Azure Credential Provider. Using this requires the `azure-identity` Python package to be installed. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. "...
CredentialProviderAzure
python
python-openxml__python-docx
src/docx/styles/style.py
{ "start": 6141, "end": 7667 }
class ____(CharacterStyle): """A paragraph style. A paragraph style provides both character formatting and paragraph formatting such as indentation and line-spacing. """ def __repr__(self): return "_ParagraphStyle('%s') id: %s" % (self.name, id(self)) @property def next_paragraph_...
ParagraphStyle
python
sympy__sympy
sympy/utilities/_compilation/runners.py
{ "start": 243, "end": 8126 }
class ____: """ CompilerRunner base class. Parameters ========== sources : list of str Paths to sources. out : str flags : iterable of str Compiler flags. run_linker : bool compiler_name_exe : (str, str) tuple Tuple of compiler name & command to call. cwd :...
CompilerRunner
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0097_add_unique_constraint_to_datasource.py
{ "start": 155, "end": 1727 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
django__django
tests/inline_formsets/tests.py
{ "start": 4344, "end": 8565 }
class ____(TestCase): def test_inline_formset_factory(self): """ These should both work without a problem. """ inlineformset_factory(Parent, Child, fk_name="mother", fields="__all__") inlineformset_factory(Parent, Child, fk_name="father", fields="__all__") def test_excep...
InlineFormsetFactoryTest
python
instagram__MonkeyType
tests/test_stubs.py
{ "start": 12488, "end": 13336 }
class ____: def test_render(self): cm_stub = _func_stub_from_callable(Dummy.a_class_method.__func__) im_stub = _func_stub_from_callable(Dummy.an_instance_method) class_stub = ClassStub('Test', function_stubs=(cm_stub, im_stub), attribute_stubs=[ ...
TestClassStub
python
pytorch__pytorch
torch/_inductor/codegen/common.py
{ "start": 37762, "end": 48012 }
class ____: name: str cpp: Callable[..., str] # None when not impl in libdevice/triton triton: Optional[Callable[..., str]] = None # None when not impl in aten/.../vec cppvec: Optional[Callable[..., str]] = None type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND = ( ELEMENTWISE_TYP...
OverridesData
python
django__django
django/contrib/postgres/operations.py
{ "start": 4058, "end": 5190 }
class ____(NotInTransactionMixin, AddIndex): """Create an index using PostgreSQL's CREATE INDEX CONCURRENTLY syntax.""" atomic = False category = OperationCategory.ADDITION def describe(self): return "Concurrently create index %s on field(s) %s of model %s" % ( self.index.name, ...
AddIndexConcurrently
python
milvus-io__pymilvus
pymilvus/exceptions.py
{ "start": 1548, "end": 1627 }
class ____(MilvusException): """Raise when params are incorrect"""
ParamError
python
numba__numba
numba/core/pylowering.py
{ "start": 517, "end": 2273 }
class ____: """ A sentinel value for undefined variable created by Expr.undef. """ def __repr__(self): return "<undefined>" _UNDEFINED = _Undefined() # Map operators to methods on the PythonAPI class PYTHON_BINOPMAP = { operator.add: ("number_add", False), operator.sub: ("number_subt...
_Undefined
python
PyCQA__pylint
tests/data/clientmodule_test.py
{ "start": 114, "end": 546 }
class ____: """ Ancestor method """ cls_member = DoNothing() def __init__(self, value): local_variable = 0 self.attr = 'this method shouldn\'t have a docstring' self.__value = value def get_value(self): """ nice docstring ;-) """ return self.__value def set...
Ancestor
python
pytorch__pytorch
test/nn/test_convolution.py
{ "start": 1902, "end": 52977 }
class ____(NNTestCase): _do_cuda_memory_leak_check = True _do_cuda_non_default_stream = True def test_conv_backcompat(self): from torch.serialization import SourceChangeWarning # This file was generated by running on PyTorch 1.0.1 on Python 2: # # import torch #...
TestConvolutionNN
python
joke2k__faker
faker/providers/ssn/it_IT/__init__.py
{ "start": 96486, "end": 101143 }
class ____(SsnProvider): """ Generates italian fiscal codes. """ def ssn(self) -> str: sex: int = self.random_int(min=0, max=1) surname: str = self._get_surname_letters() name: str = self._get_name_letters(sex) year: str = "%02d" % self.random_int(min=0, max=99) ...
Provider
python
walkccc__LeetCode
solutions/3331. Find Subtree Sizes After Changes/3331.py
{ "start": 0, "end": 903 }
class ____: def findSubtreeSizes(self, parent: list[int], s: str) -> list[int]: n = len(parent) ans = [0] * n newParent = parent.copy() tree = [[] for _ in range(n)] for i in range(1, n): closest = self._findClosestAncestor(i, parent, s) if closest != -1: newParent[i] = closes...
Solution
python
nedbat__coveragepy
tests/test_context.py
{ "start": 5092, "end": 8178 }
class ____(CoverageTest): """Tests of dynamically changing contexts.""" SOURCE = """\ def helper(lineno): x = 2 def test_one(): a = 5 helper(6) def test_two(): a = 9 b = 10 if a > 11: b = 12 ...
DynamicContextTest
python
django__django
django/contrib/admin/options.py
{ "start": 4072, "end": 24416 }
class ____(metaclass=forms.MediaDefiningClass): """Functionality common to both ModelAdmin and InlineAdmin.""" autocomplete_fields = () raw_id_fields = () fields = None exclude = None fieldsets = None form = forms.ModelForm filter_vertical = () filter_horizontal = () radio_field...
BaseModelAdmin
python
django-import-export__django-import-export
import_export/widgets.py
{ "start": 23652, "end": 25772 }
class ____(Widget): """ Widget that converts between representations of a ManyToMany relationships as a list and an actual ManyToMany field. :param model: The model the ManyToMany field refers to (required). :param separator: Defaults to ``','``. :param field: A field on the related model. Defa...
ManyToManyWidget
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 504577, "end": 505310 }
class ____(sgqlc.types.Type): """Parameters to be used for the committer_email_pattern rule""" __schema__ = github_schema __field_names__ = ("name", "negate", "operator", "pattern") name = sgqlc.types.Field(String, graphql_name="name") """How this rule will appear to users.""" negate = sgqlc.t...
CommitterEmailPatternParameters
python
pydata__xarray
asv_bench/benchmarks/dataset_io.py
{ "start": 10104, "end": 10696 }
class ____(IOMultipleNetCDF): def setup(self): # TODO: Lazily skipped in CI as it is very demanding and slow. # Improve times and remove errors. _skip_slow() self.make_ds() self.format = "NETCDF3_64BIT" def time_write_dataset_netcdf4(self): xr.save_mfdataset( ...
IOWriteMultipleNetCDF3
python
astropy__astropy
astropy/nddata/mixins/tests/test_ndslicing.py
{ "start": 461, "end": 657 }
class ____(NDSlicingMixin, NDData): pass # Just some uncertainty (following the StdDevUncertainty implementation of # storing the uncertainty in a property 'array') with slicing.
NDDataSliceable
python
rq__rq
tests/test_spawn_worker.py
{ "start": 2757, "end": 4210 }
class ____(TimeoutTestCase, RQTestCase): @slow def test_idle_worker_warm_shutdown(self): """worker with no ongoing job receiving single SIGTERM signal and shutting down""" w = SpawnWorker('foo', connection=self.connection) self.assertFalse(w._stop_requested) p = Process(target=ki...
WorkerShutdownTestCase
python
PrefectHQ__prefect
src/prefect/cli/_prompts.py
{ "start": 10920, "end": 22536 }
class ____(PromptBase[str]): response_type: type[str] = str validate_error_message = "[prompt.invalid]Please enter a valid timezone." def process_response(self, value: str) -> str: try: is_valid_timezone(value) return value except ValueError: raise Invali...
RRuleTimezonePrompt
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/asyncio/result.py
{ "start": 1939, "end": 16744 }
class ____(_WithKeys, AsyncCommon[Row[Unpack[_Ts]]]): """An asyncio wrapper around a :class:`_result.Result` object. The :class:`_asyncio.AsyncResult` only applies to statement executions that use a server-side cursor. It is returned only from the :meth:`_asyncio.AsyncConnection.stream` and :meth:...
AsyncResult
python
airbytehq__airbyte
airbyte-integrations/connectors/source-recharge/unit_tests/integration/streams/test_onetimes.py
{ "start": 503, "end": 1826 }
class ____(StreamTestCase): _STREAM_NAME = "onetimes" @HttpMocker() def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None: http_mocker.get( self.stream_request().with_limit(250).with_updated_at_min(START_DATE).build(), get_stream_respon...
TestFullRefresh
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 99749, "end": 100143 }
class ____(Token): """ A token that will never match. """ def __init__(self) -> None: super().__init__() self._may_return_empty = True self.mayIndexError = False self.errmsg = "Unmatchable token" def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturn...
NoMatch
python
dagster-io__dagster
python_modules/libraries/dagster-gcp/dagster_gcp/pipes/clients/dataproc_job.py
{ "start": 1117, "end": 2349 }
class ____(TypedDict): request: NotRequired[SubmitJobRequest] project_id: NotRequired[str] region: NotRequired[str] job: NotRequired[Job] retry: NotRequired[Retry] timeout: NotRequired[float] metadata: NotRequired[Sequence[tuple[str, Union[str, bytes]]]] def _inject_pipes_args_into_list(ar...
SubmitJobParams
python
spyder-ide__spyder
spyder/api/widgets/toolbars.py
{ "start": 1337, "end": 1874 }
class ____(QObject): """ Filter tool tip events on toolbuttons. """ def eventFilter(self, obj, event): event_type = event.type() action = obj.defaultAction() if isinstance(obj, QToolButton) else None if event_type == QEvent.ToolTip and action is not None: if action.t...
ToolTipFilter
python
nedbat__coveragepy
tests/test_api.py
{ "start": 33271, "end": 39031 }
class ____(IncludeOmitTestsMixin, CoverageTest): """Test using `source`, `include`, and `omit` when measuring code.""" def setUp(self) -> None: super().setUp() # These tests use the TESTS_DIR/modules files, but they cd into it. To # keep tests from cross-contaminating, we make a copy o...
SourceIncludeOmitTest
python
gevent__gevent
src/gevent/tests/test__issue1686.py
{ "start": 543, "end": 2878 }
class ____(unittest.TestCase): def test(self): # pylint:disable=too-many-locals # If this test is broken, there are a few failure modes. # - In the original examples, the parent process just hangs, because the # child has raced ahead, spawned the greenlet and read the data. When the ...
TestDestroyInChildWithActiveSpawn