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
great-expectations__great_expectations
great_expectations/data_context/store/_store_backend.py
{ "start": 317, "end": 9742 }
class ____(metaclass=ABCMeta): """A store backend acts as a key-value store that can accept tuples as keys, to abstract away reading and writing to a persistence layer. In general a StoreBackend implementation must provide implementations of: - _get - _set - list_keys - _has_key ...
StoreBackend
python
pypa__pipenv
pipenv/cli/options.py
{ "start": 1574, "end": 1960 }
class ____: def __init__(self): self.index = None self.verbose = False self.quiet = False self.pypi_mirror = None self.python = None self.site_packages = None self.clear = False self.system = False self.project = Project() self.installs...
State
python
getsentry__sentry
src/sentry/sentry_metrics/querying/data/transformation/base.py
{ "start": 205, "end": 696 }
class ____(ABC, Generic[QueryTransformerResult]): """ Represents an abstract transformer that can transform QueryResult objects. """ @abstractmethod def transform(self, query_results: list[QueryResult]) -> QueryTransformerResult: """ Transforms the supplied query results into a Quer...
QueryResultsTransformer
python
lazyprogrammer__machine_learning_examples
rl2/mountaincar/pg_theano.py
{ "start": 4164, "end": 7157 }
class ____: def __init__(self, D, ft, hidden_layer_sizes=[]): self.ft = ft # create the graph self.layers = [] M1 = D for M2 in hidden_layer_sizes: layer = HiddenLayer(M1, M2) self.layers.append(layer) M1 = M2 # final layer layer = HiddenLayer(M1, 1, lambda x: x) se...
ValueModel
python
ansible__ansible
test/units/module_utils/datatag/test_datatag.py
{ "start": 1647, "end": 1767 }
class ____(AnsibleDatatagBase): content_str: str @dataclasses.dataclass(**_tag_dataclass_kwargs)
ExampleTagWithContent
python
airbytehq__airbyte
airbyte-integrations/connectors/source-amazon-seller-partner/components.py
{ "start": 5743, "end": 6925 }
class ____(Decoder): parameters: InitVar[Mapping[str, Any]] NORMALIZED_FIELD_NAMES = ["date", "rating", "comments", "response", "order_id", "rater_email"] def is_stream_response(self) -> bool: return False def decode(self, response: requests.Response) -> Generator[MutableMapping[str, Any], Non...
SellerFeedbackReportsGzipCsvDecoder
python
PyCQA__pylint
pylint/pyreverse/inspector.py
{ "start": 16358, "end": 20872 }
class ____(AbstractRelationshipHandler): """Handle regular association relationships.""" def handle( self, node: nodes.AssignAttr | nodes.AssignName, parent: nodes.ClassDef ) -> None: # Extract the name to handle both AssignAttr and AssignName nodes name = node.attrname if isinstanc...
AssociationsHandler
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 267903, "end": 269233 }
class ____( ConditionalValueDefnumberArrayExprRef ): """ ConditionalPredicateValueDefnumberArrayExprRef schema wrapper. Parameters ---------- test : str, dict, :class:`Predicate`, :class:`FieldGTPredicate`, :class:`FieldLTPredicate`, :class:`FieldGTEPredicate`, :class:`FieldLTEPredicate`, :clas...
ConditionalPredicateValueDefnumberArrayExprRef
python
keon__algorithms
tests/test_strings.py
{ "start": 21487, "end": 22497 }
class ____(unittest.TestCase): """[summary] Tests for the fizzbuzz method in file fizzbuzz.py """ def test_fizzbuzz(self): # Testing that n < 0 returns a Value Error self.assertRaises(ValueError, fizzbuzz.fizzbuzz, -2) # Testing that a string returns a Type Error. self.a...
TestFizzbuzz
python
pytorch__pytorch
test/dynamo/test_higher_order_ops.py
{ "start": 179106, "end": 182384 }
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
ZoranPandovski__al-go-rithms
search/a_star/python/astar (2).py
{ "start": 608, "end": 1429 }
class ____(object): """ Class cell represents a cell in the world which have the property position : The position of the represented by tupleof x and y coordinates initially set to (0,0) parent : This contains the parent cell object which we visited before arrinving this cell g,h,f : The pa...
Cell
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py
{ "start": 5904, "end": 6743 }
class ____(BaseConfig): bypass_reason: Optional[str] = Field(description="Reason why this test is bypassed.") unsupported_types: Optional[List[UnsupportedFileTypeConfig]] = Field(description="A list of unsupported file types for the source.") skip_test: Optional[bool] = Field(False, description="Skip file-b...
FileTypesConfig
python
pypa__pip
src/pip/_vendor/pkg_resources/__init__.py
{ "start": 73458, "end": 74740 }
class ____(EmptyProvider): """Metadata handler for standalone PKG-INFO files Usage:: metadata = FileMetadata("/path/to/PKG-INFO") This provider rejects all data and metadata requests except for PKG-INFO, which is treated as existing, and will be the contents of the file at the provided lo...
FileMetadata
python
tqdm__tqdm
tests/tests_tqdm.py
{ "start": 12772, "end": 67775 }
class ____(BytesIO): """File-like to assert the expected type is written""" def __init__(self, expected_type): super().__init__() self.expected_type = expected_type def write(self, s): assert isinstance(s, self.expected_type) def test_native_string_io_for_default_file(): """Na...
WriteTypeChecker
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_nbagg.py
{ "start": 5059, "end": 5149 }
class ____(FigureCanvasWebAggCore): manager_class = FigureManagerNbAgg
FigureCanvasNbAgg
python
opencv__opencv-python
setup.py
{ "start": 12718, "end": 20768 }
class ____: """ Patch SKBuild logic to only take files related to the Python package and construct a file hierarchy that SKBuild expects (see below) """ _setuptools_wrap = None # Have to wrap a function reference, or it's converted # into an instance method on attr assignment i...
RearrangeCMakeOutput
python
sympy__sympy
sympy/physics/quantum/hilbert.py
{ "start": 2856, "end": 5337 }
class ____(HilbertSpace): """Finite dimensional Hilbert space of complex vectors. The elements of this Hilbert space are n-dimensional complex valued vectors with the usual inner product that takes the complex conjugate of the vector on the right. A classic example of this type of Hilbert space is...
ComplexSpace
python
xlwings__xlwings
xlwings/constants.py
{ "start": 76646, "end": 77342 }
class ____: xlMarkerStyleAutomatic = -4105 # from enum XlMarkerStyle xlMarkerStyleCircle = 8 # from enum XlMarkerStyle xlMarkerStyleDash = -4115 # from enum XlMarkerStyle xlMarkerStyleDiamond = 2 # from enum XlMarkerStyle xlMarkerStyleDot = -4118 # from enum XlMarkerStyle xlMarkerStyleNone ...
MarkerStyle
python
davidhalter__jedi
test/completion/inheritance.py
{ "start": 1069, "end": 1357 }
class ____(Test1): def __init__(self): self.foo_sub_class = list def bar(self): #? ['foo_here', 'foo_in_func', 'foo_sub_class'] self.foo_ #? int() self.foo_here #? self.foo_nested #? self.foo_not_on_self
SubTest
python
getsentry__sentry
src/sentry/monitors/processing_errors/errors.py
{ "start": 5852, "end": 6668 }
class ____: errors: Sequence[ProcessingError] checkin: CheckinItem id: uuid.UUID = field(default_factory=uuid.uuid4) def to_dict(self) -> CheckinProcessingErrorData: return { "id": self.id.hex, "checkin": self.checkin.to_dict(), "errors": self.errors, ...
CheckinProcessingError
python
tensorflow__tensorflow
tensorflow/python/ops/critical_section_ops.py
{ "start": 3861, "end": 16398 }
class ____: """Critical section. A `CriticalSection` object is a resource in the graph which executes subgraphs in **serial** order. A common example of a subgraph one may wish to run exclusively is the one given by the following function: ```python v = resource_variable_ops.ResourceVariable(0.0, name="v...
CriticalSection
python
doocs__leetcode
solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution.py
{ "start": 0, "end": 319 }
class ____: def minNumber(self, nums1: List[int], nums2: List[int]) -> int: ans = 100 for a in nums1: for b in nums2: if a == b: ans = min(ans, a) else: ans = min(ans, 10 * a + b, 10 * b + a) return ans
Solution
python
huggingface__transformers
src/transformers/models/bert/modeling_bert.py
{ "start": 6030, "end": 9154 }
class ____(nn.Module): def __init__(self, config, is_causal=False, layer_idx=None): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a mu...
BertSelfAttention
python
sympy__sympy
sympy/tensor/array/expressions/array_expressions.py
{ "start": 1668, "end": 2001 }
class ____(Expr): shape: tuple[Expr, ...] def __getitem__(self, item): if not isinstance(item, collections.abc.Iterable): item = (item,) ArrayElement._check_shape(self, item) return self._get(item) def _get(self, item): return _get_array_element_or_slice(self, i...
_ArrayExpr
python
great-expectations__great_expectations
great_expectations/expectations/metrics/query_metrics/query_multiple_columns.py
{ "start": 631, "end": 3306 }
class ____(QueryMetricProvider): metric_name = "query.multiple_columns" value_keys = ( "columns", "query", ) @metric_value(engine=SqlAlchemyExecutionEngine) def _sqlalchemy( cls, execution_engine: SqlAlchemyExecutionEngine, metric_domain_kwargs: dict, ...
QueryMultipleColumns
python
pytorch__pytorch
test/inductor/test_aot_inductor_custom_ops.py
{ "start": 16202, "end": 17589 }
class ____(TestCase): def setUp(self): if IS_SANDCASTLE or IS_FBCODE: torch.ops.load_library("//caffe2/test/inductor:custom_ops") elif IS_MACOS: raise unittest.SkipTest("non-portable load_library call used in test") else: lib_file_path = find_library_locat...
AOTICustomOpTestCase
python
pytorch__pytorch
test/test_xpu.py
{ "start": 29848, "end": 31848 }
class ____(TestCase): def setUp(self): torch._C._activate_gpu_trace() self.mock = unittest.mock.MagicMock() def test_event_creation_callback(self): gpu_trace.register_callback_for_event_creation(self.mock) event = torch.xpu.Event() event.record() self.mock.asser...
TestXpuTrace
python
pypa__hatch
src/hatch/config/model.py
{ "start": 9848, "end": 13575 }
class ____(LazilyParsedConfig): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._field_project = FIELD_TO_PARSE self._field_env = FIELD_TO_PARSE self._field_python = FIELD_TO_PARSE self._field_data = FIELD_TO_PARSE self._field_cache = FIEL...
DirsConfig
python
huggingface__transformers
src/transformers/models/sam_hq/modular_sam_hq.py
{ "start": 1392, "end": 2833 }
class ____(SamPromptEncoderConfig): r""" This is the configuration class to store the configuration of a [`SamHQPromptEncoderModel`].The [`SamHQPromptEncoderModel`] module is used to encode the input 2D points and bounding boxes. Instantiating a configuration defaults will yield a similar configuration ...
SamHQPromptEncoderConfig
python
apache__airflow
providers/influxdb/tests/unit/influxdb/operators/test_influxdb.py
{ "start": 925, "end": 1422 }
class ____: @mock.patch("airflow.providers.influxdb.operators.influxdb.InfluxDBHook") def test_influxdb_operator_test(self, mock_hook): sql = """from(bucket:"test") |> range(start: -10m)""" op = InfluxDBOperator(task_id="basic_influxdb", sql=sql, influxdb_conn_id="influxdb_default") op.e...
TestInfluxDBOperator
python
dask__distributed
distributed/tests/test_client.py
{ "start": 141349, "end": 142136 }
class ____(Exception): pass @gen_cluster(client=True) async def test_robust_unserializable(c, s, a, b): class NoTokenization: def __getstate__(self): raise MyException() with pytest.raises((TypeError, TokenizationError), match="serialize"): future = c.submit(identity, NoTokeni...
MyException
python
ray-project__ray
rllib/core/rl_module/apis/target_network_api.py
{ "start": 249, "end": 2075 }
class ____(abc.ABC): """An API to be implemented by RLModules for handling target networks. RLModules implementing this API must override the `make_target_networks`, `get_target_network_pairs`, and the `forward_target` methods. Note that the respective Learner that owns the implementing RLModule handl...
TargetNetworkAPI
python
huggingface__transformers
src/transformers/models/glpn/modeling_glpn.py
{ "start": 12179, "end": 15698 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config # stochastic depth decay rule dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")] # patch embeddings embeddings = [] f...
GLPNEncoder
python
ansible__ansible
test/lib/ansible_test/_internal/executor.py
{ "start": 1825, "end": 2038 }
class ____(ApplicationWarning): """Exception when change detection was performed, but no changes were found.""" def __init__(self) -> None: super().__init__('No changes detected.')
NoChangesDetected
python
mlflow__mlflow
mlflow/optuna/storage.py
{ "start": 1288, "end": 25224 }
class ____(BaseStorage): """ MLflow based storage class with batch processing to avoid REST API throttling. """ def __init__( self, experiment_id: str, name: str | None = None, batch_flush_interval: float = 1.0, batch_size_threshold: int = 100, ): """...
MlflowStorage
python
crytic__slither
slither/vyper_parsing/ast/types.py
{ "start": 2784, "end": 2884 }
class ____(ASTNode): test: ASTNode body: List[ASTNode] orelse: List[ASTNode] @dataclass
If
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
{ "start": 123454, "end": 124389 }
class ____(nn.Module): def __init__(self, in_channels, se_channels, out_channels): super().__init__() self.conv1 = nn.Conv1d( in_channels=in_channels, out_channels=se_channels, kernel_size=1, padding="same", padding_mode="reflect", ...
SqueezeExcitationBlock
python
numpy__numpy
numpy/lib/tests/test_function_base.py
{ "start": 83724, "end": 85149 }
class ____: def test_simple(self): assert_(sinc(0) == 1) w = sinc(np.linspace(-1, 1, 100)) # check symmetry assert_array_almost_equal(w, flipud(w), 7) def test_array_like(self): x = [0, 0.5] y1 = sinc(np.array(x)) y2 = sinc(list(x)) y3 = sinc(tup...
TestSinc
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 15801, "end": 16437 }
class ____(Node): # # Code generation for statements is split into the following subphases: # # (1) generate_function_definitions # Emit C code for the definitions of any structs, # unions, enums and functions defined in the current # scope-block. # # (2) gene...
StatNode
python
pypa__setuptools
setuptools/tests/test_config_discovery.py
{ "start": 10589, "end": 12325 }
class ____: @pytest.mark.parametrize( ("folder", "opts"), [ ("src", {}), ("lib", {"packages": "find:", "packages.find": {"where": "lib"}}), ], ) def test_setupcfg_metadata(self, tmp_path, folder, opts): files = [f"{folder}/pkg/__init__.py", "setup.cfg"...
TestWithAttrDirective
python
google__jax
tests/pallas/tpu_pallas_distributed_test.py
{ "start": 25642, "end": 28132 }
class ____(jtu.JaxTestCase): def test_verification(self): self.skipTest( 'TODO(b/455847773): Fix MLIR layout mismatch in tpu.memref_slice (dynamic offset issue).' ) if (num_devices := jax.local_device_count()) <= 1: self.skipTest('Test requires multiple devices.') if not jtu.is_device_t...
VerificationTest
python
sympy__sympy
sympy/core/containers.py
{ "start": 6060, "end": 9479 }
class ____(Basic): """ Wrapper around the builtin dict object. Explanation =========== The Dict is a subclass of Basic, so that it works well in the SymPy framework. Because it is immutable, it may be included in sets, but its values must all be given at instantiation and cannot be ch...
Dict
python
Farama-Foundation__Gymnasium
tests/wrappers/test_numpy_to_torch.py
{ "start": 435, "end": 4572 }
class ____(NamedTuple): a: np.ndarray b: np.ndarray @pytest.mark.parametrize( "value, expected_value", [ (1.0, np.array(1.0, dtype=np.float32)), (2, np.array(2, dtype=np.int64)), ((3.0, 4), (np.array(3.0, dtype=np.float32), np.array(4, dtype=np.int64))), ([3.0, 4], [np....
ExampleNamedTuple
python
kamyu104__LeetCode-Solutions
Python/random-pick-with-blacklist.py
{ "start": 737, "end": 1375 }
class ____(object): def __init__(self, N, blacklist): """ :type N: int :type blacklist: List[int] """ self.__n = N-len(blacklist) blacklist.sort() self.__blacklist = blacklist def pick(self): """ :rtype: int """ ...
Solution2
python
python-openxml__python-docx
src/docx/image/helpers.py
{ "start": 116, "end": 3089 }
class ____: """Wraps a file-like object to provide access to structured data from a binary file. Byte-order is configurable. `base_offset` is added to any base value provided to calculate actual location for reads. """ def __init__(self, stream, byte_order, base_offset=0): super(StreamRead...
StreamReader
python
agronholm__apscheduler
src/apscheduler/serializers/cbor.py
{ "start": 431, "end": 2553 }
class ____(Serializer): """ Serializes objects using CBOR (:rfc:`8949`). Can serialize types not normally CBOR serializable, if they implement ``__getstate__()`` and ``__setstate__()``. :param type_tag: CBOR tag number for indicating arbitrary serialized object :param dump_options: keyword arg...
CBORSerializer
python
jmcnamara__XlsxWriter
examples/inheritance2.py
{ "start": 2271, "end": 3821 }
class ____(Workbook): """ Subclass of the XlsxWriter Workbook class to override the default Worksheet class with our custom class. """ def add_worksheet(self, name=None): # Overwrite add_worksheet() to create a MyWorksheet object. # Also add an Worksheet attribute to store the colu...
MyWorkbook
python
doocs__leetcode
solution/2600-2699/2661.First Completely Painted Row or Column/Solution.py
{ "start": 0, "end": 472 }
class ____: def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int: m, n = len(mat), len(mat[0]) idx = {} for i in range(m): for j in range(n): idx[mat[i][j]] = (i, j) row = [0] * m col = [0] * n for k in range(len(arr)):...
Solution
python
pallets__flask
src/flask/ctx.py
{ "start": 7790, "end": 17246 }
class ____: """An app context contains information about an app, and about the request when handling a request. A context is pushed at the beginning of each request and CLI command, and popped at the end. The context is referred to as a "request context" if it has request information, and an "app contex...
AppContext
python
pytorch__pytorch
torch/_dynamo/source.py
{ "start": 30588, "end": 30994 }
class ____(ChainedSource): def reconstruct(self, codegen: "PyCodegen") -> None: codegen(self.base) codegen.extend_output(codegen.create_load_attrs("_fields")) def guard_source(self) -> GuardSource: return self.base.guard_source() def name(self) -> str: return f"___namedtupl...
NamedTupleFieldsSource
python
python-jsonschema__jsonschema
jsonschema/tests/test_exceptions.py
{ "start": 12995, "end": 17361 }
class ____(TestCase): def test_it_knows_how_many_total_errors_it_contains(self): # FIXME: #442 errors = [ exceptions.ValidationError("Something", validator=i) for i in range(8) ] tree = exceptions.ErrorTree(errors) self.assertEqual(tree.total_errors, 8...
TestErrorTree
python
sympy__sympy
sympy/functions/special/error_functions.py
{ "start": 47256, "end": 49693 }
class ____(DefinedFunction): r""" The offset logarithmic integral. Explanation =========== For use in SymPy, this function is defined as .. math:: \operatorname{Li}(x) = \operatorname{li}(x) - \operatorname{li}(2) Examples ======== >>> from sympy import Li >>> from sympy.abc...
Li
python
tensorflow__tensorflow
tensorflow/python/framework/weak_tensor.py
{ "start": 1392, "end": 1778 }
class ____(composite_tensor_gradient.CompositeTensorGradient): """CompositeTensorGradient for WeakTensor.""" def get_gradient_components(self, weak_tensor): return weak_tensor.tensor def replace_gradient_components(self, weak_tensor, component_grads): return weak_tensor._type_spec._from_components([comp...
WeakTensorGradient
python
gevent__gevent
src/gevent/_ffi/loop.py
{ "start": 2723, "end": 16882 }
class ____(object): def __init__(self, ffi): self.ffi = ffi self.callbacks = [] if GEVENT_DEBUG_LEVEL < TRACE: self.from_handle = ffi.from_handle def from_handle(self, handle): # pylint:disable=method-hidden x = self.ffi.from_handle(handle) return x de...
AbstractCallbacks
python
google__jax
jax/_src/interpreters/mlir.py
{ "start": 60245, "end": 139329 }
class ____: """An immutable container of tokens to be used to lower effectful jaxprs. When lowering effectful jaxprs, we need to thread HLO tokens to sequence them. Each effect will need its own token that will be threaded in and out of the effectful primitives. A `TokenSet` encapsulates a set of HLO tokens tha...
TokenSet
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeParams3.py
{ "start": 1443, "end": 1864 }
class ____[T]: T = 1 reveal_type(T, expected_text="Literal[1]") class Inner1: T = "" reveal_type(T, expected_text="Literal['']") def inner_method(self): reveal_type(T, expected_text="TypeVar") def outer_method(self): T = 3j reveal_type(T, expecte...
Outer2
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 31508, "end": 32869 }
class ____(FieldValues): """ Valid and invalid values for `UUIDField`. """ valid_inputs = { '825d7aeb-05a9-45b5-a5b7-05df87923cda': uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda'), '825d7aeb05a945b5a5b705df87923cda': uuid.UUID('825d7aeb-05a9-45b5-a5b7-05df87923cda'), 'urn:uuid:...
TestUUIDField
python
gevent__gevent
src/gevent/tests/test__monkey_ssl_warning2.py
{ "start": 208, "end": 404 }
class ____(SSLContext): pass # This file should only have this one test in it # because we have to be careful about our imports # and because we need to be careful about our patching.
MySubclass
python
huggingface__transformers
src/transformers/models/gemma/modular_gemma.py
{ "start": 13491, "end": 14267 }
class ____(LlamaForCausalLM): def forward(**super_kwargs): r""" Example: ```python >>> from transformers import AutoTokenizer, GemmaForCausalLM >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b") >>> tokenizer = AutoTokenizer.from_pretrained("google/gemm...
GemmaForCausalLM
python
python-openxml__python-docx
src/docx/shared.py
{ "start": 1777, "end": 2015 }
class ____(Length): """Convenience constructor for length in inches, e.g. ``width = Inches(0.5)``.""" def __new__(cls, inches: float): emu = int(inches * Length._EMUS_PER_INCH) return Length.__new__(cls, emu)
Inches
python
getsentry__sentry
tests/sentry/integrations/utils/test_codecov.py
{ "start": 572, "end": 3783 }
class ____(APITestCase): def setUp(self) -> None: self.create_integration( organization=self.organization, provider="github", external_id="extid", ) options.set("codecov.client-secret", "supersecrettoken") def test_no_github_integration(self) -> None:...
TestCodecovIntegration
python
pypa__setuptools
setuptools/_vendor/backports/tarfile/__init__.py
{ "start": 19391, "end": 20225 }
class ____(object): """Small proxy class that enables transparent compression detection for the Stream interface (mode 'r|*'). """ def __init__(self, fileobj): self.fileobj = fileobj self.buf = self.fileobj.read(BLOCKSIZE) def read(self, size): self.read = self.fileobj.r...
_StreamProxy
python
gevent__gevent
src/gevent/exceptions.py
{ "start": 1811, "end": 2024 }
class ____(AssertionError): """ Raised when the event loop returns control to a greenlet in an unexpected way. This is usually a bug in gevent, greenlet, or the event loop. """
InvalidSwitchError
python
airbytehq__airbyte
airbyte-integrations/connectors/source-salesforce/source_salesforce/api.py
{ "start": 6616, "end": 17486 }
class ____: logger = logging.getLogger("airbyte") version = API_VERSION parallel_tasks_size = 100 # https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_api.htm # Request Size Limits REQUEST_SIZE_L...
Salesforce
python
pola-rs__polars
py-polars/src/polars/io/iceberg/_utils.py
{ "start": 5831, "end": 11178 }
class ____: def __init__( self, table: Table, projected_schema: pyiceberg.schema.Schema, ) -> None: import pyiceberg.schema from pyiceberg.io.pyarrow import schema_to_pyarrow from pyiceberg.transforms import IdentityTransform from pyiceberg.types import ( ...
IdentityTransformedPartitionValuesBuilder
python
django-extensions__django-extensions
tests/testapp/models.py
{ "start": 2535, "end": 2633 }
class ____(models.Model): class Meta: app_label = "django_extensions"
DummyRelationModel
python
FactoryBoy__factory_boy
tests/alchemyapp/models.py
{ "start": 528, "end": 722 }
class ____(Base): __tablename__ = 'MultiFieldModelTable' id = Column(Integer(), primary_key=True) foo = Column(Unicode(20)) slug = Column(Unicode(20), unique=True)
MultiFieldModel
python
numpy__numpy
tools/swig/test/testArray.py
{ "start": 3849, "end": 8739 }
class ____(unittest.TestCase): def setUp(self): self.nrows = 5 self.ncols = 4 self.array2 = Array.Array2(self.nrows, self.ncols) def testConstructor0(self): "Test Array2 default constructor" a = Array.Array2() self.assertTrue(isinstance(a, Array.Array2)) ...
Array2TestCase
python
rapidsai__cudf
python/cudf_polars/cudf_polars/experimental/rapidsmpf/dispatch.py
{ "start": 1223, "end": 1442 }
class ____(NamedTuple): """A named tuple representing fanout information.""" num_consumers: int """The number of consumers.""" unbounded: bool """Whether the node needs unbounded fanout."""
FanoutInfo
python
django__django
tests/admin_views/admin.py
{ "start": 13334, "end": 13398 }
class ____(admin.StackedInline): model = Whatsit
WhatsitInline
python
walkccc__LeetCode
solutions/2263. Make Array Non-decreasing or Non-increasing/2263.py
{ "start": 0, "end": 415 }
class ____: def convertArray(self, nums: list[int]) -> int: def cost(nums: list[int]) -> int: ans = 0 minHeap = [] # Greedily make `nums` non-increasing. for num in nums: if minHeap and minHeap[0] < num: ans += num - heapq.heappushpop(minHeap, num) heapq.heappush...
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol24.py
{ "start": 286, "end": 453 }
class ____: def meth(self, x: int) -> int: ... # This should generate an error because C.meth isn't compatible # with ProtoA().meth. a: ProtoA = C b: ProtoB = C
C
python
pytorch__pytorch
torch/_inductor/loop_body.py
{ "start": 20527, "end": 20882 }
class ____(DefaultHandler): def __init__(self, inner: OpsHandler[Any], counts: collections.Counter[str]): self._inner = inner self._counts = counts def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: self._counts[name] += 1 return getattr(self._i...
CountOps
python
scrapy__scrapy
tests/test_pipeline_files.py
{ "start": 12321, "end": 20300 }
class ____: default_cls_settings = { "EXPIRES": 90, "FILES_URLS_FIELD": "file_urls", "FILES_RESULT_FIELD": "files", } file_cls_attr_settings_map = { ("EXPIRES", "FILES_EXPIRES", "expires"), ("FILES_URLS_FIELD", "FILES_URLS_FIELD", "files_urls_field"), ("FILES_...
TestFilesPipelineCustomSettings
python
django__django
tests/composite_pk/test_filter.py
{ "start": 431, "end": 20477 }
class ____(TestCase): maxDiff = None @classmethod def setUpTestData(cls): cls.tenant_1 = Tenant.objects.create() cls.tenant_2 = Tenant.objects.create() cls.tenant_3 = Tenant.objects.create() cls.user_1 = User.objects.create( tenant=cls.tenant_1, id=1,...
CompositePKFilterTests
python
sphinx-doc__sphinx
sphinx/writers/html5.py
{ "start": 1238, "end": 38759 }
class ____(SphinxTranslator, BaseTranslator): # type: ignore[misc] """Our custom HTML translator.""" builder: StandaloneHTMLBuilder # Override docutils.writers.html5_polyglot:HTMLTranslator # otherwise, nodes like <inline classes="s">...</inline> will be # converted to <s>...</s> by `visit_inline`...
HTML5Translator
python
numpy__numpy
numpy/lib/tests/test_type_check.py
{ "start": 9761, "end": 10019 }
class ____: def test_generic(self): with np.errstate(divide='ignore', invalid='ignore'): vals = isposinf(np.array((-1., 0, 1)) / 0.) assert_(vals[0] == 0) assert_(vals[1] == 0) assert_(vals[2] == 1)
TestIsposinf
python
ray-project__ray
ci/ray_ci/automation/docker_tags_lib.py
{ "start": 6969, "end": 7183 }
class ____(Exception): """ Exception for failing to retrieve image config. """ def __init__(self, message: str): super().__init__(f"Failed to retrieve {message}")
RetrieveImageConfigException
python
pandas-dev__pandas
pandas/core/window/rolling.py
{ "start": 50890, "end": 66140 }
class ____(BaseWindow): def count(self, numeric_only: bool = False): window_func = window_aggregations.roll_sum return self._apply(window_func, name="count", numeric_only=numeric_only) def apply( self, func: Callable[..., Any], raw: bool = False, engine: Literal[...
RollingAndExpandingMixin
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_cond_format11.py
{ "start": 315, "end": 1343 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("cond_format11.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with conditional formatting.""" ...
TestCompareXLSXFiles
python
ray-project__ray
python/ray/tune/tests/test_logger.py
{ "start": 687, "end": 1743 }
class ____: evaluated_params: dict trial_id: str logdir: str experiment_path: Optional[str] = None experiment_dir_name: Optional[str] = None path: Optional[str] = None checkpoint: Optional[Checkpoint] = None @property def config(self): return self.evaluated_params def i...
Trial
python
pytorch__pytorch
test/inductor/test_mkldnn_pattern_matcher.py
{ "start": 9571, "end": 24249 }
class ____(TestPatternMatcherBase): def _test_conv_unary_base(self, dim=4): assert dim == 4 or dim == 5 class M(torch.nn.Module): def __init__( self, unary_fn, **kwargs, ): super().__init__() if ...
TestPatternMatcherGeneric
python
PyCQA__pylint
tests/functional/c/class_scope.py
{ "start": 105, "end": 712 }
class ____: """well""" attr = 42 get_attr = lambda arg=attr: arg * 24 # +1: [undefined-variable, used-before-assignment] get_attr_bad = lambda arg=revattr: revattr * 42 revattr = 24 bad_lambda = lambda: get_attr_bad # [undefined-variable] bad_gen = list(attr + i for i in range(10)) # [un...
Well
python
airbytehq__airbyte
airbyte-integrations/connectors/source-smartsheets/source_smartsheets/sheet.py
{ "start": 324, "end": 7099 }
class ____: def __init__(self, config: Mapping[str, Any]): self._spreadsheet_id = config["spreadsheet_id"] self._config = config self._metadata = config.get("metadata_fields", []) self.api_client = smartsheet.Smartsheet(self.get_access_token(config)) self.api_client.errors_as...
SmartSheetAPIWrapper
python
pytorch__pytorch
torch/distributions/constraints.py
{ "start": 12043, "end": 12536 }
class ____(Constraint): """ Constrain to an integer interval `[lower_bound, inf)`. """ is_discrete = True def __init__(self, lower_bound): self.lower_bound = lower_bound super().__init__() def check(self, value): return (value % 1 == 0) & (value >= self.lower_bound) ...
_IntegerGreaterThan
python
django__django
tests/queries/models.py
{ "start": 7947, "end": 8143 }
class ____(models.Model): single = models.ForeignKey(SingleObject, models.SET_NULL, null=True) f = models.IntegerField(null=True) class Meta: ordering = ["single"]
RelatedObject
python
doocs__leetcode
solution/1700-1799/1728.Cat and Mouse II/Solution.py
{ "start": 0, "end": 3077 }
class ____: def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool: m, n = len(grid), len(grid[0]) cat_start = mouse_start = food = 0 dirs = (-1, 0, 1, 0, -1) g_mouse = [[] for _ in range(m * n)] g_cat = [[] for _ in range(m * n)] for i, row in ...
Solution
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_glue.py
{ "start": 4145, "end": 5564 }
class ____: @pytest.mark.asyncio @mock.patch.object(GlueCatalogHook, "async_get_partitions") async def test_poke(self, mock_async_get_partitions): a_mock = mock.AsyncMock() a_mock.return_value = True mock_async_get_partitions.return_value = a_mock trigger = GlueCatalogPartiti...
TestGlueCatalogPartitionSensorTrigger
python
PrefectHQ__prefect
src/integrations/prefect-gcp/prefect_gcp/credentials.py
{ "start": 1766, "end": 2518 }
class ____(Enum): CLOUD_STORAGE = "cloud_storage" BIGQUERY = "bigquery" SECRET_MANAGER = "secret_manager" AIPLATFORM = "job_service" # vertex ai @functools.lru_cache(maxsize=8, typed=True) def _get_job_service_async_client_cached( ctx, client_options: tuple ) -> "JobServiceAsyncClient": """ ...
ClientType
python
celery__celery
celery/schedules.py
{ "start": 1731, "end": 3037 }
class ____: def __init__(self, nowfun: Callable | None = None, app: Celery | None = None): self.nowfun = nowfun self._app = app def now(self) -> datetime: return (self.nowfun or self.app.now)() def remaining_estimate(self, last_run_at: datetime) -> timedelta: raise NotImpl...
BaseSchedule
python
pypa__pipenv
pipenv/exceptions.py
{ "start": 7893, "end": 8229 }
class ____(PipenvException): def __init__(self, message=None, **kwargs): if not message: message = ( "There was an unexpected error while activating your virtualenv. " "Continuing anyway..." ) PipenvException.__init__(self, message, **kwargs) ...
VirtualenvException
python
Netflix__metaflow
test/unit/inheritance/flows/comprehensive_diamond_base.py
{ "start": 924, "end": 1684 }
class ____(BaseA, BaseB): """Diamond merge point with additional features""" param_c = Parameter("param_c", help="Parameter from BaseC", default=25) config_c = Config("config_c", default_value={"mode": "diamond", "enabled": True}) @step def process(self): """Process step using values from ...
BaseC
python
has2k1__plotnine
plotnine/geoms/annotate.py
{ "start": 427, "end": 4165 }
class ____: """ Create an annotation layer Parameters ---------- geom : geom to use for annotation, or name of geom (e.g. 'point'). x : Position y : Position xmin : Position ymin : Position xmax : Position ymax : Positi...
annotate
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-together/llama_index/embeddings/together/base.py
{ "start": 234, "end": 5525 }
class ____(BaseEmbedding): api_base: str = Field( default="https://api.together.xyz/v1", description="The base URL for the Together API.", ) api_key: str = Field( default="", description="The API key for the Together API. If not set, will attempt to use the TOGETHER_API_KEY e...
TogetherEmbedding
python
weaviate__weaviate-python-client
weaviate/collections/classes/filters.py
{ "start": 447, "end": 2430 }
class ____(str, Enum): EQUAL = "Equal" NOT_EQUAL = "NotEqual" LESS_THAN = "LessThan" LESS_THAN_EQUAL = "LessThanEqual" GREATER_THAN = "GreaterThan" GREATER_THAN_EQUAL = "GreaterThanEqual" LIKE = "Like" IS_NULL = "IsNull" CONTAINS_ANY = "ContainsAny" CONTAINS_ALL = "ContainsAll" ...
_Operator
python
pytorch__pytorch
tools/experimental/torchfuzz/tensor_fuzzer.py
{ "start": 378, "end": 535 }
class ____(NamedTuple): """Specification for a tensor argument.""" size: tuple[int, ...] stride: tuple[int, ...] dtype: torch.dtype
TensorSpec
python
kamyu104__LeetCode-Solutions
Python/number-of-divisible-triplet-sums.py
{ "start": 65, "end": 591 }
class ____(object): def divisibleTripletCount(self, nums, d): """ :type nums: List[int] :type d: int :rtype: int """ result = 0 cnt = collections.Counter() for i in xrange(len(nums)): for j in xrange(i+1, len(nums)): if (num...
Solution
python
walkccc__LeetCode
solutions/99. Recover Binary Search Tree/99-3.py
{ "start": 0, "end": 1247 }
class ____: def recoverTree(self, root: TreeNode | None) -> None: pred = None x = None # the first wrong node y = None # the second wrong node def findPredecessor(root: TreeNode | None) -> TreeNode | None: pred = root.left while pred.right and pred.right != root: pred = pred.rig...
Solution
python
scikit-image__scikit-image
benchmarks/benchmark_morphology.py
{ "start": 1645, "end": 2296 }
class ____: # skip rectangle as roughly equivalent to square param_names = ["shape", "radius"] params = [ ((512, 512),), (1, 3, 5, 15, 25, 40), ] def setup(self, shape, radius): rng = np.random.default_rng(123) # Create an image that is mostly True, with random isola...
IsotropicMorphology2D
python
yaml__pyyaml
lib/yaml/scanner.py
{ "start": 906, "end": 51279 }
class ____: def __init__(self): """Initialize the scanner.""" # It is assumed that Scanner and Reader will have a common descendant. # Reader do the dirty work of checking for BOM and converting the # input data to Unicode. It also adds NUL to the end. # # Reader sup...
Scanner