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
tensorflow__tensorflow
tensorflow/python/training/saver_test.py
{ "start": 48912, "end": 54248 }
class ____(SaveRestoreShardedTest): _WRITE_VERSION = saver_pb2.SaverDef.V2 def testIterators(self): save_path = os.path.join(self.get_temp_dir(), "sharded_iterators") # Build a graph with 2 parameter nodes on different devices and save. with session.Session( target="", config=config_pb...
SaveRestoreShardedTestV2
python
gevent__gevent
src/greentest/3.10/test_ssl.py
{ "start": 204134, "end": 210459 }
class ____(unittest.TestCase): def keylog_lines(self, fname=os_helper.TESTFN): with open(fname) as f: return len(list(f)) @requires_keylog @unittest.skipIf(Py_DEBUG_WIN32, "Avoid mixing debug/release CRT on Windows") def test_keylog_defaults(self): self.addCleanup(os_helper...
TestSSLDebug
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/solids.py
{ "start": 20265, "end": 20466 }
class ____(graphene.Union): class Meta: types = (GrapheneSolidStepStatsConnection, GrapheneSolidStepStatsUnavailableError) name = "SolidStepStatsOrError"
GrapheneSolidStepStatsOrError
python
google__jax
jax/_src/state/indexing.py
{ "start": 1033, "end": 4886 }
class ____: """A slice with a start index and a size. Both start index and size can either be static, i.e. known at tracing and compilation time, or dynamic. """ start: int | Array size: int | Array stride: int = 1 def __post_init__(self): if self.stride < 0: raise ValueError("`stride` must...
Slice
python
PyCQA__pylint
tests/functional/ext/docparams/missing_param_doc.py
{ "start": 3915, "end": 4580 }
class ____: """ Methods decorated with `typing.overload` are excluded from the docparam checks. For example: `missing-param-doc` and `missing-type-doc`. """ def __init__(self, word): self.word = word @overload def starts_with(self, letter: None) -> None: ... @overload d...
Word
python
sqlalchemy__sqlalchemy
test/ext/declarative/test_reflection.py
{ "start": 15798, "end": 18440 }
class ____(DeferredInhReflectBase): @classmethod def define_tables(cls, metadata): Table( "foo", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("type", String(32)), Column(...
DeferredJoinedInhReflectionTest
python
pytest-dev__pytest
src/_pytest/capture.py
{ "start": 18958, "end": 22194 }
class ____(Generic[AnyStr]): _state = None _in_suspended = False def __init__( self, in_: CaptureBase[AnyStr] | None, out: CaptureBase[AnyStr] | None, err: CaptureBase[AnyStr] | None, ) -> None: self.in_: CaptureBase[AnyStr] | None = in_ self.out: Capture...
MultiCapture
python
django-haystack__django-haystack
test_haystack/whoosh_tests/test_whoosh_backend.py
{ "start": 41795, "end": 43167 }
class ____(WhooshTestCase): fixtures = ["bulk_data.json"] def setUp(self): super().setUp() # Stow. self.old_ui = connections["whoosh"].get_unified_index() self.ui = UnifiedIndex() self.wmmi = WhooshMockSearchIndex() self.wamsi = WhooshAnotherMockSearchIndex() ...
LiveWhooshMultiSearchQuerySetTestCase
python
kamyu104__LeetCode-Solutions
Python/invert-binary-tree.py
{ "start": 1714, "end": 2006 }
class ____(object): # @param {TreeNode} root # @return {TreeNode} def invertTree(self, root): if root is not None: root.left, root.right = self.invertTree(root.right), \ self.invertTree(root.left) return root
Solution3
python
jazzband__django-formtools
tests/tests.py
{ "start": 1196, "end": 6838 }
class ____(TestCase): def setUp(self): super().setUp() # Create a FormPreview instance to share between tests self.preview = preview.FormPreview(TestForm) input_template = '<input type="hidden" name="%s" value="%s" />' self.input = input_template % (self.preview.unused_name(...
PreviewTests
python
apache__airflow
scripts/ci/prek/upgrade_important_versions.py
{ "start": 11405, "end": 25819 }
class ____(Enum): UNQUOTED = 0 SINGLE_QUOTED = 1 DOUBLE_QUOTED = 2 REVERSE_SINGLE_QUOTED = 3 REVERSE_DOUBLE_QUOTED = 4 PIP_PATTERNS: list[tuple[re.Pattern, Quoting]] = [ (re.compile(r"(AIRFLOW_PIP_VERSION=)([0-9.abrc]+)"), Quoting.UNQUOTED), (re.compile(r"(python -m pip install --upgrade p...
Quoting
python
tensorflow__tensorflow
tensorflow/python/keras/losses.py
{ "start": 16871, "end": 19016 }
class ____(LossFunctionWrapper): """Computes the mean squared logarithmic error between `y_true` and `y_pred`. `loss = square(log(y_true + 1.) - log(y_pred + 1.))` Standalone usage: >>> y_true = [[0., 1.], [0., 0.]] >>> y_pred = [[1., 1.], [1., 0.]] >>> # Using 'auto'/'sum_over_batch_size' reduction type...
MeanSquaredLogarithmicError
python
numpy__numpy
numpy/distutils/msvc9compiler.py
{ "start": 1039, "end": 2192 }
class ____(_MSVCCompiler): def __init__(self, verbose=0, dry_run=0, force=0): _MSVCCompiler.__init__(self, verbose, dry_run, force) def initialize(self, plat_name=None): # The 'lib' and 'include' variables may be overwritten # by MSVCCompiler.initialize, so save them for later merge. ...
MSVCCompiler
python
walkccc__LeetCode
solutions/1751. Maximum Number of Events That Can Be Attended II/1751.py
{ "start": 0, "end": 632 }
class ____: def maxValue(self, events: list[list[int]], k: int) -> int: events.sort() @functools.lru_cache(None) def dp(i: int, k: int) -> int: """ Returns the maximum sum of values that you can receive by attending events[i..n), where k is the maximum number of attendance. """ ...
Solution
python
tensorflow__tensorflow
tensorflow/python/training/basic_session_run_hooks.py
{ "start": 34173, "end": 35929 }
class ____(session_run_hook.SessionRunHook): """Delays execution until global step reaches `wait_until_step`. This hook delays execution until global step reaches to `wait_until_step`. It is used to gradually start workers in distributed settings. One example usage would be setting `wait_until_step=int(K*log(t...
GlobalStepWaiterHook
python
davidhalter__jedi
test/completion/arrays.py
{ "start": 2349, "end": 3496 }
class ____: setitem_x = [1,2] setitem_x[0] = 3 #? ['setitem_x'] F().setitem_x #? list() F().setitem_x # ----------------- # dicts # ----------------- dic2 = {'asdf': 3, 'b': 'str'} #? int() dic2['asdf'] #? None int() str() dic2.get('asdf') # string literal #? int() dic2[r'asdf'] #? int() dic2[r'asdf'] #? in...
F
python
great-expectations__great_expectations
great_expectations/render/renderer/site_builder.py
{ "start": 41063, "end": 41186 }
class ____: def __init__(self, title, link) -> None: self.title = title self.link = link
CallToActionButton
python
catalyst-team__catalyst
catalyst/contrib/datasets/imagenette.py
{ "start": 473, "end": 942 }
class ____(ImageClassificationDataset): """ `Imagenette <https://github.com/fastai/imagenette#imagenette-1>`_ Dataset with images resized so that the shortest size is 160 px. .. note:: catalyst[cv] required for this dataset. """ name = "imagenette2-160" resources = [ ( ...
Imagenette160
python
joke2k__faker
tests/providers/test_ssn.py
{ "start": 41214, "end": 41799 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("en_IN") Faker.seed(0) test_samples = 10 self.aadhaar_ids = [self.fake.aadhaar_id() for _ in range(test_samples)] def test_length(self): for aadhaar_id in self.aadhaar_ids: assert len(aadhaar_i...
TestEnIn
python
keon__algorithms
algorithms/map/separate_chaining_hashtable.py
{ "start": 18, "end": 172 }
class ____(object): def __init__(self, key=None, value=None, next=None): self.key = key self.value = value self.next = next
Node
python
google__python-fire
fire/trace.py
{ "start": 8251, "end": 10314 }
class ____: """A FireTraceElement represents a single step taken by a Fire execution. Examples of a FireTraceElement are the instantiation of a class or the accessing of an object member. """ def __init__(self, component=None, action=None, target=None, ...
FireTraceElement
python
great-expectations__great_expectations
docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/multicolumn_map_expectation_template.py
{ "start": 2858, "end": 5782 }
class ____(MulticolumnMapExpectation): # </snippet> # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/multicolumn_map_expectation_template.py docstring"> """TODO: Add a docstring here""" # </snippet> # These examples will be shown in the public gallery. ...
ExpectMulticolumnValuesToMatchSomeCriteria
python
pytorch__pytorch
test/distributed/checkpoint/e2e/test_fine_tuning.py
{ "start": 1111, "end": 1762 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.layer1 = nn.Linear(DIM, DIM) self.layer2 = nn.Linear(DIM, DIM) self.layer3 = nn.Linear(DIM, DIM) self.sequential = nn.Sequential(nn.Linear(DIM, DIM), nn.ReLU()) self.module_list = nn.ModuleList...
PreTrainedModel
python
pandas-dev__pandas
pandas/core/arrays/integer.py
{ "start": 5693, "end": 5882 }
class ____(IntegerDtype): type = np.int64 name: ClassVar[str] = "Int64" __doc__ = _dtype_docstring.format(dtype="int64") @register_extension_dtype @set_module("pandas")
Int64Dtype
python
scipy__scipy
benchmarks/benchmarks/interpolate.py
{ "start": 1809, "end": 2459 }
class ____(Benchmark): param_names = ['n_grids', 'method'] params = [ [10j, 100j, 1000j], ['nearest', 'linear', 'cubic'] ] def setup(self, n_grids, method): self.func = lambda x, y: x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2 self.grid_x, self.grid_y = np.mgrid[0...
GridData
python
gevent__gevent
src/gevent/testing/util.py
{ "start": 6751, "end": 12408 }
class ____(object): """ The results of running an external command. If the command was successful, this has a boolean value of True; otherwise, a boolean value of false. The integer value of this object is the command's exit code. """ def __init__(self, command, ...
RunResult
python
google__pytype
pytype/typegraph/typegraph_serializer.py
{ "start": 1656, "end": 1884 }
class ____: id: int solver_idx: int start_node: CFGNodeId end_node: CFGNodeId initial_binding_count: int shortcircuited: bool from_cache: bool steps: list[SerializedQueryStep] @dataclasses.dataclass
SerializedQuery
python
Textualize__textual
src/textual/_path.py
{ "start": 301, "end": 2062 }
class ____(Exception): """Raised when supplied CSS path(s) are invalid.""" def _css_path_type_as_list(css_path: CSSPathType) -> list[PurePath]: """Normalize the supplied CSSPathType into a list of paths. Args: css_path: Value to be normalized. Raises: CSSPathError: If the argument ha...
CSSPathError
python
doocs__leetcode
solution/2200-2299/2256.Minimum Average Difference/Solution.py
{ "start": 0, "end": 434 }
class ____: def minimumAverageDifference(self, nums: List[int]) -> int: pre, suf = 0, sum(nums) n = len(nums) ans, mi = 0, inf for i, x in enumerate(nums): pre += x suf -= x a = pre // (i + 1) b = 0 if n - i - 1 == 0 else suf // (n - i ...
Solution
python
getsentry__sentry
src/sentry/issues/endpoints/project_event_details.py
{ "start": 3044, "end": 5396 }
class ____(ProjectEndpoint): owner = ApiOwner.ISSUES publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } rate_limits = RateLimitConfig( limit_overrides={ "GET": { RateLimitCategory.IP: RateLimit(limit=5, window=1), RateLimitCategory.USE...
ProjectEventDetailsEndpoint
python
cython__cython
Cython/Compiler/PyrexTypes.py
{ "start": 98931, "end": 101291 }
class ____(CType): # common base type for pointer/array types # # base_type CType Reference type # is_string bool Pointer is a char* or similar C string. # is_pyunicode_ptr bool Pointer is a Py_UNICODE*. subtypes = ['base_type'] def __init__...
CPointerBaseType
python
django__django
django/forms/widgets.py
{ "start": 33535, "end": 34449 }
class ____(MultiWidget): """ A widget that splits datetime input into two <input type="text"> boxes. """ supports_microseconds = False template_name = "django/forms/widgets/splitdatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, ...
SplitDateTimeWidget
python
coleifer__peewee
peewee.py
{ "start": 98452, "end": 111716 }
class ____(_callable_context_manager): context_class = Context field_types = {} operations = {} param = '?' quote = '""' server_version = None # Feature toggles. compound_select_parentheses = CSQ_PARENTHESES_NEVER for_update = False index_schema_prefix = False index_using_pr...
Database
python
openai__openai-python
src/openai/resources/beta/threads/runs/runs.py
{ "start": 2086, "end": 75439 }
class ____(SyncAPIResource): @cached_property def steps(self) -> Steps: return Steps(self._client) @cached_property def with_raw_response(self) -> RunsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object in...
Runs
python
allegroai__clearml
clearml/backend_api/session/client/client.py
{ "start": 2934, "end": 4286 }
class ____(Session): """ Session that raises exceptions on errors, and be configured with explicit ``config_file`` path. """ def __init__( self, config_file: Union[Path, Text] = None, initialize_logging: bool = False, *args: Any, **kwargs: Any, ) -> None: ...
StrictSession
python
joke2k__faker
faker/providers/currency/es_AR/__init__.py
{ "start": 48, "end": 281 }
class ____(CurrencyProvider): price_formats = ["%##", "%.###", "%#.##0", "%##.##0", "%##.##0", "%.###.##0", "%#,##"] def pricetag(self) -> str: return "$" + self.numerify(self.random_element(self.price_formats))
Provider
python
fastapi__sqlmodel
docs_src/tutorial/many_to_many/tutorial003.py
{ "start": 753, "end": 3834 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_links: List[HeroTeamLink] = Relationship(back_populates="hero") sqlite_file_name = "database.db" sql...
Hero
python
pytorch__pytorch
torch/nn/modules/rnn.py
{ "start": 48956, "end": 60810 }
class ____(RNNBase): r"""__init__(input_size,hidden_size,num_layers=1,bias=True,batch_first=False,dropout=0.0,bidirectional=False,device=None,dtype=None) Apply a multi-layer gated recurrent unit (GRU) RNN to an input sequence. For each element in the input sequence, each layer computes the following fu...
GRU
python
plotly__plotly.py
plotly/graph_objs/indicator/number/_font.py
{ "start": 233, "end": 9890 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "indicator.number" _path_str = "indicator.number.font" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @p...
Font
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/strategy_options.py
{ "start": 45935, "end": 52005 }
class ____(_AbstractLoad): """represent a standalone '*' load operation""" __slots__ = ("strategy", "path", "local_opts") _traverse_internals = [ ("strategy", visitors.ExtendedInternalTraversal.dp_plain_obj), ("path", visitors.ExtendedInternalTraversal.dp_plain_obj), ( ...
_WildcardLoad
python
openai__openai-python
src/openai/types/beta/threads/message_delta.py
{ "start": 279, "end": 570 }
class ____(BaseModel): content: Optional[List[MessageContentDelta]] = None """The content of the message in array of text and/or images.""" role: Optional[Literal["user", "assistant"]] = None """The entity that produced the message. One of `user` or `assistant`."""
MessageDelta
python
facebook__pyre-check
tools/generate_taint_models/model.py
{ "start": 12229, "end": 12771 }
class ____(Model): class_name: str annotation: str def __init__(self, class_name: str, annotation: str) -> None: self.class_name = class_name self.annotation = annotation def __str__(self) -> str: return f"class {self.class_name}({self.annotation}): ..." def __eq__(self, o...
ClassModel
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-pathway/llama_index/readers/pathway/base.py
{ "start": 3476, "end": 4951 }
class ____(BaseReader): """ Pathway reader. Retrieve documents from Pathway data indexing pipeline. Args: host (str): The URI where Pathway is currently hosted. port (str | int): The port number on which Pathway is listening. See Also: llamaindex.retriever.pathway.PathwayR...
PathwayReader
python
realpython__materials
python-enum/semaphore.py
{ "start": 24, "end": 665 }
class ____(Enum): RED = 1 YELLOW = 2 GREEN = 3 # def handle_semaphore(light): # if light is Semaphore.RED: # print("You must stop!") # elif light is Semaphore.YELLOW: # print("Light will change to red, be careful!") # elif light is Semaphore.GREEN: # print("You can cont...
Semaphore
python
tornadoweb__tornado
tornado/test/util_test.py
{ "start": 9001, "end": 9670 }
class ____(unittest.TestCase): def test_import_member(self): self.assertIs(import_object("tornado.escape.utf8"), utf8) def test_import_member_unicode(self): self.assertIs(import_object("tornado.escape.utf8"), utf8) def test_import_module(self): self.assertIs(import_object("tornado....
ImportObjectTest
python
h5py__h5py
h5py/tests/test_file.py
{ "start": 24369, "end": 25059 }
class ____(TestCase): """ Feature: Files can be closed """ def test_close(self): """ Close file via .close method """ fid = File(self.mktemp(), 'w') self.assertTrue(fid) fid.close() self.assertFalse(fid) def test_closed_file(self): """ Trying to...
TestClose
python
apache__airflow
task-sdk/tests/task_sdk/definitions/test_callback.py
{ "start": 6717, "end": 8030 }
class ____: @pytest.mark.parametrize( ("callback_callable", "kwargs", "expected_path"), [ pytest.param( empty_async_callback_for_deadline_tests, TEST_CALLBACK_KWARGS, TEST_CALLBACK_PATH, id="callable", ), ...
TestAsyncCallback
python
airbytehq__airbyte
airbyte-integrations/connectors/source-microsoft-onedrive/source_microsoft_onedrive/source.py
{ "start": 571, "end": 3152 }
class ____(FileBasedSource): def __init__(self, catalog: Optional[ConfiguredAirbyteCatalog], config: Optional[Mapping[str, Any]], state: Optional[TState]): super().__init__( stream_reader=SourceMicrosoftOneDriveStreamReader(), spec_class=SourceMicrosoftOneDriveSpec, catal...
SourceMicrosoftOneDrive
python
apache__airflow
airflow-core/tests/unit/models/test_dag.py
{ "start": 113688, "end": 139405 }
class ____: """ Task clearing behavior is mainly controlled by dag.partial_subset. Here we verify, primarily with regard to setups and teardowns, the behavior of dag.partial_subset but also the supporting methods defined on AbstractOperator. """ @staticmethod def make_tasks(dag, input_s...
TestTaskClearingSetupTeardownBehavior
python
getsentry__sentry
src/sentry/incidents/endpoints/organization_incident_details.py
{ "start": 775, "end": 1301 }
class ____(serializers.Serializer): status = serializers.IntegerField() comment = serializers.CharField(required=False, allow_null=True) def validate_status(self, value): try: value = IncidentStatus(value) except Exception: raise serializers.ValidationError( ...
IncidentSerializer
python
huggingface__transformers
src/transformers/models/mistral3/modeling_mistral3.py
{ "start": 1779, "end": 2508 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Mistral3RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): inp...
Mistral3RMSNorm
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_constraints.py
{ "start": 1247, "end": 1285 }
class ____(Child0, Local): pass
Child1
python
huggingface__transformers
setup.py
{ "start": 7844, "end": 16390 }
class ____(Command): """ A custom distutils command that updates the dependency table. usage: python setup.py deps_table_update """ description = "build runtime dependency table" user_options = [ # format: (long option, short option, description). ("dep-table-update", None, "upd...
DepsTableUpdateCommand
python
scrapy__scrapy
scrapy/core/downloader/handlers/http11.py
{ "start": 4581, "end": 9752 }
class ____(TCP4ClientEndpoint): """An endpoint that tunnels through proxies to allow HTTPS downloads. To accomplish that, this endpoint sends an HTTP CONNECT to the proxy. The HTTP CONNECT is always sent when using this endpoint, I think this could be improved as the CONNECT will be redundant if the con...
TunnelingTCP4ClientEndpoint
python
scipy__scipy
scipy/special/tests/test_spherical_bessel.py
{ "start": 11042, "end": 15195 }
class ____: # These are tests from the TestSpherical class of test_basic.py, # rewritten to use spherical_* instead of sph_* but otherwise unchanged. def test_sph_in(self): # This test reproduces test_basic.TestSpherical.test_sph_in. i1n = np.empty((2,2)) x = 0.2 i1n[0][0] ...
TestSphericalOld
python
huggingface__transformers
src/transformers/models/siglip2/modeling_siglip2.py
{ "start": 23587, "end": 25884 }
class ____(nn.Module): def __init__(self, config: Siglip2TextConfig): super().__init__() self.config = config embed_dim = config.hidden_size self.embeddings = Siglip2TextEmbeddings(config) self.encoder = Siglip2Encoder(config) self.final_layer_norm = nn.LayerNorm(embe...
Siglip2TextTransformer
python
huggingface__transformers
src/transformers/models/aimv2/configuration_aimv2.py
{ "start": 1315, "end": 5906 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Aimv2VisionModel`]. It is used to instantiate a AIMv2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a si...
Aimv2VisionConfig
python
ray-project__ray
python/ray/_private/worker.py
{ "start": 12224, "end": 45210 }
class ____: """A class used to define the control flow of a worker process. Note: The methods in this class are considered unexposed to the user. The functions outside of this class are considered exposed. Attributes: node (ray._private.node.Node): The node this worker is attached ...
Worker
python
great-expectations__great_expectations
great_expectations/core/freshness_diagnostics.py
{ "start": 3594, "end": 4016 }
class ____(_ParentFreshnessDiagnostics): parent_error_class: ClassVar[Type[GreatExpectationsError]] = CheckpointNotAddedError children_error_classes: ClassVar[Tuple[Type[GreatExpectationsError], ...]] = ( ValidationDefinitionNotAddedError, ) raise_for_error_class: ClassVar[Type[ResourceFreshness...
CheckpointFreshnessDiagnostics
python
Textualize__textual
docs/examples/widgets/header_app_title.py
{ "start": 80, "end": 357 }
class ____(App): def compose(self) -> ComposeResult: yield Header() def on_mount(self) -> None: self.title = "Header Application" self.sub_title = "With title and sub-title" if __name__ == "__main__": app = HeaderApp() app.run()
HeaderApp
python
spack__spack
lib/spack/spack/variant.py
{ "start": 1343, "end": 8661 }
class ____: """Represents a variant definition, created by the ``variant()`` directive. There can be multiple definitions of the same variant, and they are given precedence by order of appearance in the package. Later definitions have higher precedence. Similarly, definitions in derived classes have hi...
Variant
python
doocs__leetcode
solution/2500-2599/2569.Handling Sum Queries After Update/Solution.py
{ "start": 1808, "end": 2263 }
class ____: def handleQuery( self, nums1: List[int], nums2: List[int], queries: List[List[int]] ) -> List[int]: tree = SegmentTree(nums1) s = sum(nums2) ans = [] for op, a, b in queries: if op == 1: tree.modify(1, a + 1, b + 1) elif...
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-postgres/dagster_postgres_tests/test_daemon_cursor_storage.py
{ "start": 264, "end": 563 }
class ____(TestDaemonCursorStorage): __test__ = True @pytest.fixture(scope="function", name="storage") def cursor_storage(self, conn_string): storage = PostgresRunStorage.create_clean_storage(conn_string) assert storage return storage
TestPostgresDaemonCursorStorage
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_tests.py
{ "start": 83084, "end": 84502 }
class ____(TestCase): def test_copy(self) -> None: class Schema(Config): foo = c.MarkdownExtensions() copy.deepcopy(Schema()) copy.deepcopy(self.get_config(IpAddressTest.Schema, {'option': '1.2.3.4:5678'})) copy.deepcopy(IpAddressTest.Schema) copy.deepcopy(IpAdd...
SchemaTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/math_ops/segment_reduction_ops_test.py
{ "start": 1458, "end": 3574 }
class ____(test.TestCase): def _input(self, input_shape, dtype=dtypes_lib.int32): num_elem = 1 for x in input_shape: num_elem *= x values = np.arange(1, num_elem + 1) np_values = values.reshape(input_shape).astype(dtype.as_numpy_dtype) if dtype == dtypes_lib.bfloat16: # Large numbers ...
SegmentReductionHelper
python
pandas-dev__pandas
asv_bench/benchmarks/libs.py
{ "start": 2219, "end": 2445 }
class ____: def setup(self): class Foo: @cache_readonly def prop(self): return 5 self.obj = Foo() def time_cache_readonly(self): self.obj.prop
CacheReadonly
python
zarr-developers__zarr-python
src/zarr/core/_info.py
{ "start": 411, "end": 2034 }
class ____: """ Visual summary for a Group. Note that this method and its properties is not part of Zarr's public API. """ _name: str _type: Literal["Group"] = "Group" _zarr_format: ZarrFormat _read_only: bool _store_type: str _count_members: int | None = None _count_ar...
GroupInfo
python
django__django
tests/servers/tests.py
{ "start": 1850, "end": 3767 }
class ____(LiveServerBase): server_thread_class = CloseConnectionTestLiveServerThread @classmethod def _make_connections_override(cls): conn = connections[DEFAULT_DB_ALIAS] cls.conn = conn cls.old_conn_max_age = conn.settings_dict["CONN_MAX_AGE"] # Set the connection's CONN_...
LiveServerTestCloseConnectionTest
python
modin-project__modin
modin/config/envvars.py
{ "start": 26545, "end": 26892 }
class ____(EnvironmentVariable, type=int): """ How much memory (in bytes) give to an execution engine. Notes ----- * In Ray case: the amount of memory to start the Plasma object store with. * In Dask case: the amount of memory that is given to each worker depending on CPUs used. """ va...
Memory
python
pydantic__pydantic
pydantic/types.py
{ "start": 45265, "end": 46258 }
class ____(Generic[SecretType]): def __init__(self, secret_value: SecretType) -> None: self._secret_value: SecretType = secret_value def get_secret_value(self) -> SecretType: """Get the secret value. Returns: The secret value. """ return self._secret_value ...
_SecretBase
python
encode__django-rest-framework
tests/test_serializer_nested.py
{ "start": 8551, "end": 8670 }
class ____(models.Model): profile = models.ForeignKey(NestedWriteProfile, on_delete=models.CASCADE)
NestedWritePerson
python
getsentry__sentry
src/sentry/web/frontend/error_404.py
{ "start": 207, "end": 542 }
class ____(View): def dispatch(self, request: HttpRequest, exception=None) -> HttpResponse: # HACK: We don't have any use for exception, but in Django 2.0, # signatures for 4XX handler views were changed to include it. return render_to_response("sentry/404.html", status=404, request=re...
Error404View
python
pytorch__pytorch
torch/distributed/optim/zero_redundancy_optimizer.py
{ "start": 6706, "end": 11183 }
class ____: r""" Information needed by :class:`ZeroRedundancyOptimizer` to overlap with :class:`DistributedDataParallel`. Arguments: world_size (int): world size of the process group being used. Attributes: shard_buckets (bool): if ``True``, then the assignment of each :cla...
_OverlapInfo
python
django-haystack__django-haystack
test_haystack/test_altered_internal_names.py
{ "start": 395, "end": 688 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(model_attr="foo", document=True) name = indexes.CharField(model_attr="author") pub_date = indexes.DateTimeField(model_attr="pub_date") def get_model(self): return MockModel
MockModelSearchIndex
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_tests.py
{ "start": 39544, "end": 44913 }
class ____(TestCase): def test_theme_as_string(self) -> None: class Schema(Config): option = c.Theme() conf = self.get_config(Schema, {'option': "mkdocs"}) assert_type(conf.option, Theme) assert_type(conf.option.name, Optional[str]) self.assertEqual(conf.option.n...
ThemeTest
python
apache__airflow
providers/samba/src/airflow/providers/samba/transfers/gcs_to_samba.py
{ "start": 1337, "end": 9020 }
class ____(BaseOperator): """ Transfer files from a Google Cloud Storage bucket to SMB server. .. code-block:: python with models.DAG( "example_gcs_to_smb", start_date=datetime(2020, 6, 19), schedule=None, ) as dag: # downloads file to media/...
GCSToSambaOperator
python
python-markdown__markdown
markdown/extensions/attr_list.py
{ "start": 2478, "end": 7508 }
class ____(Treeprocessor): BASE_RE = r'\{\:?[ ]*([^\}\n ][^\n]*)[ ]*\}' HEADER_RE = re.compile(r'[ ]+{}[ ]*$'.format(BASE_RE)) BLOCK_RE = re.compile(r'\n[ ]*{}[ ]*$'.format(BASE_RE)) INLINE_RE = re.compile(r'^{}'.format(BASE_RE)) NAME_RE = re.compile(r'[^A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02...
AttrListTreeprocessor
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 54649, "end": 55306 }
class ____(Elemwise): _parameters = ["frame", "name"] _defaults = {"name": no_default} _keyword_only = ["name"] operation = M.to_frame _filter_passthrough = True @functools.cached_property def unique_partition_mapping_columns_from_shuffle(self): result = set() name_mapping =...
ToFrame
python
tox-dev__tox
src/tox/execute/request.py
{ "start": 601, "end": 2713 }
class ____: """Defines a commands execution request.""" def __init__( # noqa: PLR0913 self, cmd: Sequence[str | Path], cwd: Path, env: dict[str, str], stdin: StdinSource, run_id: str, allow: list[str] | None = None, ) -> None: """ Cre...
ExecuteRequest
python
pytorch__pytorch
torch/_dynamo/compiled_autograd.py
{ "start": 8309, "end": 9493 }
class ____: def __init__(self) -> None: self.custom_function_name_counter: Counter[str] = Counter() def add( self, name: str, fn: Callable[..., Any], is_custom_function: bool, is_traceable: bool, ) -> str: if is_custom_function: name = "Cp...
OpNamespace
python
ZoranPandovski__al-go-rithms
machine_learning/Neural_Networks/python/xor_nn.py
{ "start": 106, "end": 1361 }
class ____: def __init__(self, x, y): self.neurons = 5 self.x = x self.y = y self.err = 1 self.w1 = np.random.random((x.shape[1], self.neurons)) self.w2 = np.random.random((self.neurons, y.shape[1])) def forward(self): self.a1 = sigmoid(self.x @ self.w1) ...
NN
python
PrefectHQ__prefect
src/integrations/prefect-azure/prefect_azure/credentials.py
{ "start": 10154, "end": 14275 }
class ____(Block): """ Block used to manage Cosmos DB authentication with Azure. Azure authentication is handled via the `azure` module through a connection string. Args: connection_string: Includes the authorization information required. Example: Load stored Azure Cosmos DB cr...
AzureCosmosDbCredentials
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1386845, "end": 1387739 }
class ____(sgqlc.types.Type, Node): """An emoji reaction to a particular piece of content.""" __schema__ = github_schema __field_names__ = ("content", "created_at", "database_id", "reactable", "user") content = sgqlc.types.Field(sgqlc.types.non_null(ReactionContent), graphql_name="content") """Iden...
Reaction
python
pyca__cryptography
src/cryptography/x509/base.py
{ "start": 1268, "end": 2509 }
class ____(Exception): def __init__(self, msg: str, oid: ObjectIdentifier) -> None: super().__init__(msg) self.oid = oid def _reject_duplicate_extension( extension: Extension[ExtensionType], extensions: list[Extension[ExtensionType]], ) -> None: # This is quadratic in the number of ext...
AttributeNotFound
python
PrefectHQ__prefect
src/prefect/_vendor/croniter/croniter.py
{ "start": 4592, "end": 4688 }
class ____(CroniterError): """Unable to find next/prev timestamp match"""
CroniterBadDateError
python
Textualize__textual
docs/examples/widgets/markdown_viewer.py
{ "start": 1693, "end": 2007 }
class ____(App): def compose(self) -> ComposeResult: markdown_viewer = MarkdownViewer(EXAMPLE_MARKDOWN, show_table_of_contents=True) markdown_viewer.code_indent_guides = False yield markdown_viewer if __name__ == "__main__": app = MarkdownExampleApp() app.run()
MarkdownExampleApp
python
django-debug-toolbar__django-debug-toolbar
debug_toolbar/toolbar.py
{ "start": 1019, "end": 7133 }
class ____: # for internal testing use only _created = Signal() store: BaseStore = None def __init__( self, request: HttpRequest, get_response: GetResponse, request_id: str | None = None, ): self.request = request self.config = dt_settings.get_config(...
DebugToolbar
python
pytest-dev__pytest
src/_pytest/subtests.py
{ "start": 1749, "end": 2150 }
class ____: """The values passed to Subtests.test() that are included in the test report.""" msg: str | None kwargs: Mapping[str, Any] def _to_json(self) -> dict[str, Any]: return dataclasses.asdict(self) @classmethod def _from_json(cls, d: dict[str, Any]) -> Self: return cls(...
SubtestContext
python
kamyu104__LeetCode-Solutions
Python/number-of-good-leaf-nodes-pairs.py
{ "start": 1649, "end": 2502 }
class ____(object): def countPairs(self, root, distance): """ :type root: TreeNode :type distance: int :rtype: int """ def dfs(distance, node): if not node: return 0, collections.Counter() if not node.left and not node.right: ...
Solution2
python
spack__spack
lib/spack/spack/vendor/pyrsistent/_pmap.py
{ "start": 192, "end": 14717 }
class ____(object): """ Persistent map/dict. Tries to follow the same naming conventions as the built in dict where feasible. Do not instantiate directly, instead use the factory functions :py:func:`m` or :py:func:`pmap` to create an instance. Was originally written as a very close copy of the Clo...
PMap
python
kamyu104__LeetCode-Solutions
Python/find-the-largest-area-of-square-inside-two-rectangles.py
{ "start": 761, "end": 1227 }
class ____(object): def largestSquareArea(self, bottomLeft, topRight): """ :type bottomLeft: List[List[int]] :type topRight: List[List[int]] :rtype: int """ return max(max(min(min(topRight[i][0], topRight[j][0])-max(bottomLeft[i][0], bottomLeft[j][0]), min(topRight[i]...
Solution2
python
encode__starlette
starlette/websockets.py
{ "start": 8004, "end": 8336 }
class ____: def __init__(self, code: int = 1000, reason: str | None = None) -> None: self.code = code self.reason = reason or "" async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await send({"type": "websocket.close", "code": self.code, "reason": self.reason}...
WebSocketClose
python
kamyu104__LeetCode-Solutions
Python/maximum-performance-of-a-team.py
{ "start": 65, "end": 665 }
class ____(object): def maxPerformance(self, n, speed, efficiency, k): """ :type n: int :type speed: List[int] :type efficiency: List[int] :type k: int :rtype: int """ MOD = 10**9 + 7 result, s_sum = 0, 0 min_heap = [] for e, s ...
Solution
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 56337, "end": 56630 }
class ____(_TestOnlySetsInBinaryOps, __TestCase): def setUp(self): self.set = set((1, 2, 3)) self.other = (2, 4, 6) self.otherIsIterable = True super().setUp() #------------------------------------------------------------------------------
TestOnlySetsTuple
python
openai__openai-python
src/openai/types/chat/chat_completion_content_part_refusal_param.py
{ "start": 237, "end": 467 }
class ____(TypedDict, total=False): refusal: Required[str] """The refusal message generated by the model.""" type: Required[Literal["refusal"]] """The type of the content part."""
ChatCompletionContentPartRefusalParam
python
django__django
tests/model_forms/tests.py
{ "start": 32676, "end": 33302 }
class ____(SimpleTestCase): def test_validates_with_replaced_field_not_specified(self): form = IncompleteCategoryFormWithFields( data={"name": "some name", "slug": "some-slug"} ) self.assertIs(form.is_valid(), True) def test_validates_with_replaced_field_excluded(self): ...
ValidationTest
python
pytorch__pytorch
test/distributed/test_c10d_pypg.py
{ "start": 4990, "end": 5255 }
class ____(dist._Work): """ Dummy work that is used to test blocking the current stream. """ def __init__(self): super().__init__() self.future_ = torch.futures.Future() def get_future(self): return self.future_
BlockWork
python
pennersr__django-allauth
tests/apps/socialaccount/providers/trello/tests.py
{ "start": 239, "end": 659 }
class ____(OAuthTestsMixin, TestCase): provider_id = TrelloProvider.id def get_mocked_response(self): return [ MockedResponse( HTTPStatus.OK, r""" {"id": "123", "email": "raymond.penners@example.com", "username": "pennersr", "name": "Raymond"} """, ...
TrelloTests
python
tiangolo__fastapi
docs_src/body_multiple_params/tutorial002.py
{ "start": 236, "end": 490 }
class ____(BaseModel): username: str full_name: Union[str, None] = None @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item, user: User): results = {"item_id": item_id, "item": item, "user": user} return results
User
python
Textualize__textual
docs/examples/widgets/data_table.py
{ "start": 553, "end": 844 }
class ____(App): def compose(self) -> ComposeResult: yield DataTable() def on_mount(self) -> None: table = self.query_one(DataTable) table.add_columns(*ROWS[0]) table.add_rows(ROWS[1:]) app = TableApp() if __name__ == "__main__": app.run()
TableApp