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
Netflix__metaflow
metaflow/_vendor/click/_winconsole.py
{ "start": 4260, "end": 5226 }
class ____(_WindowsConsoleRawIOBase): def writable(self): return True @staticmethod def _get_error_message(errno): if errno == ERROR_SUCCESS: return "ERROR_SUCCESS" elif errno == ERROR_NOT_ENOUGH_MEMORY: return "ERROR_NOT_ENOUGH_MEMORY" return "Window...
_WindowsConsoleWriter
python
scipy__scipy
scipy/optimize/_shgo_lib/_vertex.py
{ "start": 5006, "end": 5715 }
class ____: """Base class for a vertex cache for a simplicial complex.""" def __init__(self): self.cache = collections.OrderedDict() self.nfev = 0 # Feasible points self.index = -1 def __iter__(self): for v in self.cache: yield self.cache[v] return ...
VertexCacheBase
python
pdm-project__pdm
src/pdm/models/setup.py
{ "start": 356, "end": 1171 }
class ____: """ Abstraction of a Python project setup file. """ name: str | None = None version: str | None = None install_requires: list[str] = field(default_factory=list) extras_require: dict[str, list[str]] = field(default_factory=dict) python_requires: str | None = None summary:...
Setup
python
pyqtgraph__pyqtgraph
pyqtgraph/flowchart/library/Data.py
{ "start": 14101, "end": 14970 }
class ____(CtrlNode): """Select a slice from an array axis. """ nodeName = 'Slice' uiTemplate = [ ('axis', 'intSpin', {'value': 0, 'min': 0, 'max': 1000000}), ('start', 'intSpin', {'value': 0, 'min': -1000000, 'max': 1000000}), ('stop', 'intSpin', {'value': -1, 'min': -1000000, '...
Slice
python
PrefectHQ__prefect
tests/test_task_engine.py
{ "start": 56276, "end": 58967 }
class ____: @pytest.fixture async def flow_run_context(self, prefect_client: PrefectClient): @flow def f(): pass test_task_runner = ThreadPoolTaskRunner() flow_run = await prefect_client.create_flow_run(f) await propose_state(prefect_client, Running(), flow_r...
TestRunCountTracking
python
ray-project__ray
python/ray/data/_internal/datasource/parquet_datasink.py
{ "start": 4004, "end": 11563 }
class ____(_FileDatasink): def __init__( self, path: str, *, partition_cols: Optional[List[str]] = None, arrow_parquet_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, arrow_parquet_args: Optional[Dict[str, Any]] = None, min_rows_per_file: Optional[int]...
ParquetDatasink
python
getsentry__sentry
src/sentry/hybridcloud/rpc/caching/service.py
{ "start": 12470, "end": 12911 }
class ____(RpcService): key = "control_caching" local_mode = SiloMode.CONTROL @classmethod def get_local_implementation(cls) -> RpcService: from .impl import LocalControlCachingService return LocalControlCachingService() @rpc_method @abc.abstractmethod def clear_key(self, ...
ControlCachingService
python
python-openxml__python-docx
src/docx/image/exceptions.py
{ "start": 55, "end": 162 }
class ____(Exception): """The recognized image stream appears to be corrupted."""
InvalidImageStreamError
python
great-expectations__great_expectations
great_expectations/expectations/regex_based_column_map_expectation.py
{ "start": 1577, "end": 3719 }
class ____(ColumnMapMetricProvider): """Base class for all RegexColumnMapMetrics. RegexColumnMapMetric classes inheriting from RegexColumnMapMetricProvider are ephemeral, defined by their `regex` attribute, and registered during the execution of their associated RegexColumnMapExpectation. Metric Regis...
RegexColumnMapMetricProvider
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 539273, "end": 539774 }
class ____(sgqlc.types.Type): """Autogenerated return type of CreateMigrationSource""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "migration_source") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client perfor...
CreateMigrationSourcePayload
python
getsentry__sentry
src/sentry/core/endpoints/project_environments.py
{ "start": 965, "end": 3378 }
class ____(ProjectEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } @extend_schema( operation_id="List a Project's Environments", parameters=[ GlobalParams.ORG_ID_OR_SLUG, GlobalParams.PROJECT_ID_OR_SLUG, EnvironmentParams.VISIBILITY...
ProjectEnvironmentsEndpoint
python
getsentry__sentry
src/sentry/codecov/endpoints/sync_repos/serializers.py
{ "start": 113, "end": 1358 }
class ____(serializers.Serializer): """ Serializer for a sync repository response """ isSyncing = serializers.BooleanField() def to_representation(self, graphql_response): """ Transform the GraphQL response to the serialized format """ try: http_method =...
SyncReposSerializer
python
django__django
tests/sitemaps_tests/urls/https.py
{ "start": 106, "end": 482 }
class ____(SimpleSitemap): protocol = "https" secure_sitemaps = { "simple": HTTPSSitemap, } urlpatterns = [ path("secure/index.xml", views.index, {"sitemaps": secure_sitemaps}), path( "secure/sitemap-<section>.xml", views.sitemap, {"sitemaps": secure_sitemaps}, name="d...
HTTPSSitemap
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/call17.py
{ "start": 342, "end": 420 }
class ____(Generic[T_co]): def or_else(self, op: object) -> Ok[T_co]: ...
Ok
python
getsentry__sentry
src/sentry/notifications/types.py
{ "start": 8362, "end": 8490 }
class ____: is_disabled: bool is_active: bool has_only_inactive_subscriptions: bool @dataclass
GroupSubscriptionStatus
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py
{ "start": 49212, "end": 58948 }
class ____(SageMakerBaseOperator): """ Starts a model training job. After training completes, Amazon SageMaker saves the resulting model artifacts to an Amazon S3 location that you specify. .. seealso:: For more information on how to use this operator, take a look at the guide: :re...
SageMakerTrainingOperator
python
fluentpython__example-code-2e
13-protocol-abc/lotto.py
{ "start": 70, "end": 634 }
class ____(Tombola): def __init__(self, iterable): self._balls = list(iterable) # <1> def load(self, iterable): self._balls.extend(iterable) def pick(self): try: position = random.randrange(len(self._balls)) # <2> except ValueError: raise LookupEr...
LottoBlower
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_traversal.py
{ "start": 817, "end": 2131 }
class ____(FSDPTest): @property def world_size(self): if torch.torch.accelerator.is_available(): gpu_cnt = torch.accelerator.device_count() if gpu_cnt < 2: return gpu_cnt return 2 @skip_if_lt_x_gpu(2) def test_fsdp_modules(self): nested_wr...
TestTraversal
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_v2_test.py
{ "start": 185702, "end": 216989 }
class ____(test.TestCase, parameterized.TestCase): def test_defaults(self): categorical_column = fc.categorical_column_with_identity( key='aaa', num_buckets=3) embedding_dimension = 2 embedding_column = fc.embedding_column( categorical_column, dimension=embedding_dimension) self.asser...
EmbeddingColumnTest
python
davidhalter__jedi
test/completion/pep0526_variables.py
{ "start": 1873, "end": 1921 }
class ____: name: int = 1 #? int() DC().name
DC
python
pytorch__pytorch
torch/utils/_pytree.py
{ "start": 17129, "end": 23497 }
class ____: value: Any def _is_constant_holder(spec: "TreeSpec") -> bool: """Checks if the spec is from a pytree registered with register_constant""" return isinstance(spec._context, ConstantNode) def _retrieve_constant(spec: "TreeSpec") -> Any: """Given a spec from a pytree registered with register...
ConstantNode
python
sqlalchemy__sqlalchemy
test/orm/test_merge.py
{ "start": 62165, "end": 63027 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "data", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("data", PickleType(comparator=operator.eq)...
MutableMergeTest
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_heapq.py
{ "start": 1058, "end": 1499 }
class ____(__TestCase): def test_py_functions(self): for fname in func_names: self.assertEqual(getattr(py_heapq, fname).__module__, 'heapq') @skipUnless(c_heapq, 'requires _heapq') def test_c_functions(self): for fname in func_names: self.assertEqual(getattr(c_heapq,...
TestModules
python
Textualize__textual
docs/examples/styles/scrollbar_size2.py
{ "start": 448, "end": 816 }
class ____(App): CSS_PATH = "scrollbar_size2.tcss" def compose(self): yield Horizontal( ScrollableContainer(Label(TEXT * 5), id="v1"), ScrollableContainer(Label(TEXT * 5), id="v2"), ScrollableContainer(Label(TEXT * 5), id="v3"), ) if __name__ == "__main__":...
ScrollbarApp
python
ApeWorX__ape
src/ape/cli/paramtype.py
{ "start": 848, "end": 1117 }
class ____(click.ParamType): """ A param-type for ignoring param-types. Good to use when the multi-type handling happens already in a callback or in the command itself. """ def convert(self, value: Any, param, ctx) -> Any: return value
Noop
python
ray-project__ray
python/ray/serve/llm/deployment.py
{ "start": 444, "end": 2233 }
class ____(InternalLLMServer): """The implementation of the vLLM engine deployment. To build a Deployment object you should use `build_llm_deployment` function. We also expose a lower level API for more control over the deployment class through `serve.deployment` function. Examples: .. tes...
LLMServer
python
django__django
tests/queries/models.py
{ "start": 16650, "end": 16906 }
class ____(models.Model): name = models.CharField(max_length=20) has_blackboard = models.BooleanField(null=True) school = models.ForeignKey(School, models.CASCADE) students = models.ManyToManyField(Student, related_name="classroom")
Classroom
python
walkccc__LeetCode
solutions/1261. Find Elements in a Contaminated Binary Tree/1261.py
{ "start": 0, "end": 387 }
class ____: def __init__(self, root: TreeNode | None): self.vals = set() self.dfs(root, 0) def find(self, target: int) -> bool: return target in self.vals def dfs(self, root: TreeNode | None, val: int) -> None: if not root: return root.val = val self.vals.add(val) self.dfs(roo...
FindElements
python
pytorch__pytorch
test/inductor/test_multi_kernel.py
{ "start": 2498, "end": 12887 }
class ____(TestCase): def test_softmax(self, expect_multi_kernel=True): x = torch.rand(2, 1024).to(GPU_TYPE) ref = torch.softmax(x, -1) compiled_fn = torch.compile(torch.softmax) act, wrapper_code = run_and_get_code(compiled_fn, x, -1) # wrapper_code will contains 2 entries ...
MultiKernelTest
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 416767, "end": 418860 }
class ____: def test_against_R(self): # Test against R implementation in `distributionsrd` # library(distributionsrd) # options(digits=16) # x = 1.1 # b = 2 # a = 1.5 # m = 3 # s = 1.2 # ddoubleparetolognormal(x, b, a, m, s) # pdoublepa...
TestDParetoLognorm
python
google__pytype
pytype/tools/analyze_project/pytype_runner_test.py
{ "start": 18174, "end": 21588 }
class ____(TestBase): """Tests for PytypeRunner.write_build_statement.""" def write_build_statement(self, *args, **kwargs): conf = self.parser.config_from_defaults() with test_utils.Tempdir() as d: conf.output = d.path runner = make_runner([], [], conf) output = runner.write_build_stateme...
TestNinjaBuildStatement
python
openai__openai-python
src/openai/types/beta/assistant_stream_event.py
{ "start": 2436, "end": 2656 }
class ____(BaseModel): data: Run """ Represents an execution run on a [thread](https://platform.openai.com/docs/api-reference/threads). """ event: Literal["thread.run.completed"]
ThreadRunCompleted
python
kamyu104__LeetCode-Solutions
Python/permutations.py
{ "start": 34, "end": 709 }
class ____(object): # @param num, a list of integer # @return a list of lists of integers def permute(self, num): result = [] used = [False] * len(num) self.permuteRecu(result, used, [], num) return result def permuteRecu(self, result, used, cur, num): if len(cur...
Solution
python
keras-team__keras
keras/src/backend/common/backend_utils_test.py
{ "start": 579, "end": 1606 }
class ____(test_case.TestCase): def test_valid_padding_without_output_padding(self): """Test conversion with 'valid' padding and no output padding""" ( left_pad, right_pad, ) = _convert_conv_transpose_padding_args_from_keras_to_jax( kernel_size=3, ...
ConvertConvTransposePaddingArgsJAXTest
python
encode__django-rest-framework
tests/test_model_serializer.py
{ "start": 18270, "end": 18408 }
class ____(json.JSONDecoder): pass @pytest.mark.skipif(not hasattr(models, 'JSONField'), reason='no models.JSONField')
CustomJSONDecoder
python
pytorch__pytorch
torch/ao/pruning/scheduler/cubic_scheduler.py
{ "start": 168, "end": 3875 }
class ____(BaseScheduler): r"""Sets the sparsity level of each parameter group to the final sl plus a given exponential function. .. math:: s_i = s_f + (s_0 - s_f) \cdot \left( 1 - \frac{t - t_0}{n\Delta t} \right)^3 where :math:`s_i` is the sparsity at epoch :math:`t`, :math;`s_f` is the fin...
CubicSL
python
scrapy__scrapy
tests/CrawlerProcess/reactor_select_subclass_twisted_reactor_select.py
{ "start": 196, "end": 311 }
class ____(SelectReactor): pass reactor = SelectReactorSubclass() installReactor(reactor)
SelectReactorSubclass
python
tensorflow__tensorflow
tensorflow/python/eager/backprop.py
{ "start": 24812, "end": 50300 }
class ____: """Record operations for automatic differentiation. Operations are recorded if they are executed within this context manager and at least one of their inputs is being "watched". Trainable variables (created by `tf.Variable` or `tf.compat.v1.get_variable`, where `trainable=True` is default in bot...
GradientTape
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/pool/base.py
{ "start": 40872, "end": 52337 }
class ____(PoolProxiedConnection): """Proxies a DBAPI connection and provides return-on-dereference support. This is an internal object used by the :class:`_pool.Pool` implementation to provide context management to a DBAPI connection delivered by that :class:`_pool.Pool`. The public facing inter...
_ConnectionFairy
python
plotly__plotly.py
tests/test_core/test_graph_objs/test_repr.py
{ "start": 63, "end": 2223 }
class ____(TestCase): def test_trace_repr(self): N = 100 scatt = go.Scatter( y=list(range(N)), marker={"color": "green", "opacity": [e / N for e in range(N)]}, ) expected = """\ Scatter({ 'marker': {'color': 'green', 'opacity': [0.0, 0.01, ...
TestGraphObjRepr
python
qdrant__qdrant-client
tests/congruence_tests/test_recommendation.py
{ "start": 539, "end": 15326 }
class ____: __test__ = False def __init__(self): self.query_image = np.random.random(image_vector_size).tolist() @classmethod def simple_recommend_image(cls, client: QdrantBase) -> list[models.ScoredPoint]: return client.query_points( collection_name=COLLECTION_NAME, ...
TestSimpleRecommendation
python
mlflow__mlflow
tests/pyfunc/test_chat_agent.py
{ "start": 2652, "end": 2970 }
class ____(ChatAgent): @mlflow.trace def predict( self, messages: list[ChatAgentMessage], context: ChatContext, custom_inputs: dict[str, Any] ) -> ChatAgentResponse: mock_response = get_mock_response(messages) return ChatAgentResponse(**mock_response).model_dump()
SimpleDictChatAgent
python
PyCQA__pylint
doc/data/messages/u/unexpected-special-method-signature/good.py
{ "start": 0, "end": 122 }
class ____: def __enter__(self): pass def __exit__(self, type, value, traceback): pass
ContextManager
python
scipy__scipy
scipy/optimize/tests/test__shgo.py
{ "start": 1228, "end": 1695 }
class ____(StructTestFunction): def f(self, x): return x[0] ** 2 + x[1] ** 2 def g(x): return -(np.sum(x, axis=0) - 6.0) cons = wrap_constraints(g) test1_1 = StructTest1(bounds=[(-1, 6), (-1, 6)], expected_x=[0, 0]) test1_2 = StructTest1(bounds=[(0, 1), (0, 1)], ...
StructTest1
python
allegroai__clearml
clearml/backend_api/services/v2_23/datasets.py
{ "start": 61562, "end": 69317 }
class ____(Request): """ Commit changes to a draft version. :param version: Draft version ID :type version: str :param override_stats: Override version statistics (when provided, these will be used instead of computed statistics) :type override_stats: Statistics :param calculate_sta...
CommitVersionRequest
python
doocs__leetcode
solution/1800-1899/1864.Minimum Number of Swaps to Make the Binary String Alternating/Solution.py
{ "start": 0, "end": 375 }
class ____: def minSwaps(self, s: str) -> int: def calc(c: int) -> int: return sum((c ^ i & 1) != x for i, x in enumerate(map(int, s))) // 2 n0 = s.count("0") n1 = len(s) - n0 if abs(n0 - n1) > 1: return -1 if n0 == n1: return min(calc(0),...
Solution
python
sympy__sympy
sympy/polys/domains/ring.py
{ "start": 229, "end": 3245 }
class ____(Domain[Er]): """Represents a ring domain. """ is_Ring = True def get_ring(self): """Returns a ring associated with ``self``. """ return self def exquo(self, a, b): """Exact quotient of ``a`` and ``b``, implies ``__floordiv__``. """ if a % b: rai...
Ring
python
google__jax
jax/_src/numpy/reductions.py
{ "start": 79940, "end": 110922 }
class ____(Protocol): def __call__(self, a: ArrayLike, axis: Axis = None, dtype: DTypeLike | None = None, out: None = None) -> Array: ... def _cumulative_reduction( name: str, reduction: Callable[..., Array], a: ArrayLike, axis: int | None, dtype: DTypeLike | None, out: None = None, fill_...
CumulativeReduction
python
marshmallow-code__marshmallow
tests/base.py
{ "start": 6411, "end": 6634 }
class ____(Schema): title = fields.String() user = fields.Nested(UserSchema) collaborators = fields.List(fields.Nested(UserSchema())) categories = fields.List(fields.String) id = fields.String()
BlogSchema
python
apache__airflow
providers/airbyte/src/airflow/providers/airbyte/sensors/airbyte.py
{ "start": 1380, "end": 5737 }
class ____(BaseSensorOperator): """ Check for the state of a previously submitted Airbyte job. :param airbyte_job_id: Required. Id of the Airbyte job. :param airbyte_conn_id: Optional. The name of the Airflow connection to get connection information for Airbyte. Defaults to "airbyte_default". ...
AirbyteJobSensor
python
sqlalchemy__sqlalchemy
test/orm/test_selectin_relations.py
{ "start": 82989, "end": 91741 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "nodes", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("parent_id", Integer, ForeignKey("nodes.i...
SelfReferentialTest
python
tiangolo__fastapi
tests/test_response_model_as_return_annotation.py
{ "start": 442, "end": 49406 }
class ____(BaseModel): name: str price: float app = FastAPI() @app.get("/no_response_model-no_annotation-return_model") def no_response_model_no_annotation_return_model(): return User(name="John", surname="Doe") @app.get("/no_response_model-no_annotation-return_dict") def no_response_model_no_annotati...
Item
python
celery__celery
t/unit/backends/test_base.py
{ "start": 10790, "end": 12862 }
class ____: def setup_method(self): self.b = BaseBackend(self.app) def test_unpickleable(self): self.b.serializer = 'pickle' x = self.b.prepare_exception(Unpickleable(1, 2, 'foo')) assert isinstance(x, KeyError) y = self.b.exception_to_python(x) assert isinstanc...
test_prepare_exception
python
encode__django-rest-framework
rest_framework/relations.py
{ "start": 15857, "end": 16956 }
class ____(RelatedField): """ A read-write field that represents the target of the relationship by a unique 'slug' attribute. """ default_error_messages = { 'does_not_exist': _('Object with {slug_name}={value} does not exist.'), 'invalid': _('Invalid value.'), } def __init__...
SlugRelatedField
python
getsentry__sentry
src/sentry/web/forms/accounts.py
{ "start": 836, "end": 5009 }
class ____(forms.Form): username_field: Field[Any, Any] username = forms.CharField( label=_("Account"), max_length=128, widget=forms.TextInput(attrs={"placeholder": _("username or email"), "tabindex": 1}), ) password = forms.CharField( label=_("Password"), widget=...
AuthenticationForm
python
kamyu104__LeetCode-Solutions
Python/existence-of-a-substring-in-a-string-and-its-reverse.py
{ "start": 53, "end": 508 }
class ____(object): def isSubstringPresent(self, s): """ :type s: str :rtype: bool """ lookup = [[False]*26 for _ in xrange(26)] for i in xrange(len(s)-1): lookup[ord(s[i])-ord('a')][ord(s[i+1])-ord('a')] = True return any(lookup[ord(s[i+1])-ord('a...
Solution
python
pytorch__pytorch
.github/scripts/test_trymerge.py
{ "start": 7955, "end": 8441 }
class ____(GitRepo): def __init__(self) -> None: super().__init__(get_git_repo_dir(), get_git_remote_name()) def commits_resolving_gh_pr(self, pr_num: int) -> list[str]: return ["FakeCommitSha"] def commit_message(self, ref: str) -> str: return "super awesome commit message" @moc...
DummyGitRepo
python
ray-project__ray
rllib/utils/minibatch_utils.py
{ "start": 10342, "end": 11695 }
class ____: """Iterator for sharding batch into num_shards batches. Args: batch: The input multi-agent batch. num_shards: The number of shards to split the batch into. Yields: A MultiAgentBatch of size len(batch) / num_shards. """ def __init__(self, batch: MultiAgentBatch,...
ShardBatchIterator
python
ipython__ipython
IPython/testing/plugin/pytest_ipdoctest.py
{ "start": 5492, "end": 8137 }
class ____(Exception): def __init__(self, failures: Sequence["doctest.DocTestFailure"]) -> None: super().__init__() self.failures = failures def _init_runner_class() -> Type["IPDocTestRunner"]: import doctest from .ipdoctest import IPDocTestRunner class PytestDoctestRunner(IPDocTestRu...
MultipleDoctestFailures
python
celery__celery
celery/backends/redis.py
{ "start": 6703, "end": 25579 }
class ____(BaseKeyValueStoreBackend, AsyncBackendMixin): """Redis task result store. It makes use of the following commands: GET, MGET, DEL, INCRBY, EXPIRE, SET, SETEX """ ResultConsumer = ResultConsumer #: :pypi:`redis` client module. redis = redis connection_class_ssl = redis.SSLCon...
RedisBackend
python
has2k1__plotnine
plotnine/stats/stat_ellipse.py
{ "start": 360, "end": 7658 }
class ____(stat): """ Calculate normal confidence interval ellipse {usage} Parameters ---------- {common_parameters} type : Literal["t", "norm", "euclid"], default="t" The type of ellipse. `t` assumes a multivariate t-distribution. `norm` assumes a multivariate norm...
stat_ellipse
python
google__flatbuffers
python/flatbuffers/number_types.py
{ "start": 2595, "end": 2637 }
class ____(Int32Flags): pass
SOffsetTFlags
python
PyCQA__pylint
tests/functional/ext/docparams/return/missing_return_doc_Numpy.py
{ "start": 2455, "end": 2766 }
class ____: """test_ignores_ignored_argument_names_numpy Example of a method documenting the return type that an implementation should return. """ def foo(self, arg, _): """docstring ... Parameters ---------- arg : int An argument. """
Foo
python
networkx__networkx
networkx/classes/tests/test_special.py
{ "start": 1477, "end": 1611 }
class ____(_TestGraph): def setup_method(self): _TestGraph.setup_method(self) self.Graph = nx.Graph
TestSpecialGraph
python
geekcomputers__Python
Detect_Remove_loop.py
{ "start": 94, "end": 1729 }
class ____: def __init__(self): self.head = None def Insert_At_End(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return current = self.head while current.next: current = current.next curr...
Linked_List
python
pytorch__pytorch
test/dynamo/test_autograd_function.py
{ "start": 694, "end": 1138 }
class ____(torch.autograd.Function): # Test there is graph break in forward function @staticmethod def forward(ctx, foo): result = foo + foo torch._dynamo.graph_break() result = result + foo ctx.save_for_backward(result) return result @staticmethod def backwa...
CustomFunc3
python
tiangolo__fastapi
scripts/contributors.py
{ "start": 1143, "end": 1187 }
class ____(BaseModel): name: str
LabelNode
python
keras-team__keras
keras/src/backend/torch/core.py
{ "start": 3312, "end": 22700 }
class ____(KerasVariable): def _initialize(self, value): if isinstance(value, torch.nn.Parameter): # Reuse same parameter self._value = value else: self._value = torch.nn.Parameter( convert_to_tensor(value, dtype=self._dtype), requi...
Variable
python
jmcnamara__XlsxWriter
xlsxwriter/test/workbook/test_custom_sheet.py
{ "start": 1375, "end": 1966 }
class ____(unittest.TestCase): """ Test the Workbook _check_sheetname() method. """ def setUp(self): self.workbook = MyWorkbook() def tearDown(self): self.workbook.fileclosed = 1 def test_check_chartsheet(self): """Test the _check_sheetname() method""" sheet =...
TestCustomWorkBook
python
allegroai__clearml
clearml/utilities/pyhocon/config_tree.py
{ "start": 16474, "end": 16789 }
class ____(list): def __init__(self, iterable=[]): new_list = list(iterable) super(ConfigList, self).__init__(new_list) for index, value in enumerate(new_list): if isinstance(value, ConfigValues): value.parent = self value.key = index
ConfigList
python
kamyu104__LeetCode-Solutions
Python/excel-sheet-column-title.py
{ "start": 32, "end": 321 }
class ____(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ result = [] while n: result += chr((n-1)%26 + ord('A')) n = (n-1)//26 result.reverse() return "".join(result)
Solution
python
pytorch__pytorch
torch/testing/_internal/common_dist_composable.py
{ "start": 98, "end": 518 }
class ____(nn.Module): def __init__(self, device: torch.device): super().__init__() self.l1 = nn.Linear(100, 100, device=device) self.seq = nn.Sequential( nn.ReLU(), nn.Linear(100, 100, device=device), nn.ReLU(), ) self.l2 = nn.Linear(100, ...
UnitModule
python
apache__airflow
providers/google/tests/unit/google/cloud/transfers/test_sql_to_gcs.py
{ "start": 2820, "end": 20358 }
class ____: @pytest.mark.db_test @mock.patch("airflow.providers.google.cloud.transfers.sql_to_gcs.NamedTemporaryFile") @mock.patch("csv.writer") @mock.patch.object(GCSHook, "upload") @mock.patch.object(DummySQLToGCSOperator, "query") @mock.patch.object(DummySQLToGCSOperator, "convert_type") ...
TestBaseSQLToGCSOperator
python
falconry__falcon
falcon/routing/converters.py
{ "start": 1036, "end": 2168 }
class ____(metaclass=abc.ABCMeta): """Abstract base class for URI template field converters.""" CONSUME_MULTIPLE_SEGMENTS: ClassVar[bool] = False """When set to ``True`` it indicates that this converter will consume multiple URL path segments. Currently a converter with ``CONSUME_MULTIPLE_SEGMENTS=...
BaseConverter
python
pytorch__pytorch
test/distributed/elastic/metrics/api_test.py
{ "start": 893, "end": 1026 }
class ____(Parent): # need to decorate the implementation not the abstract method! @prof def func(self): pass
Child
python
ansible__ansible
lib/ansible/_internal/_ssh/_ssh_agent.py
{ "start": 4963, "end": 5263 }
class ____(bytes, VariableSized): def to_blob(self) -> bytes: if length := len(self): return uint32(length).to_blob() + self else: return b"" @classmethod def from_blob(cls, blob: memoryview | bytes) -> t.Self: return cls(blob)
binary_string
python
Farama-Foundation__Gymnasium
gymnasium/spaces/multi_binary.py
{ "start": 293, "end": 6565 }
class ____(Space[NDArray[np.int8]]): """An n-shape binary space. Elements of this space are binary arrays of a shape that is fixed during construction. Example: >>> from gymnasium.spaces import MultiBinary >>> observation_space = MultiBinary(5, seed=42) >>> observation_space.sample...
MultiBinary
python
PyCQA__bandit
tests/unit/formatters/test_sarif.py
{ "start": 341, "end": 4983 }
class ____(testtools.TestCase): def setUp(self): super().setUp() conf = config.BanditConfig() self.manager = manager.BanditManager(conf, "file") (tmp_fd, self.tmp_fname) = tempfile.mkstemp() self.context = { "filename": self.tmp_fname, "lineno": 4, ...
SarifFormatterTests
python
bokeh__bokeh
src/bokeh/sphinxext/_internal/bokeh_color.py
{ "start": 1875, "end": 2752 }
class ____(BokehDirective): has_content = False required_arguments = 1 option_spec = { "module": unchanged, } def run(self): color = self.arguments[0] html = COLOR_DETAIL.render(color=getattr(named, color).to_css(), text=color) node = nodes.raw("", html, format="ht...
BokehColorDirective
python
eventlet__eventlet
eventlet/backdoor.py
{ "start": 292, "end": 891 }
class ____: def __init__(self, f): self.f = f def isatty(self): return True def flush(self): pass def write(self, data, *a, **kw): try: self.f.write(data, *a, **kw) self.f.flush() except OSError as e: if get_errno(e) != errno...
FileProxy
python
bokeh__bokeh
src/bokeh/events.py
{ "start": 7422, "end": 7587 }
class ____(ConnectionEvent): ''' Announce when a connection to the client has been reconnected. ''' event_name = 'client_reconnected'
ClientReconnected
python
django__django
django/template/base.py
{ "start": 15841, "end": 17121 }
class ____(Lexer): def _tag_re_split_positions(self): last = 0 for match in tag_re.finditer(self.template_string): start, end = match.span() yield last, start yield start, end last = end yield last, len(self.template_string) # This paralle...
DebugLexer
python
viewflow__viewflow
tests/fsm/test_fsm__basics__zero_target.py
{ "start": 57, "end": 119 }
class ____: ZERO = 0 NEW = 1 REMOVED = 2
ReviewState
python
dagster-io__dagster
python_modules/dagster/dagster/components/resolved/core_models.py
{ "start": 9235, "end": 9721 }
class ____(SharedAssetKwargs): """The attributes of an AssetSpec that can be changed before the AssetsDefinition is created. Typically used by components to allow overriding a default resolution of each AssetSpec. """ key: Optional[ResolvedAssetKey] = None key_prefix: Annotated[ Optiona...
AssetSpecUpdateKwargs
python
numba__numba
numba/tests/test_unsafe_intrinsics.py
{ "start": 5345, "end": 7619 }
class ____(TestCase): def test_zero_count(self): lz = njit(lambda x: leading_zeros(x)) tz = njit(lambda x: trailing_zeros(x)) evens = [2, 42, 126, 128] for T in types.unsigned_domain: self.assertTrue(tz(T(0)) == lz(T(0)) == T.bitwidth) for i in range(T.bitwi...
TestZeroCounts
python
optuna__optuna
optuna/storages/_grpc/auto_generated/api_pb2_grpc.py
{ "start": 7503, "end": 19470 }
class ____(object): """* Optuna storage service defines APIs to interact with the storage. """ def CreateNewStudy(self, request, context): """* Create a new study. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') ...
StorageServiceServicer
python
great-expectations__great_expectations
great_expectations/datasource/fluent/fabric.py
{ "start": 1993, "end": 7416 }
class ____(DataAsset): """Microsoft PowerBI Asset base class.""" _reader_method: ClassVar[FabricReaderMethods] _EXCLUDE_FROM_READER_OPTIONS: ClassVar[Set[str]] = { "batch_definitions", "batch_metadata", "name", "order_by", "type", "id", } @override ...
_PowerBIAsset
python
getsentry__sentry
src/sentry/utils/sdk_crashes/path_replacer.py
{ "start": 273, "end": 499 }
class ____(PathReplacer): def __init__( self, path: str, ): self.path = path def replace_path(self, path_field: str, path_value: str) -> str | None: return self.path
FixedPathReplacer
python
pandas-dev__pandas
pandas/tests/tseries/offsets/test_fiscal.py
{ "start": 1165, "end": 5001 }
class ____: offset_lom_sat_aug = makeFY5253LastOfMonth(1, startingMonth=8, weekday=WeekDay.SAT) offset_lom_sat_sep = makeFY5253LastOfMonth(1, startingMonth=9, weekday=WeekDay.SAT) on_offset_cases = [ # From Wikipedia (see: # https://en.wikipedia.org/wiki/4%E2%80%934%E2%80%935_calendar#Last_...
TestFY5253LastOfMonth
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/client.py
{ "start": 364, "end": 779 }
class ____(SuperQObject, HBChannel): # A longer timeout than the base class time_to_dead = 3.0 # Emitted when the kernel has died. kernel_died = QtCore.Signal(object) def call_handlers(self, since_last_heartbeat): """ Reimplemented to emit signals instead of making callbacks. """ ...
QtHBChannel
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta_not_found_error.py
{ "start": 193, "end": 284 }
class ____(BaseModel): message: str type: Literal["not_found_error"]
BetaNotFoundError
python
readthedocs__readthedocs.org
readthedocs/proxito/middleware.py
{ "start": 1508, "end": 16052 }
class ____(MiddlewareMixin): """The actual middleware we'll be using in prod.""" # None of these need the proxito request middleware (response is needed). # The analytics API isn't listed because it depends on the unresolver, # which depends on the proxito middleware. skip_views = ( "health...
ProxitoMiddleware
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/subscription.py
{ "start": 481, "end": 2152 }
class ____(graphene.ObjectType): """The root for all subscriptions to retrieve real-time data from the Dagster instance.""" class Meta: name = "Subscription" pipelineRunLogs = graphene.Field( graphene.NonNull(GraphenePipelineRunLogsSubscriptionPayload), runId=graphene.Argument(grap...
GrapheneSubscription
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/special_math_test.py
{ "start": 12670, "end": 12735 }
class ____(NdtrGradientTest): _use_log = True
LogNdtrGradientTest
python
PyCQA__pylint
tests/functional/m/member/member_checks.py
{ "start": 4330, "end": 4421 }
class ____(type): def __getattr__(cls, attr): return attr
MetaWithDynamicGetattr
python
sqlalchemy__sqlalchemy
test/sql/test_metadata.py
{ "start": 97338, "end": 102012 }
class ____(fixtures.TestBase, AssertsCompiledSQL): def test_default_schema_metadata_fk(self): m = MetaData(schema="foo") t1 = Table("t1", m, Column("x", Integer)) t2 = Table("t2", m, Column("x", Integer, ForeignKey("t1.x"))) assert t2.c.x.references(t1.c.x) def test_ad_hoc_schem...
SchemaTest
python
Lightning-AI__lightning
src/lightning/pytorch/trainer/connectors/data_connector.py
{ "start": 2017, "end": 12317 }
class ____: def __init__(self, trainer: "pl.Trainer"): self.trainer = trainer self._datahook_selector: Optional[_DataHookSelector] = None def on_trainer_init( self, val_check_interval: Optional[Union[int, float, str, timedelta, dict]], reload_dataloaders_every_n_epochs: ...
_DataConnector
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_shared.py
{ "start": 967, "end": 1212 }
class ____(str, Enum): """SSL mode for Azure Database for PostgreSQL connections.""" disable = "disable" allow = "allow" prefer = "prefer" require = "require" verify_ca = "verify-ca" verify_full = "verify-full"
SSLMode
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/matchClass1.py
{ "start": 9496, "end": 9527 }
class ____(Parent[T]): ...
Child1
python
getsentry__sentry
src/sentry/integrations/messaging/linkage.py
{ "start": 12880, "end": 14972 }
class ____(LinkageView, ABC): _ALLOWED_ROLES = frozenset(["admin", "manager", "owner"]) @classmethod def is_valid_role(cls, org_member: OrganizationMember) -> bool: return org_member.role in cls._ALLOWED_ROLES @method_decorator(never_cache) def handle(self, request: HttpRequest, signed_par...
TeamLinkageView