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
kamyu104__LeetCode-Solutions
Python/first-unique-number.py
{ "start": 106, "end": 810 }
class ____(object): def __init__(self, nums): """ :type nums: List[int] """ self.__q = collections.OrderedDict() self.__dup = set() for num in nums: self.add(num) def showFirstUnique(self): """ :rtype: int """ if self....
FirstUnique
python
huggingface__transformers
src/transformers/models/canine/modeling_canine.py
{ "start": 9907, "end": 12236 }
class ____(nn.Module): """ Project representations from hidden_size*2 back to hidden_size across a window of w = config.upsampling_kernel_size characters. """ def __init__(self, config): super().__init__() self.config = config self.conv = nn.Conv1d( in_channels=c...
ConvProjection
python
weaviate__weaviate-python-client
weaviate/collections/batch/base.py
{ "start": 32005, "end": 32923 }
class ____: def __init__(self, send: threading.Thread, recv: threading.Thread): self.send = send self.recv = recv self.__started_recv = False self.__started_send = False def start_recv(self) -> None: if not self.__started_recv: self.recv.start() s...
_BgThreads
python
django__django
tests/middleware_exceptions/tests.py
{ "start": 6347, "end": 6673 }
class ____: def __init__(self, get_response): raise MiddlewareNotUsed("spam eggs") def process_request(self, request): pass @override_settings( DEBUG=True, ROOT_URLCONF="middleware_exceptions.urls", MIDDLEWARE=["django.middleware.common.CommonMiddleware"], )
MyMiddlewareWithExceptionMessage
python
TheAlgorithms__Python
data_structures/binary_tree/segment_tree.py
{ "start": 14, "end": 3276 }
class ____: def __init__(self, a): self.A = a self.N = len(self.A) self.st = [0] * ( 4 * self.N ) # approximate the overall size of segment tree with array N if self.N: self.build(1, 0, self.N - 1) def left(self, idx): """ Returns...
SegmentTree
python
ray-project__ray
python/ray/util/serialization.py
{ "start": 1247, "end": 2009 }
class ____: # NOTE(simon): Used for registering custom serializers. We cannot directly # use the SerializationContext because it requires Ray workers. Please # make sure to keep the API consistent. def _register_cloudpickle_reducer(self, cls, reducer): pickle.CloudPickler.dispatch[cls] = reduce...
StandaloneSerializationContext
python
numba__llvmlite
llvmlite/binding/value.py
{ "start": 1685, "end": 11701 }
class ____(ffi.ObjectRef): """A weak reference to a LLVM value. """ def __init__(self, ptr, kind, parents): self._kind = kind self._parents = parents ffi.ObjectRef.__init__(self, ptr) def __str__(self): with ffi.OutputString() as outstr: ffi.lib.LLVMPY_Print...
ValueRef
python
pypa__pip
src/pip/_internal/index/collector.py
{ "start": 6005, "end": 6345 }
class ____: def __init__(self, page: IndexContent) -> None: assert page.cache_link_parsing self.page = page def __eq__(self, other: object) -> bool: return isinstance(other, type(self)) and self.page.url == other.page.url def __hash__(self) -> int: return hash(self.page.url...
CacheablePageContent
python
pytorch__pytorch
torch/_dynamo/testing.py
{ "start": 8982, "end": 9277 }
class ____: def __init__(self) -> None: self.graphs: list[torch.fx.GraphModule] = [] def __call__( self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] ) -> Callable[..., Any]: self.graphs.append(gm) return gm.forward
EagerAndRecordGraphs
python
wandb__wandb
wandb/vendor/pygments/lexers/configs.py
{ "start": 1612, "end": 3033 }
class ____(RegexLexer): """ Lexer for `Windows Registry <http://en.wikipedia.org/wiki/Windows_Registry#.REG_files>`_ files produced by regedit. .. versionadded:: 1.6 """ name = 'reg' aliases = ['registry'] filenames = ['*.reg'] mimetypes = ['text/x-windows-registry'] token...
RegeditLexer
python
astropy__astropy
astropy/coordinates/angles/errors.py
{ "start": 527, "end": 642 }
class ____(RangeError): """ Raised when an angle is outside of its user-specified bounds. """
BoundsError
python
PrefectHQ__prefect
src/prefect/concurrency/_asyncio.py
{ "start": 948, "end": 1079 }
class ____(Exception): """Raised when an unhandlable occurs while acquiring concurrency slots."""
ConcurrencySlotAcquisitionError
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataproc_metastore.py
{ "start": 26074, "end": 31999 }
class ____(GoogleCloudBaseOperator): """ Export metadata from a service. :param destination_gcs_folder: A Cloud Storage URI of a folder, in the format ``gs://<bucket_name>/<path_inside_bucket>``. A sub-folder ``<export_folder>`` containing exported files will be created below it. ...
DataprocMetastoreExportMetadataOperator
python
apache__airflow
providers/google/src/airflow/providers/google/common/hooks/base_google.py
{ "start": 29048, "end": 32008 }
class ____(Token): """ A token implementation which makes Google credentials objects accessible to [gcloud-aio](https://talkiq.github.io/gcloud-aio/) clients. This class allows us to create token instances from credentials objects and thus supports a variety of use cases for Google credentials in Airfl...
_CredentialsToken
python
pytest-dev__pytest
testing/test_debugging.py
{ "start": 2672, "end": 32744 }
class ____: @pytest.fixture def pdblist(self, request): monkeypatch = request.getfixturevalue("monkeypatch") pdblist = [] def mypdb(*args): pdblist.append(args) plugin = request.config.pluginmanager.getplugin("debugging") monkeypatch.setattr(plugin, "post_mo...
TestPDB
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/scrapfly_web/base.py
{ "start": 307, "end": 2898 }
class ____(BasePydanticReader): """ Turn a url to llm accessible markdown with `Scrapfly.io`. Args: api_key: The Scrapfly API key. scrape_config: The Scrapfly ScrapeConfig object. ignore_scrape_failures: Whether to continue on failures. urls: List of urls to scrape. scrape_format: Scrap...
ScrapflyReader
python
vyperlang__vyper
vyper/builtins/functions.py
{ "start": 73262, "end": 73592 }
class ____(BuiltinFunctionT): _id = "sqrt" _inputs = [("d", DecimalT())] _return_type = DecimalT() def fetch_call_return(self, node): message = "The `sqrt` builtin was removed. Instead import module " message += "`math` and use `math.sqrt()`" raise UnimplementedException(message...
Sqrt
python
joke2k__faker
tests/providers/test_bank.py
{ "start": 13651, "end": 14117 }
class ____: """Test th_TH bank provider""" def test_bban(self, faker, num_samples): for _ in range(num_samples): assert re.fullmatch(r"\d{10}", faker.bban()) def test_iban(self, faker, num_samples): for _ in range(num_samples): iban = faker.iban() assert...
TestThTh
python
PrefectHQ__prefect
tests/server/utilities/test_text_search_parser.py
{ "start": 4023, "end": 4941 }
class ____: """Test required/AND syntax with + prefix (future feature)""" def test_plus_prefix_single_term(self): result = parse_text_search_query("+required") assert result == TextSearchQuery(include=[], exclude=[], required=["required"]) def test_plus_only(self): result = parse_t...
TestRequiredTerms
python
huggingface__transformers
tests/models/bert/test_tokenization_bert.py
{ "start": 885, "end": 2733 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = ["google-bert/bert-base-uncased"] tokenizer_class = BertTokenizer integration_expected_tokens = ['[UNK]', 'is', 'a', 'test', '[UNK]', '[UNK]', 'was', 'born', 'in', '92', '##00', '##0', ',', 'and', 'this', 'is', '[UNK]', '.', '生', '[U...
BertTokenizationTest
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_sagemaker_endpoint.py
{ "start": 1662, "end": 3219 }
class ____: @mock.patch.object(SageMakerHook, "get_conn") @mock.patch.object(SageMakerHook, "describe_endpoint") def test_sensor_with_failure(self, mock_describe, mock_get_conn): mock_describe.side_effect = [DESCRIBE_ENDPOINT_FAILED_RESPONSE] sensor = SageMakerEndpointSensor( tas...
TestSageMakerEndpointSensor
python
doocs__leetcode
solution/0100-0199/0156.Binary Tree Upside Down/Solution.py
{ "start": 192, "end": 560 }
class ____: def upsideDownBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root is None or root.left is None: return root new_root = self.upsideDownBinaryTree(root.left) root.left.right = root root.left.left = root.right root.left = None ...
Solution
python
walkccc__LeetCode
solutions/1289. Minimum Falling Path Sum II/1289.py
{ "start": 0, "end": 414 }
class ____: def minFallingPathSum(self, grid: list[list[int]]) -> int: n = len(grid) for i in range(1, n): (firstMinNum, firstMinIndex), (secondMinNum, _) = sorted( {(a, i) for i, a in enumerate(grid[i - 1])})[:2] for j in range(n): if j == firstMinIndex: grid[i][j] +=...
Solution
python
tensorflow__tensorflow
tensorflow/python/keras/utils/generic_utils.py
{ "start": 40600, "end": 41603 }
class ____(python_types.ModuleType): """Lazily import a module, mainly to avoid pulling in large dependencies.""" def __init__(self, local_name, parent_module_globals, name): self._local_name = local_name self._parent_module_globals = parent_module_globals super(LazyLoader, self).__init__(name) def ...
LazyLoader
python
getsentry__sentry
src/sentry/middleware/reporting_endpoint.py
{ "start": 162, "end": 1017 }
class ____: """ Add ReportingEndpoint header for Sentry staff users only. """ def __init__(self, get_response: Callable[[HttpRequest], HttpResponseBase]): self.get_response = get_response def __call__(self, request: HttpRequest) -> HttpResponseBase: response = self.get_response(req...
ReportingEndpointMiddleware
python
getsentry__sentry-python
sentry_sdk/tracing.py
{ "start": 6389, "end": 7267 }
class ____: """Limits the number of spans recorded in a transaction.""" __slots__ = ("maxlen", "spans", "dropped_spans") def __init__(self, maxlen): # type: (int) -> None # FIXME: this is `maxlen - 1` only to preserve historical behavior # enforced by tests. # Either this s...
_SpanRecorder
python
ray-project__ray
rllib/execution/minibatch_buffer.py
{ "start": 111, "end": 1952 }
class ____: """Ring buffer of recent data batches for minibatch SGD. This is for use with AsyncSamplesOptimizer. """ def __init__( self, inqueue: queue.Queue, size: int, timeout: float, num_passes: int, init_num_passes: int = 1, ): """Initial...
MinibatchBuffer
python
scikit-learn__scikit-learn
asv_benchmarks/benchmarks/model_selection.py
{ "start": 1190, "end": 2371 }
class ____(Predictor, Estimator, Benchmark): """ Benchmarks for GridSearch. """ timeout = 20000 param_names = ["n_jobs"] params = (Benchmark.n_jobs_vals,) def setup_cache(self): super().setup_cache() def make_data(self, params): data = _synth_classification_dataset(n_...
GridSearchBenchmark
python
cloudpipe__cloudpickle
tests/cloudpickle_test.py
{ "start": 112176, "end": 115432 }
class ____(CloudPickleTest): protocol = 2 def test_lookup_module_and_qualname_dynamic_typevar(): T = typing.TypeVar("T") module_and_name = _lookup_module_and_qualname(T, name=T.__name__) assert module_and_name is None def test_lookup_module_and_qualname_importable_typevar(): _cloudpickle_testpkg...
Protocol2CloudPickleTest
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py
{ "start": 56660, "end": 57488 }
class ____(BaseModel): class Config: extra = Extra.forbid type: Literal["DeclarativeSource"] check: CheckStream streams: List[DeclarativeStream] version: str = Field( ..., description="The version of the Airbyte CDK used to build and test the source.", ) schemas: Opt...
DeclarativeSource
python
kamyu104__LeetCode-Solutions
Python/count-nodes-with-the-highest-score.py
{ "start": 1240, "end": 1985 }
class ____(object): def countHighestScoreNodes(self, parents): """ :type parents: List[int] :rtype: int """ def dfs(adj, i, result): cnts = [dfs(adj, child, result) for child in adj[i]] total = sum(cnts)+1 score = max((len(adj)-total), 1)*r...
Solution2
python
matplotlib__matplotlib
lib/matplotlib/projections/polar.py
{ "start": 5229, "end": 6970 }
class ____(mtransforms.Affine2DBase): r""" The affine part of the polar projection. Scales the output so that maximum radius rests on the edge of the Axes circle and the origin is mapped to (0.5, 0.5). The transform applied is the same to x and y components and given by: .. math:: x_{...
PolarAffine
python
ray-project__ray
release/llm_tests/benchmark/load_test.py
{ "start": 9824, "end": 10131 }
class ____(OpenAIProvider): def format_payload(self, prompt, max_tokens, images): data = super().format_payload(prompt, max_tokens, images) data["min_tokens"] = max_tokens data["prompt_cache_max_len"] = self.parsed_options.prompt_cache_max_len return data
FireworksProvider
python
pypa__setuptools
setuptools/tests/config/test_apply_pyprojecttoml.py
{ "start": 12274, "end": 17660 }
class ____: def base_pyproject( self, tmp_path, additional_text="", license_toml='license = {file = "LICENSE.txt"}\n', ): text = PEP639_LICENSE_EXPRESSION # Sanity-check assert 'license = "mit or apache-2.0"' in text assert 'license-files' not in ...
TestLicenseFiles
python
sqlalchemy__sqlalchemy
test/sql/test_resultset.py
{ "start": 75459, "end": 96452 }
class ____(fixtures.TablesTest): run_inserts = "once" run_deletes = None __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): Table( "keyed1", metadata, Column("a", CHAR(2), key="b"), Column("c", CHAR(2), key="q"), ...
KeyTargetingTest
python
ray-project__ray
python/ray/data/_internal/execution/operators/limit_operator.py
{ "start": 537, "end": 5337 }
class ____(OneToOneOperator): """Physical operator for limit.""" def __init__( self, limit: int, input_op: PhysicalOperator, data_context: DataContext, ): self._limit = limit self._consumed_rows = 0 self._buffer: Deque[RefBundle] = deque() sel...
LimitOperator
python
ray-project__ray
release/ray_release/cluster_manager/full.py
{ "start": 389, "end": 4833 }
class ____(MinimalClusterManager): """Full manager. Builds app config and compute template and starts/terminated session using SDK. """ def start_cluster(self, timeout: float = 600.0): logger.info(f"Creating cluster {self.cluster_name}") logger.info(f"Autosuspend time: {self.autosu...
FullClusterManager
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py
{ "start": 7212, "end": 7777 }
class ____(graphene.Mutation): """Deletes a run from storage.""" Output = graphene.NonNull(GrapheneDeletePipelineRunResult) class Arguments: runId = graphene.NonNull(graphene.String) class Meta: name = "DeleteRunMutation" @capture_error @require_permission_check(Permissions.D...
GrapheneDeleteRunMutation
python
walkccc__LeetCode
solutions/1879. Minimum XOR Sum of Two Arrays/1879.py
{ "start": 0, "end": 359 }
class ____: def minimumXORSum(self, nums1: list[int], nums2: list[int]) -> int: @functools.lru_cache(None) def dp(mask: int) -> int: i = mask.bit_count() if i == len(nums1): return 0 return min((nums1[i] ^ nums2[j]) + dp(mask | 1 << j) for j in range(len(nums2)) if n...
Solution
python
PyCQA__flake8
src/flake8/formatting/base.py
{ "start": 286, "end": 7357 }
class ____: """Class defining the formatter interface. .. attribute:: options The options parsed from both configuration files and the command-line. .. attribute:: filename If specified by the user, the path to store the results of the run. .. attribute:: output_fd Initiali...
BaseFormatter
python
pytorch__pytorch
torch/utils/data/datapipes/dataframe/datapipes.py
{ "start": 3737, "end": 4626 }
class ____(DFIterDataPipe): def __init__(self, source_datapipe, dataframe_size=10, columns=None) -> None: self.source_datapipe = source_datapipe self.columns = columns self.dataframe_size = dataframe_size def _as_list(self, item): try: return list(item) excep...
ExampleAggregateAsDataFrames
python
falconry__falcon
tests/asgi/test_response_media_asgi.py
{ "start": 6132, "end": 8173 }
class ____: def test_text(self): async def test(resp): resp.text = 'body' resp.data = b'data' resp.media = ['media'] assert await resp.render_body() == b'body' run_test(test) def test_data(self): async def test(resp): resp.da...
TestRenderBodyPrecedence
python
RobertCraigie__pyright-python
src/pyright/errors.py
{ "start": 258, "end": 499 }
class ____(NodeError): def __init__(self, target: Target, path: Path) -> None: super().__init__(f'Expected {target} binary to exist at {path} but was not found.') self.path = path self.target = target
BinaryNotFound
python
numba__numba
numba/core/types/misc.py
{ "start": 4655, "end": 5107 }
class ____(Type): """ Similar to EphemeralPointer, but pointing to an array of elements, rather than a single one. The array size must be known at compile-time. """ def __init__(self, dtype, count): self.dtype = dtype self.count = count name = "*%s[%d]" % (dtype, count) ...
EphemeralArray
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/super_without_brackets.py
{ "start": 431, "end": 698 }
class ____(Animal): @staticmethod def speak(): super = "super" original_speak = super.speak() # OK return f"{original_speak} But as a dog, it barks!" def super_without_class() -> None: super.blah() # OK super.blah() # OK
FineDog
python
pyqtgraph__pyqtgraph
pyqtgraph/opengl/items/GLScatterPlotItem.py
{ "start": 459, "end": 11539 }
class ____(GLGraphicsItem): """Draws points at a list of 3D positions.""" _shaderProgram = None def __init__(self, parentItem=None, **kwds): super().__init__() glopts = kwds.pop('glOptions', 'additive') self.setGLOptions(glopts) self.pos = None self.size = 10 ...
GLScatterPlotItem
python
numpy__numpy
numpy/_core/tests/test_finfo.py
{ "start": 113, "end": 2488 }
class ____: """Minimal class to simulate machine arithmetic parameters.""" def __init__(self, dtype, machep, negep, minexp, maxexp, nmant, iexp): self.dtype = dtype self.machep = machep self.negep = negep self.minexp = minexp self.maxexp = maxexp self.nmant = nman...
MachArLike
python
huggingface__transformers
src/transformers/models/perceiver/modeling_perceiver.py
{ "start": 13279, "end": 15308 }
class ____(nn.Module): def __init__( self, config, is_cross_attention=False, qk_channels=None, v_channels=None, num_heads=1, q_dim=None, kv_dim=None, widening_factor=4, use_query_residual=True, ): super().__init__() ...
PerceiverLayer
python
great-expectations__great_expectations
great_expectations/datasource/fluent/sql_datasource.py
{ "start": 13171, "end": 14356 }
class ____(FluentBaseModel): column_names: List[str] sort_ascending: bool = True method_name: Literal["partition_on_multi_column_values"] = "partition_on_multi_column_values" @property def columns(self): return self.column_names @property def param_names(self) -> List[str]: ...
SqlPartitionerMultiColumnValue
python
getsentry__sentry
tests/sentry/core/endpoints/test_organization_member_index.py
{ "start": 24452, "end": 34581 }
class ____(OrganizationMemberListTestBase, HybridCloudTestMixin): method = "post" def invite_all_helper(self, role): invite_roles = ["owner", "manager", "member"] user = self.create_user("user@localhost") member = self.create_member(user=user, organization=self.organization, role=role)...
OrganizationMemberPermissionRoleTest
python
kubernetes-client__python
kubernetes/client/models/v1_pod_status.py
{ "start": 383, "end": 29201 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1PodStatus
python
huggingface__transformers
src/transformers/models/oneformer/modeling_oneformer.py
{ "start": 96795, "end": 102665 }
class ____(nn.Module): """ Transformer decoder """ def __init__(self, in_channels: int, config: OneFormerConfig): super().__init__() self.config = config self.dropout = config.dropout self.num_heads = config.num_attention_heads self.is_training = config.is_train...
OneFormerTransformerDecoder
python
getsentry__sentry
src/sentry/models/dashboard_widget.py
{ "start": 4496, "end": 5021 }
class ____(TypesClass): LINE_CHART = 0 AREA_CHART = 1 STACKED_AREA_CHART = 2 BAR_CHART = 3 TABLE = 4 BIG_NUMBER = 6 TOP_N = 7 DETAILS = 8 TYPES = [ (LINE_CHART, "line"), (AREA_CHART, "area"), (STACKED_AREA_CHART, "stacked_area"), (BAR_CHART, "bar"), ...
DashboardWidgetDisplayTypes
python
aimacode__aima-python
search.py
{ "start": 43428, "end": 44027 }
class ____(GraphProblem): """ A version of GraphProblem where an action can lead to nondeterministic output i.e. multiple possible states. Define the graph as dict(A = dict(Action = [[<Result 1>, <Result 2>, ...], <cost>], ...), ...) A the dictionary format is different, make sure the graph is crea...
GraphProblemStochastic
python
django__django
tests/serializers/models/data.py
{ "start": 7456, "end": 7571 }
class ____(models.Model): data = models.IntegerField() def __len__(self): return self.data
LengthModel
python
keras-team__keras
keras/src/layers/rnn/conv_lstm2d_test.py
{ "start": 160, "end": 3194 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_basics(self): channels_last = backend.config.image_data_format() == "channels_last" self.run_layer_test( layers.ConvLSTM2D, init_kwargs={"filters": 5, "kernel_size": 3, "padding": "same"}, ...
ConvLSTM2DTest
python
python__mypy
mypyc/ir/ops.py
{ "start": 42294, "end": 43942 }
class ____(RegisterOp): """Binary arithmetic or bitwise op on integer operands (e.g., r1 = r2 + r3). These ops are low-level and are similar to the corresponding C operations. The left and right values must have low-level integer types with compatible representations. Fixed-width integers, short_i...
IntOp
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 1743, "end": 1899 }
class ____(str, Enum): """ Bulk Action to be taken if the entity does not exist. """ FAIL = "fail" SKIP = "skip"
BulkActionNotOnExistence
python
pytorch__pytorch
test/torch_np/test_basic.py
{ "start": 10874, "end": 11132 }
class ____(TestCase): """Smoke_test (sequence of scalars) -> (array)""" @parametrize("func, args", funcs_and_args) def test_argstoarray_simple(self, func, args): a = func(*args) assert isinstance(a, w.ndarray)
TestPythonArgsToArray
python
kamyu104__LeetCode-Solutions
Python/clone-graph.py
{ "start": 29, "end": 143 }
class ____(object): def __init__(self, x): self.label = x self.neighbors = []
UndirectedGraphNode
python
dagster-io__dagster
python_modules/libraries/dagster-docker/dagster_docker/pipes.py
{ "start": 1919, "end": 8242 }
class ____(PipesClient, TreatAsResourceParam): """A pipes client that runs external processes in docker containers. By default context is injected via environment variables and messages are parsed out of the log stream, with other logs forwarded to stdout of the orchestration process. Args: en...
PipesDockerClient
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/v1_compat_tests/session_ops_test.py
{ "start": 1193, "end": 11100 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testHandleBasic(self): with self.cached_session() as sess: # Return a handle. a = constant_op.constant(10) b = constant_op.constant(5) c = math_ops.multiply(a, b) h = session_ops.get_session_handle(c) h = self.evalu...
SessionOpsTest
python
pypa__pip
src/pip/_vendor/rich/traceback.py
{ "start": 7948, "end": 8278 }
class ____: exc_type: str exc_value: str syntax_error: Optional[_SyntaxError] = None is_cause: bool = False frames: List[Frame] = field(default_factory=list) notes: List[str] = field(default_factory=list) is_group: bool = False exceptions: List["Trace"] = field(default_factory=list) @d...
Stack
python
dask__dask
dask/dataframe/dask_expr/_categorical.py
{ "start": 4716, "end": 4905 }
class ____(Elemwise): _parameters = ["frame"] operation = M.copy @functools.cached_property def _meta(self): return clear_known_categories(self.frame._meta)
AsUnknown
python
run-llama__llama_index
llama-index-core/llama_index/core/data_structs/data_structs.py
{ "start": 3483, "end": 4433 }
class ____(IndexStruct): """A table of keywords mapping keywords to text chunks.""" table: Dict[str, Set[str]] = field(default_factory=dict) def add_node(self, keywords: List[str], node: BaseNode) -> None: """Add text to table.""" for keyword in keywords: if keyword not in self...
KeywordTable
python
pytorch__pytorch
torch/optim/swa_utils.py
{ "start": 15467, "end": 21885 }
class ____(LRScheduler): r"""Anneals the learning rate in each parameter group to a fixed value. This learning rate scheduler is meant to be used with Stochastic Weight Averaging (SWA) method (see `torch.optim.swa_utils.AveragedModel`). Args: optimizer (torch.optim.Optimizer): wrapped optimize...
SWALR
python
huggingface__transformers
examples/modular-transformers/modeling_super.py
{ "start": 3737, "end": 7742 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) ...
SuperMLP
python
tiangolo__fastapi
tests/test_response_class_no_mediatype.py
{ "start": 328, "end": 3415 }
class ____(BaseModel): errors: typing.List[Error] @app.get( "/a", response_class=Response, responses={500: {"description": "Error", "model": JsonApiError}}, ) async def a(): pass # pragma: no cover @app.get("/b", responses={500: {"description": "Error", "model": Error}}) async def b(): pass...
JsonApiError
python
joke2k__faker
faker/providers/address/pl_PL/__init__.py
{ "start": 45, "end": 14745 }
class ____(AddressProvider): cities = ( "Warszawa", "Kraków", "Łódź", "Wrocław", "Poznań", "Gdańsk", "Szczecin", "Bydgoszcz", "Lublin", "Katowice", "Białystok", "Gdynia", "Częstochowa", "Radom", "...
Provider
python
automl__auto-sklearn
test/test_pipeline/components/data_preprocessing/test_variance_threshold.py
{ "start": 251, "end": 1407 }
class ____(PreprocessingTestCase): def test_default_configuration(self): transformations = [] for i in range(2): transformation, original = _test_preprocessing(VarianceThreshold) self.assertEqual(transformation.shape, original.shape) self.assertTrue((transformatio...
VarianceThresholdTest
python
doocs__leetcode
solution/2000-2099/2031.Count Subarrays With More Ones Than Zeros/Solution.py
{ "start": 390, "end": 806 }
class ____: def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: n = len(nums) base = n + 1 tree = BinaryIndexedTree(n + base) tree.update(base, 1) mod = 10**9 + 7 ans = s = 0 for x in nums: s += x or -1 ans += tree.query(s...
Solution
python
keras-team__keras
keras/src/layers/convolutional/base_depthwise_conv.py
{ "start": 571, "end": 11608 }
class ____(Layer): """Abstract N-D depthwise convolution layer. Depthwise convolution is a type of convolution in which each input channel is convolved with a different kernel (called a depthwise kernel). You can understand depthwise convolution as the first step in a depthwise separable convolutio...
BaseDepthwiseConv
python
huggingface__transformers
src/transformers/models/siglip2/modular_siglip2.py
{ "start": 1459, "end": 4866 }
class ____(SiglipVisionConfig): r""" This is the configuration class to store the configuration of a [`Siglip2VisionModel`]. It is used to instantiate a Siglip2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yiel...
Siglip2VisionConfig
python
PyCQA__pylint
tests/functional/i/init_not_called.py
{ "start": 1254, "end": 1583 }
class ____(Parent): @overload def __init__(self, num: int): ... @overload def __init__(self, num: float): ... def __init__(self, num): super().__init__(round(num)) # https://github.com/pylint-dev/pylint/issues/7742 # Crash when parent class has a class attribute named `__...
Child
python
django__django
tests/migrations/test_migrations_conflict/0002_second.py
{ "start": 43, "end": 648 }
class ____(migrations.Migration): dependencies = [("migrations", "0001_initial")] operations = [ migrations.DeleteModel("Tribble"), migrations.RemoveField("Author", "silly_field"), migrations.AddField("Author", "rating", models.IntegerField(default=0)), migrations.CreateModel( ...
Migration
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 296292, "end": 298666 }
class ____(StatNode): # print statement # # arg_tuple TupleNode # stream ExprNode or None (stdout) # append_newline boolean child_attrs = ["arg_tuple", "stream"] def analyse_expressions(self, env): if self.stream: stream = self.stream.analyse_e...
PrintStatNode
python
tensorflow__tensorflow
tensorflow/python/client/session.py
{ "start": 11808, "end": 14695 }
class ____(_FetchMapper): """Fetch mapper for singleton tensors and ops.""" def __init__(self, fetches, contraction_fn): """Creates an _ElementFetchMapper. This is the fetch mapper used for leaves in the fetch struct. Because of the expansions mechanism, a leaf can actually fetch more than one tensor...
_ElementFetchMapper
python
dagster-io__dagster
python_modules/dagster/dagster_tests/logging_tests/test_logging.py
{ "start": 6866, "end": 21928 }
class ____(logging.Filter): def __init__(self, filter_level): super().__init__() self.filter_level = filter_level def filter(self, record): record.msg = f"{record.msg} default logger is {DAGSTER_DEFAULT_LOGGER}" return record.levelno == self.filter_level def test_capture_handl...
CustomLevelFilter
python
has2k1__plotnine
plotnine/_mpl/layout_manager/_layout_items.py
{ "start": 1678, "end": 4958 }
class ____: """ Calculate space taken up by an artist """ # fig: Figure # renderer: RendererBase plot: ggplot def __post_init__(self): self.figure = self.plot.figure self.renderer = cast("RendererBase", self.plot.figure._get_renderer()) # pyright: ignore def bbox(self...
Calc
python
django__django
tests/file_storage/test_inmemory_storage.py
{ "start": 5755, "end": 9446 }
class ____(unittest.TestCase): def setUp(self): self.storage = InMemoryStorage() def test_file_modified_time(self): """ File modified time should change after file changing """ self.storage.save("file.txt", ContentFile("test")) modified_time = self.storage.get_mo...
MemoryStorageTimesTests
python
pytorch__pytorch
torch/ao/pruning/_experimental/pruner/lstm_saliency_pruner.py
{ "start": 184, "end": 2197 }
class ____(BaseStructuredSparsifier): """ Prune packed LSTM weights based on saliency. For each layer {k} inside a LSTM, we have two packed weight matrices - weight_ih_l{k} - weight_hh_l{k} These tensors pack the weights for the 4 linear layers together for efficiency. [W_ii | W_if | W_ig ...
LSTMSaliencyPruner
python
django__django
tests/cache/tests.py
{ "start": 1929, "end": 2817 }
class ____: def __getstate__(self): raise pickle.PickleError() def empty_response(request): return HttpResponse() KEY_ERRORS_WITH_MEMCACHED_MSG = ( "Cache key contains characters that will cause errors if used with memcached: %r" ) def retry(retries=3, delay=1): def decorator(func): ...
Unpicklable
python
kubernetes-client__python
kubernetes/client/api/openid_api.py
{ "start": 543, "end": 5464 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client ...
OpenidApi
python
gevent__gevent
src/greentest/3.10/test_httplib.py
{ "start": 3797, "end": 14126 }
class ____(TestCase): def test_auto_headers(self): # Some headers are added automatically, but should not be added by # .request() if they are explicitly set. class HeaderCountingBuffer(list): def __init__(self): self.count = {} def append(self, item)...
HeaderTests
python
pypa__pip
src/pip/_vendor/rich/_ratio.py
{ "start": 115, "end": 5325 }
class ____(Protocol): """Any object that defines an edge (such as Layout).""" size: Optional[int] = None ratio: int = 1 minimum_size: int = 1 def ratio_resolve(total: int, edges: Sequence[Edge]) -> List[int]: """Divide total space to satisfy size, ratio, and minimum_size, constraints. The re...
Edge
python
tiangolo__fastapi
docs_src/separate_openapi_schemas/tutorial002.py
{ "start": 93, "end": 524 }
class ____(BaseModel): name: str description: Union[str, None] = None app = FastAPI(separate_input_output_schemas=False) @app.post("/items/") def create_item(item: Item): return item @app.get("/items/") def read_items() -> List[Item]: return [ Item( name="Portal Gun", ...
Item
python
PrefectHQ__prefect
src/prefect/concurrency/context.py
{ "start": 229, "end": 922 }
class ____(ContextModel): __var__: ClassVar[ContextVar[Self]] = ContextVar("concurrency") # Track the leases that have been acquired but were not able to be released # due to cancellation or some other error. These leases are revoked when # the context manager exits. cleanup_lease_ids: list[UUID] =...
ConcurrencyContext
python
huggingface__transformers
src/transformers/data/data_collator.py
{ "start": 10109, "end": 17931 }
class ____(DataCollatorMixin): """ Data collator that will dynamically pad the inputs received, as well as the labels. Args: tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]): The tokenizer used for encoding the data. padding (`bool`, `str` or [`~utils.PaddingSt...
DataCollatorForTokenClassification
python
pytorch__pytorch
test/dynamo/test_subclasses.py
{ "start": 102490, "end": 103278 }
class ____(torch.nn.Module): def forward(self, primals_1: "f32[3, 4]", primals_2: "f32[3, 4]", primals_3: "Sym(3)", primals_4: "Sym(4)", primals_5: "Sym(3)", primals_6: "Sym(4)"): clone: "f32[3, 4]" = torch.ops.aten.clone.default(primals_1); primals_1 = None clone_1: "f32[3, 4]" = torch.ops.aten.cl...
GraphModule
python
pytorch__pytorch
test/torch_np/numpy_tests/linalg/test_linalg.py
{ "start": 11613, "end": 11891 }
class ____(LinalgTestCase): def test_herm_cases(self): self.check_cases(require={"hermitian"}, exclude={"generalized", "size-0"}) def test_empty_herm_cases(self): self.check_cases(require={"hermitian", "size-0"}, exclude={"generalized"})
HermitianTestCase
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0147_addons_filetreediff_enabled_by_default.py
{ "start": 349, "end": 936 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0146_addons_filetreediff_ignored_files"), ] operations = [ migrations.RunPython(migrate), migrations.AlterField( model_name="addonsconfig", name="filetreediff_ena...
Migration
python
pytorch__pytorch
torch/testing/_internal/distributed/nn/api/remote_module_test.py
{ "start": 1759, "end": 2006 }
class ____: def forward( self, tensor: Tensor, number: int, word: str = "default" ) -> tuple[str, int, Tensor]: # pyre-ignore[7]: Pyre and torch.jit.interface don't mix well pass @torch.jit.interface
MyModuleInterface
python
kamyu104__LeetCode-Solutions
Python/count-cells-in-overlapping-horizontal-and-vertical-substrings.py
{ "start": 50, "end": 1651 }
class ____(object): def countCells(self, grid, pattern): """ :type grid: List[List[str]] :type pattern: str :rtype: int """ # Template: https://cp-algorithms.com/string/z-function.html def z_function(s): # Time: O(n), Space: O(n) z = [0]*len(s) ...
Solution
python
sympy__sympy
sympy/core/operations.py
{ "start": 17827, "end": 20777 }
class ____(AssocOp): """ Join/meet operations of an algebraic lattice[1]. Explanation =========== These binary operations are associative (op(op(a, b), c) = op(a, op(b, c))), commutative (op(a, b) = op(b, a)) and idempotent (op(a, a) = op(a) = a). Common examples are AND, OR, Union, Inters...
LatticeOp
python
astropy__astropy
astropy/modeling/tests/test_models.py
{ "start": 22369, "end": 35671 }
class ____(Fittable2DModelTester): pass def test_ShiftModel(): # Shift by a scalar m = models.Shift(42) assert m(0) == 42 assert_equal(m([1, 2]), [43, 44]) # Shift by a list m = models.Shift([42, 43], n_models=2) assert_equal(m(0), [42, 43]) assert_equal(m([1, 2], model_set_axis=F...
TestFittable2DModels
python
huggingface__transformers
src/transformers/quantizers/quantizer_auto_round.py
{ "start": 967, "end": 3068 }
class ____(HfQuantizer): """ Quantizer of the AutoRound method. (https://huggingface.co/papers/2309.05516) """ # AutoRound requires data calibration - we support only inference requires_calibration = True required_packages = ["auto_round"] def __init__(self, quantization_config: Quantizati...
AutoRoundQuantizer
python
django__django
tests/postgres_tests/models.py
{ "start": 262, "end": 436 }
class ____: def __init__(self, tag_id): self.tag_id = tag_id def __eq__(self, other): return isinstance(other, Tag) and self.tag_id == other.tag_id
Tag
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/core/airflow_defs_data.py
{ "start": 1361, "end": 6980 }
class ____: """A class that holds data about the assets that are mapped to Airflow dags and tasks, and provides methods for retrieving information about the mappings. The user should not instantiate this class directly. It is provided when customizing the events that are generated by the Airflow sensor ...
AirflowDefinitionsData
python
conda__conda
conda/models/channel.py
{ "start": 13682, "end": 24359 }
class ____(Channel): def __init__( self, name: str, channels: Iterable[Channel], platform: str | None = None, ): self.name = name self.location = None # assume all channels are Channels (not MultiChannels) if platform: channels = ( ...
MultiChannel
python
getsentry__sentry
src/sentry/ingest/transaction_clusterer/__init__.py
{ "start": 744, "end": 1071 }
class ____(Enum): TRANSACTIONS = NamespaceOption( name="transactions", data="txnames2", rules="txrules", persistent_storage="sentry:transaction_name_cluster_rules", tracker="txcluster.rules_per_project", meta_store="sentry:transaction_name_cluster_meta", )
ClustererNamespace