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
networkx__networkx
networkx/algorithms/tests/test_cycles.py
{ "start": 25929, "end": 30906 }
class ____: @classmethod def setup_class(cls): cls.nodes = [0, 1, 2, 3] cls.edges = [(-1, 0), (0, 1), (1, 0), (1, 0), (2, 1), (3, 1)] def test_graph_nocycle(self): G = nx.Graph(self.edges) pytest.raises(nx.exception.NetworkXNoCycle, nx.find_cycle, G, self.nodes) def tes...
TestFindCycle
python
getsentry__sentry
src/sentry/relocation/services/relocation_export/model.py
{ "start": 230, "end": 500 }
class ____(pydantic.BaseModel): relocation_uuid: str requesting_region_name: str replying_region_name: str org_slug: str # encrypted_bytes excluded, as receivers are expected to manually read them from filestore.
RelocationExportReplyWithExportParameters
python
walkccc__LeetCode
solutions/3472. Longest Palindromic Subsequence After at Most K Operations/3472.py
{ "start": 0, "end": 744 }
class ____: # Similar to 516. Longest Palindromic Subsequence def longestPalindromicSubsequence(self, s: str, k: int) -> int: @functools.lru_cache(None) def dp(i: int, j: int, op: int) -> int: """Returns the length of LPS(s[i..j]) with at most `op` operations.""" if i > j: return 0 ...
Solution
python
doocs__leetcode
solution/0700-0799/0702.Search in a Sorted Array of Unknown Size/Solution.py
{ "start": 182, "end": 570 }
class ____: def search(self, reader: "ArrayReader", target: int) -> int: r = 1 while reader.get(r) < target: r <<= 1 l = r >> 1 while l < r: mid = (l + r) >> 1 if reader.get(mid) >= target: r = mid else: ...
Solution
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 11754, "end": 11857 }
class ____(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
AdminProfile
python
bokeh__bokeh
src/bokeh/server/auth_provider.py
{ "start": 7751, "end": 9588 }
class ____(AuthProvider): ''' A default no-auth AuthProvider. All of the properties of this provider return None. ''' @property def get_user(self): return None @property def get_user_async(self): return None @property def login_url(self): return None ...
NullAuth
python
milvus-io__pymilvus
tests/test_decorators.py
{ "start": 261, "end": 5157 }
class ____: def mock_failure(self, code: grpc.StatusCode): if code in IGNORE_RETRY_CODES: raise MockUnRetriableError(code) if code == MockUnavailableError().code(): raise MockUnavailableError if code == MockDeadlineExceededError().code(): raise MockDeadlin...
TestDecorators
python
h5py__h5py
h5py/tests/test_file.py
{ "start": 8974, "end": 10043 }
class ____(TestCase): """ Feature: File mode can be retrieved via file.mode """ def test_mode_attr(self): """ Mode equivalent can be retrieved via property """ fname = self.mktemp() with File(fname, 'w') as f: self.assertEqual(f.mode, 'r+') with File(fna...
TestModes
python
pytorch__pytorch
torch/fx/passes/shape_prop.py
{ "start": 532, "end": 3294 }
class ____(NamedTuple): # TensorMetadata is a structure containing pertinent information # about a tensor within a PyTorch program. # General Tensor metadata shape: torch.Size dtype: torch.dtype requires_grad: bool stride: tuple[int, ...] memory_format: Optional[torch.memory_format] ...
TensorMetadata
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F811_30.py
{ "start": 76, "end": 209 }
class ____: """A.""" def foo(self) -> None: """Foo.""" bar = foo def bar(self) -> None: """Bar."""
A
python
numba__numba
numba/core/untyped_passes.py
{ "start": 15891, "end": 17159 }
class ____(FunctionPass): """A pass to canonicalize loop exit by splitting it from function exit. """ _name = "canonicalize_loop_exit" def __init__(self): FunctionPass.__init__(self) def run_pass(self, state): fir = state.func_ir cfg = compute_cfg_from_blocks(fir.blocks) ...
CanonicalizeLoopExit
python
pandas-dev__pandas
asv_bench/benchmarks/dtypes.py
{ "start": 3173, "end": 3559 }
class ____: def setup(self): self.ext_dtype = pd.Int64Dtype() self.np_dtype = np.dtype("int64") def time_is_extension_array_dtype_true(self): is_extension_array_dtype(self.ext_dtype) def time_is_extension_array_dtype_false(self): is_extension_array_dtype(self.np_dtype) fr...
CheckDtypes
python
huggingface__transformers
src/transformers/models/bark/generation_configuration_bark.py
{ "start": 9574, "end": 11209 }
class ____(GenerationConfig): model_type = "fine_acoustics" def __init__( self, temperature=1.0, max_fine_history_length=512, max_fine_input_length=1024, n_fine_codebooks=8, **kwargs, ): """Class that holds a generation configuration for [`BarkFineMod...
BarkFineGenerationConfig
python
pytorch__pytorch
test/dynamo/test_ctx_manager.py
{ "start": 1870, "end": 44532 }
class ____(torch._dynamo.test_case.TestCaseWithNestedGraphBreaks): def test_no_grad(self): def fn1(a, b): x = a + 1 # redundant no_grad should get ignored with torch.no_grad(): x = x + b x = x + 2 return x def fn2(a, b): ...
CtxManagerTests
python
great-expectations__great_expectations
great_expectations/data_context/types/base.py
{ "start": 15938, "end": 21211 }
class ____(AbstractConfig): def __init__( # noqa: C901, PLR0912, PLR0913, PLR0915 # FIXME CoP self, class_name, name: Optional[str] = None, id: Optional[str] = None, module_name=None, credentials=None, assets=None, base_directory=None, glob_di...
DataConnectorConfig
python
astropy__astropy
astropy/visualization/wcsaxes/tests/test_images.py
{ "start": 48119, "end": 49960 }
class ____(BaseLowLevelWCS): @property def pixel_n_dim(self): return 2 @property def world_n_dim(self): return 2 @property def world_axis_physical_types(self): return [ "pos.eq.ra", "pos.eq.dec", ] @property def world_axis_units(...
EquatorialArcsecWCS
python
Pylons__pyramid
src/pyramid/registry.py
{ "start": 287, "end": 4303 }
class ____(Components, dict): """A registry object is an :term:`application registry`. It is used by the framework itself to perform mappings of URLs to view callables, as well as servicing other various framework duties. A registry has its own internal API, but this API is rarely used by Pyramid a...
Registry
python
django__django
django/contrib/auth/apps.py
{ "start": 454, "end": 1467 }
class ____(AppConfig): default_auto_field = "django.db.models.AutoField" name = "django.contrib.auth" verbose_name = _("Authentication and Authorization") def ready(self): post_migrate.connect( create_permissions, dispatch_uid="django.contrib.auth.management.create_permi...
AuthConfig
python
tensorflow__tensorflow
tensorflow/python/ops/losses/util_test.py
{ "start": 957, "end": 1875 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testGetRegularizationLoss(self): # Empty regularization collection should evaluate to 0.0. with self.cached_session(): self.assertEqual(0.0, util.get_regularization_loss().eval()) # Loss should sum. ops.add_to_collection( op...
LossesUtilTest
python
sqlalchemy__sqlalchemy
test/sql/test_returning.py
{ "start": 24419, "end": 29439 }
class ____(fixtures.TablesTest): __requires__ = ("insert_returning",) run_define_tables = "each" __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): from sqlalchemy.sql import ColumnElement from sqlalchemy.ext.compiler import compiles counter = i...
InsertReturnDefaultsTest
python
dask__dask
dask/_expr.py
{ "start": 36556, "end": 39349 }
class ____(Expr): """A sequence of expressions This is used to be able to optimize multiple collections combined, e.g. when being computed simultaneously with ``dask.compute((Expr1, Expr2))``. """ def __getitem__(self, other): return self.operands[other] def _layer(self) -> dict: ...
_ExprSequence
python
python-poetry__poetry
tests/vcs/git/git_fixture.py
{ "start": 133, "end": 283 }
class ____(typing.NamedTuple): path: Path repo: dulwich.repo.Repo init_commit: str middle_commit: str head_commit: str
TempRepoFixture
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pydoclint/DOC502_google.py
{ "start": 0, "end": 3685 }
class ____(Exception): ... # DOC502 def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. Raises: Fast...
FasterThanLightError
python
lepture__authlib
authlib/jose/errors.py
{ "start": 958, "end": 1367 }
class ____(JoseError): error = "invalid_encryption_algorithm_for_ECDH_1PU_with_key_wrapping" def __init__(self): description = ( "In key agreement with key wrapping mode ECDH-1PU algorithm " "only supports AES_CBC_HMAC_SHA2 family encryption algorithms" ) super()...
InvalidEncryptionAlgorithmForECDH1PUWithKeyWrappingError
python
getsentry__sentry
src/sentry/utils/warnings.py
{ "start": 2286, "end": 3404 }
class ____: """ Add-only set structure for storing unique warnings. """ def __init__(self) -> None: self.__warnings: dict[tuple[object, ...], Warning] = {} def __contains__(self, value: object) -> bool: assert isinstance(value, Warning) return self.__get_key(value) in self....
WarningSet
python
dask__distributed
distributed/core.py
{ "start": 2380, "end": 3255 }
class ____(IOError): pass logger = logging.getLogger(__name__) def raise_later(exc): def _raise(*args, **kwargs): raise exc return _raise tick_maximum_delay = parse_timedelta( dask.config.get("distributed.admin.tick.limit"), default="ms" ) LOG_PDB = dask.config.get("distributed.admin.pdb...
RPCClosed
python
cython__cython
tests/run/function_as_method_py_T494.py
{ "start": 248, "end": 325 }
class ____(object): """ >>> C.plus1(1) 2 """ plus1 = f_plus
C
python
pypa__pip
src/pip/_vendor/rich/errors.py
{ "start": 569, "end": 642 }
class ____(ConsoleError): """Alt screen mode was required."""
NoAltScreen
python
django-extensions__django-extensions
tests/testapp/models.py
{ "start": 13954, "end": 14014 }
class ____(models.Model): photo = models.FileField()
Photo
python
aimacode__aima-python
search.py
{ "start": 17343, "end": 25944 }
class ____(Problem): """ The problem of moving the Hybrid Wumpus Agent from one place to other """ def __init__(self, initial, goal, allowed, dimrow): """ Define goal state and initialize a problem """ super().__init__(initial, goal) self.dimrow = dimrow self.goal = goal ...
PlanRoute
python
spack__spack
lib/spack/spack/oci/opener.py
{ "start": 1425, "end": 1826 }
class ____(spack.tokenize.TokenBase): AUTH_PARAM = rf"({token}){BWS}={BWS}({token}|{quoted_string})" # TOKEN68 = r"([A-Za-z0-9\-._~+/]+=*)" # todo... support this? TOKEN = rf"{tchar}+" EQUALS = rf"{BWS}={BWS}" COMMA = rf"{OWS},{OWS}" SPACE = r" +" EOF = r"$" ANY = r"." WWW_AUTHENTICAT...
WwwAuthenticateTokens
python
doocs__leetcode
solution/2800-2899/2847.Smallest Number With Given Digit Product/Solution.py
{ "start": 0, "end": 338 }
class ____: def smallestNumber(self, n: int) -> str: cnt = [0] * 10 for i in range(9, 1, -1): while n % i == 0: n //= i cnt[i] += 1 if n > 1: return "-1" ans = "".join(str(i) * cnt[i] for i in range(2, 10)) return ans if...
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B017_0.py
{ "start": 247, "end": 1985 }
class ____(unittest.TestCase): def evil_raises(self) -> None: with self.assertRaises(Exception): raise Exception("Evil I say!") def also_evil_raises(self) -> None: with self.assertRaises(BaseException): raise Exception("Evil I say!") def context_manager_raises(self)...
Foobar
python
apache__airflow
providers/standard/src/airflow/providers/standard/example_dags/example_hitl_operator.py
{ "start": 1257, "end": 6025 }
class ____(BaseNotifier): """Simple notifier to demonstrate HITL notification without setup any connection.""" template_fields = ("message",) def __init__(self, message: str) -> None: self.message = message def notify(self, context: Context) -> None: url = HITLOperator.generate_link_t...
LocalLogNotifier
python
google__jax
tests/dynamic_api_test.py
{ "start": 21801, "end": 36955 }
class ____(jtu.JaxTestCase): def test_jvp_broadcast(self): @jax.jit def fn(n, x): return lax.broadcast_in_dim(x, (n,), ()) outer_jaxpr = jax.make_jaxpr( lambda x, t: jax.jvp(lambda y: fn(3, y), (x,), (t,)) )(3., 4.) # { lambda ; a:f32[] b:f32[]. let # c:f32[3] d:f32[3] = pji...
DynamicShapeAutodiffTest
python
python-pillow__Pillow
Tests/test_file_tiff.py
{ "start": 36249, "end": 36890 }
class ____: def test_fd_leak(self, tmp_path: Path) -> None: tmpfile = tmp_path / "temp.tif" # this is an mmaped file. with Image.open("Tests/images/uint16_1_4660.tif") as im: im.save(tmpfile) im = Image.open(tmpfile) fp = im.fp assert not fp.closed ...
TestFileTiffW32
python
pytorch__pytorch
test/pytest_shard_custom.py
{ "start": 908, "end": 2307 }
class ____: def __init__(self, config): self.config = config def pytest_report_collectionfinish(self, config, items) -> str: """Log how many and which items are tested in this shard.""" msg = f"Running {len(items)} items in this shard" if config.getoption("print_items"): ...
PytestShardPlugin
python
ZoranPandovski__al-go-rithms
data_structures/Tree/Binary-tree/python/BinaryTree.py
{ "start": 38, "end": 277 }
class ____: def __init__(self, key): self.right = None self.left = None self.key = key def addLeftChild(self, node): self.left = node def addRightChild(self, node): self.right = node
Node
python
getsentry__sentry
src/sentry_plugins/twilio/plugin.py
{ "start": 3315, "end": 6531 }
class ____(CorePluginMixin, NotificationPlugin): version = sentry.VERSION description = DESCRIPTION resource_links = [ ( "Documentation", "https://github.com/getsentry/sentry/blob/master/src/sentry_plugins/twilio/Twilio_Instructions.md", ), ("Report Issue", "h...
TwilioPlugin
python
plotly__plotly.py
plotly/graph_objs/contour/_textfont.py
{ "start": 233, "end": 9936 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "contour" _path_str = "contour.textfont" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @property de...
Textfont
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/serializers/test_data_source_serializer.py
{ "start": 558, "end": 2081 }
class ____(TestCase): def test_serialize(self) -> None: snuba_query = create_snuba_query( SnubaQuery.Type.ERROR, Dataset.Events, "hello", "count()", timedelta(minutes=1), timedelta(minutes=1), None, ) type_na...
TestDataSourceSerializer
python
python-markdown__markdown
markdown/extensions/sane_lists.py
{ "start": 1729, "end": 2150 }
class ____(Extension): """ Add sane lists to Markdown. """ def extendMarkdown(self, md): """ Override existing Processors. """ md.parser.blockprocessors.register(SaneOListProcessor(md.parser), 'olist', 40) md.parser.blockprocessors.register(SaneUListProcessor(md.parser), 'ulist', 30) ...
SaneListExtension
python
pandas-dev__pandas
pandas/tests/indexes/period/test_constructors.py
{ "start": 25525, "end": 25997 }
class ____: def test_constructor_cant_cast_period(self): msg = "Cannot cast PeriodIndex to dtype float64" with pytest.raises(TypeError, match=msg): Series(period_range("2000-01-01", periods=10, freq="D"), dtype=float) def test_constructor_cast_object(self): pi = period_range...
TestSeriesPeriod
python
huggingface__transformers
src/transformers/models/mobilenet_v1/modeling_mobilenet_v1.py
{ "start": 8118, "end": 10379 }
class ____(MobileNetV1PreTrainedModel): def __init__(self, config: MobileNetV1Config) -> None: super().__init__(config) self.num_labels = config.num_labels self.mobilenet_v1 = MobileNetV1Model(config) last_hidden_size = self.mobilenet_v1.layer[-1].convolution.out_channels ...
MobileNetV1ForImageClassification
python
redis__redis-py
redis/commands/search/reducers.py
{ "start": 2078, "end": 2378 }
class ____(Reducer): """ Return the value for the nth percentile within the range of values for the field within the group. """ NAME = "QUANTILE" def __init__(self, field: str, pct: float) -> None: super().__init__(field, str(pct)) self._field = field
quantile
python
realpython__materials
python-class/employee.py
{ "start": 32, "end": 1021 }
class ____: company = "Example, Inc." def __init__(self, name, birth_date): self.name = name self.birth_date = birth_date @property def birth_date(self): return self._birth_date @birth_date.setter def birth_date(self, value): self._birth_date = datetime.fromiso...
Employee
python
getsentry__sentry
tests/sentry/issue_detection/test_m_n_plus_one_db_detector.py
{ "start": 875, "end": 8320 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self._settings = get_detection_settings() def find_problems( self, event: dict[str, Any], settings: dict[DetectorType, Any] | None = None ) -> list[PerformanceProblem]: detector_settings = settings or self._setti...
MNPlusOneDBDetectorTest
python
apache__airflow
providers/edge3/src/airflow/providers/edge3/models/edge_worker.py
{ "start": 1942, "end": 3565 }
class ____(str, Enum): """Status of a Edge Worker instance.""" STARTING = "starting" """Edge Worker is in initialization.""" RUNNING = "running" """Edge Worker is actively running a task.""" IDLE = "idle" """Edge Worker is active and waiting for a task.""" SHUTDOWN_REQUEST = "shutdown r...
EdgeWorkerState
python
kubernetes-client__python
kubernetes/base/dynamic/discovery.py
{ "start": 16871, "end": 16965 }
class ____(json.JSONEncoder): def default(self, o): return o.to_dict()
CacheEncoder
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 8018, "end": 8403 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): n_missing = metafeatures.get_value("NumberOfFeaturesWithMissingValues") n_total = float(metafeatures["NumberOfFeatures"](X, y, logger).value) return float(n_missing / n_total) @metafeatures.define("NumberOfMissingValue...
PercentageOfFeaturesWithMissingValues
python
urllib3__urllib3
src/urllib3/exceptions.py
{ "start": 9492, "end": 9844 }
class ____(HTTPError): """Raised by assert_header_parsing, but we convert it to a log.warning statement.""" def __init__( self, defects: list[MessageDefect], unparsed_data: bytes | str | None ) -> None: message = f"{defects or 'Unknown'}, unparsed data: {unparsed_data!r}" super().__...
HeaderParsingError
python
keras-team__keras
keras/src/metrics/confusion_metrics_test.py
{ "start": 32127, "end": 35620 }
class ____(testing.TestCase): def test_config(self): s_obj = metrics.PrecisionAtRecall( 0.4, num_thresholds=100, class_id=12, name="precision_at_recall_1" ) self.assertEqual(s_obj.name, "precision_at_recall_1") self.assertLen(s_obj.variables, 4) self.assertEqual(s...
PrecisionAtRecallTest
python
walkccc__LeetCode
solutions/1360. Number of Days Between Two Dates/1360.py
{ "start": 0, "end": 549 }
class ____: def daysBetweenDates(self, date1: str, date2: str) -> int: days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def isLeapYear(year: int) -> bool: return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 def daysFrom1971(date: str) -> int: year, month, day = map(int, dat...
Solution
python
kamyu104__LeetCode-Solutions
Python/minimize-the-maximum-difference-of-pairs.py
{ "start": 96, "end": 751 }
class ____(object): def minimizeMax(self, nums, p): """ :type nums: List[int] :type p: int :rtype: int """ def check(x): i = cnt = 0 while i+1 < len(nums) and cnt < p: if nums[i+1]-nums[i] <= x: i += 1 ...
Solution
python
sympy__sympy
sympy/stats/drv.py
{ "start": 5943, "end": 6076 }
class ____(DiscreteDomain, SingleDomain): def as_boolean(self): return Contains(self.symbol, self.set)
SingleDiscreteDomain
python
wntrblm__nox
nox/_options.py
{ "start": 1233, "end": 21827 }
class ____(str): __slots__ = () ReuseVenvType = Literal["no", "yes", "never", "always"] options = _option_set.OptionSet( description="Nox is a Python automation toolkit.", add_help=False ) options.add_groups( _option_set.OptionGroup( "general", "General options", "These are gener...
DefaultStr
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vectorizers.py
{ "start": 13885, "end": 14218 }
class ____(_VectorizerConfigCreate): vectorizer: Union[Vectorizers, _EnumLikeStr] = Field( default=Vectorizers.TEXT2VEC_VOYAGEAI, frozen=True, exclude=True ) dimensions: Optional[int] model: Optional[str] baseURL: Optional[str] truncate: Optional[bool] vectorizeClassName: bool
_Text2VecVoyageConfig
python
huggingface__transformers
src/transformers/models/table_transformer/modeling_table_transformer.py
{ "start": 32571, "end": 37570 }
class ____(TableTransformerPreTrainedModel): """ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a [`TableTransformerEncoderLayer`]. The encoder updates the flattened feature map through multiple self-attention layers. Small tweak for Table Transforme...
TableTransformerEncoder
python
huggingface__transformers
examples/pytorch/token-classification/run_ner.py
{ "start": 3800, "end": 26658 }
class ____: """ Arguments pertaining to what data we are going to input our model for training and eval. """ task_name: Optional[str] = field(default="ner", metadata={"help": "The name of the task (ner, pos...)."}) dataset_name: Optional[str] = field( default=None, metadata={"help": "The na...
DataTrainingArguments
python
tiangolo__fastapi
scripts/sponsors.py
{ "start": 1022, "end": 1118 }
class ____(BaseModel): sponsorEntity: SponsorEntity tier: Tier
SponsorshipAsMaintainerNode
python
graphql-python__graphene
graphene/tests/issues/test_356.py
{ "start": 231, "end": 698 }
class ____(graphene.Union): class Meta: types = (SomeTypeOne, SomeTypeTwo) def test_issue(): class Query(graphene.ObjectType): things = relay.ConnectionField(MyUnion) with raises(Exception) as exc_info: graphene.Schema(query=Query) assert str(exc_info.value) == ( "Que...
MyUnion
python
ray-project__ray
python/ray/tests/test_task_events_2.py
{ "start": 1072, "end": 11278 }
class ____: def __init__(self): raise ValueError("Actor init is expected to fail") def ready(self): pass def test_actor_creation_task_ok(shutdown_only): ray.init(_system_config=_SYSTEM_CONFIG) a = ActorOk.remote() ray.get(a.ready.remote()) def verify(): tasks = list_t...
ActorInitFailed
python
davidhalter__jedi
test/completion/dynamic_params.py
{ "start": 1786, "end": 2123 }
class ____(from_class(1),): pass # ----------------- # comprehensions # ----------------- def from_comprehension(foo): #? int() float() return foo [from_comprehension(1.0) for n in (1,)] [from_comprehension(n) for n in (1,)] # ----------------- # lambdas # ----------------- #? int() x_lambda = lambda x...
Foo
python
ansible__ansible
test/units/module_utils/basic/test_run_command.py
{ "start": 1054, "end": 1855 }
class ____(BytesIO): def __init__(self, *args, **kwargs): fh = kwargs.pop('fh', None) super(SpecialBytesIO, self).__init__(*args, **kwargs) self.fh = fh def fileno(self): return self.fh # We need to do this because some of our tests create a new value for stdout and stderr ...
SpecialBytesIO
python
kamyu104__LeetCode-Solutions
Python/count-good-numbers.py
{ "start": 541, "end": 767 }
class ____(object): def countGoodNumbers(self, n): """ :type n: int :rtype: int """ MOD = 10**9 + 7 return pow(5, (n+1)//2%(MOD-1), MOD)*pow(4, n//2%(MOD-1), MOD) % MOD
Solution2
python
redis__redis-py
tests/test_connection_pool.py
{ "start": 28247, "end": 28589 }
class ____: @pytest.fixture() def r(self, request): return _get_client(redis.Redis, request, single_connection_client=False) def test_multi_connection_command(self, r): assert not r.connection assert r.set("a", "123") assert r.get("a") == b"123" @pytest.mark.onlynoncluster...
TestMultiConnectionClient
python
joke2k__faker
faker/providers/phone_number/__init__.py
{ "start": 317, "end": 5825 }
class ____(BaseProvider): country_calling_codes: ElementsType[str] = ( "+93", "+358 18", "+355", "+213", "+1 684", "+376", "+244", "+1 264", "+1 268", "+54", "+374", "+297", "+247", "+61", "+672 1...
Provider
python
google__pytype
pytype/pyi/parser_test.py
{ "start": 90481, "end": 91511 }
class ____(parser_test_base.ParserTestBase): def check(self, src, expected): tree = self.parse(src) all_ = [x for x in tree.constants if x.name == "__all__"] pyval = all_[0].value if all_ else None self.assertEqual(pyval, expected) def test_basic(self): self.check( """ __all__ = ...
AllTest
python
getsentry__sentry
tests/sentry/integrations/test_pipeline.py
{ "start": 28380, "end": 29734 }
class ____(IntegrationTestCase): provider = GitlabIntegrationProvider external_id = "dummy_id-123" def test_different_user_same_external_id(self, *args) -> None: new_user = self.create_user() self.setUp() integration = self.create_provider_integration( provider=self.prov...
GitlabFinishPipelineTest
python
sqlalchemy__sqlalchemy
test/orm/test_instrumentation.py
{ "start": 759, "end": 10236 }
class ____(fixtures.ORMTest): def fixture(self): return Table( "t", MetaData(), Column("id", Integer, primary_key=True), Column("type", Integer), Column("x", Integer), Column("y", Integer), ) def register(self, cls, canary)...
InitTest
python
python__mypy
mypyc/test/test_tuplename.py
{ "start": 249, "end": 1044 }
class ____(unittest.TestCase): def setUp(self) -> None: self.inst_a = RInstance(ClassIR("A", "__main__")) self.inst_b = RInstance(ClassIR("B", "__main__")) def test_names(self) -> None: assert RTuple([int_rprimitive, int_rprimitive]).unique_id == "T2II" assert RTuple([list_rprim...
TestTupleNames
python
xlwings__xlwings
xlwings/constants.py
{ "start": 64333, "end": 65178 }
class ____: xlAboveAverageCondition = 12 # from enum XlFormatConditionType xlBlanksCondition = 10 # from enum XlFormatConditionType xlCellValue = 1 # from enum XlFormatConditionType xlColorScale = 3 # from enum XlFormatConditionType xlDatabar = 4 # from enum XlFormatConditionType xlErrorsCo...
FormatConditionType
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py
{ "start": 4028, "end": 5405 }
class ____(AwsBaseWaiterTrigger): """ Asynchronously poll the boto3 API and wait for the JobFlow to finish terminating. :param job_flow_id: ID of the EMR Job Flow to terminate :param waiter_delay: The amount of time in seconds to wait between attempts. :param waiter_max_attempts: The maximum number...
EmrTerminateJobFlowTrigger
python
streamlit__streamlit
lib/streamlit/testing/v1/element_tree.py
{ "start": 36016, "end": 36421 }
class ____(Element): proto: ArrowProto = field(repr=False) def __init__(self, proto: ArrowProto, root: ElementTree) -> None: self.key = None self.proto = proto self.root = root self.type = "arrow_table" @property def value(self) -> PandasDataframe: return datafr...
Table
python
kubernetes-client__python
kubernetes/client/models/v2_horizontal_pod_autoscaler_behavior.py
{ "start": 383, "end": 4379 }
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...
V2HorizontalPodAutoscalerBehavior
python
pypa__pip
tests/lib/test_lib.py
{ "start": 2625, "end": 8652 }
class ____: def run_stderr_with_prefix( self, script: PipTestEnvironment, prefix: str, **kwargs: Any ) -> None: """ Call run() that prints stderr with the given prefix. """ text = f"{prefix}: hello, world\\n" command = f'import sys; sys.stderr.write("{text}")' ...
TestPipTestEnvironment
python
kamyu104__LeetCode-Solutions
Python/find-the-original-typed-string-i.py
{ "start": 288, "end": 653 }
class ____(object): def possibleStringCount(self, word): """ :type word: str :rtype: int """ result = 1 curr = 0 for i in xrange(len(word)): curr += 1 if i+1 == len(word) or word[i+1] != word[i]: result += curr-1 ...
Solution2
python
django__django
django/core/serializers/pyyaml.py
{ "start": 1245, "end": 2302 }
class ____(PythonSerializer): """Convert a queryset to YAML.""" internal_use_only = False def _value_from_field(self, obj, field): # A nasty special case: base YAML doesn't support serialization of time # types (as opposed to dates or datetimes, which it does support). # Since we w...
Serializer
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/util/_collections.py
{ "start": 17545, "end": 19277 }
class ____(ScopedRegistry[_T]): """A :class:`.ScopedRegistry` that uses a ``threading.local()`` variable for storage. """ def __init__(self, createfunc: Callable[[], _T]): self.createfunc = createfunc self.registry = threading.local() def __call__(self) -> _T: try: ...
ThreadLocalRegistry
python
joke2k__faker
faker/providers/address/fr_CA/__init__.py
{ "start": 71, "end": 1859 }
class ____(EnCaProvider): # Most of the parts are identical to en_CA, we simply override those who are not shared between the two. city_prefixes = ( "Ville", "Baie", "Saint-", "Sainte-", "Mont-", "La", "Lac-", "L'", "L'Île-", ) c...
Provider
python
google__pytype
pytype/pyc/opcodes.py
{ "start": 12439, "end": 12533 }
class ____(OpcodeWithArg): _FLAGS = HAS_ARGUMENT | HAS_JREL __slots__ = ()
POP_JUMP_IF_FALSE
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 102731, "end": 103045 }
class ____(Literal): def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: if instring[loc] == self.firstMatchChar: return loc + 1, self.match raise ParseException(instring, loc, self.errmsg, self) ParserElement._literalStringClass = Literal
_SingleCharLiteral
python
apache__airflow
airflow-core/tests/unit/utils/test_process_utils.py
{ "start": 1336, "end": 3501 }
class ____: @staticmethod def _ignores_sigterm(child_pid, child_setup_done): def signal_handler(unused_signum, unused_frame): pass signal.signal(signal.SIGTERM, signal_handler) child_pid.value = os.getpid() child_setup_done.release() while True: t...
TestReapProcessGroup
python
numba__numba
numba/tests/test_types.py
{ "start": 22504, "end": 22737 }
class ____(TestCase): """Tests the use of the Type metaclass init correctly setting the flag on the `is_internal` attr of a concrete Type class """ source_lines = """ from numba.core import types
TestIsInternalTypeMarker
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_text_editor_code_execution_tool_result_block_param.py
{ "start": 1129, "end": 1470 }
class ____(TypedDict, total=False): content: Required[Content] tool_use_id: Required[str] type: Required[Literal["text_editor_code_execution_tool_result"]] cache_control: Optional[BetaCacheControlEphemeralParam] """Create a cache control breakpoint at this content block."""
BetaTextEditorCodeExecutionToolResultBlockParam
python
doocs__leetcode
solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution3.py
{ "start": 0, "end": 414 }
class ____: def minInsertions(self, s: str) -> int: n = len(s) f = [[0] * n for _ in range(n)] for k in range(2, n + 1): for i in range(n - k + 1): j = i + k - 1 if s[i] == s[j]: f[i][j] = f[i + 1][j - 1] else: ...
Solution
python
mwaskom__seaborn
seaborn/_stats/order.py
{ "start": 801, "end": 2259 }
class ____(Stat): """ Replace observations with percentile values. Parameters ---------- k : list of numbers or int If a list of numbers, this gives the percentiles (in [0, 100]) to compute. If an integer, compute `k` evenly-spaced percentiles between 0 and 100. For example,...
Perc
python
pennersr__django-allauth
allauth/account/stages.py
{ "start": 627, "end": 1576 }
class ____: key: str # Set in subclasses urlname: Optional[str] = None login: Login def __init__(self, controller, request, login): if not self.key: raise ValueError() self.controller = controller self.request = request self.login = login self.state ...
LoginStage
python
joke2k__faker
faker/providers/phone_number/lv_LV/__init__.py
{ "start": 49, "end": 184 }
class ____(PhoneNumberProvider): formats = ( "+371 ########", "+(371) ########", "+371########", )
Provider
python
tensorflow__tensorflow
third_party/xla/xla/python/profiler/profile_data_test.py
{ "start": 781, "end": 6373 }
class ____(absltest.TestCase): def test_find_plane_with_name(self): profile = profile_data.ProfileData.from_text_proto(""" planes { name: "a" } planes { name: "b" } """) self.assertEqual(profile.find_plane_with_name('a').name, 'a') self.assertEqual(profile.find_plane_with_name('b'...
ProfileDataTest
python
django__django
tests/db_functions/text/test_ord.py
{ "start": 205, "end": 1238 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.john = Author.objects.create(name="John Smith", alias="smithj") cls.elena = Author.objects.create(name="Élena Jordan", alias="elena") cls.rhonda = Author.objects.create(name="Rhonda") def test_basic(self): author...
OrdTests
python
davidhalter__jedi
test/completion/classes.py
{ "start": 6176, "end": 6319 }
class ____(): def __init__(self, obj): self.obj = obj def __getattr__(self, name): return getattr(self.obj, name)
Wrapper
python
charliermarsh__ruff
crates/ruff_python_ast/generate.py
{ "start": 3618, "end": 5007 }
class ____: name: str variant: str ty: str doc: str | None fields: list[Field] | None derives: list[str] custom_source_order: bool source_order: list[str] | None def __init__(self, group: Group, node_name: str, node: dict[str, Any]) -> None: self.name = node_name sel...
Node
python
walkccc__LeetCode
solutions/689. Maximum Sum of 3 Non-Overlapping Subarrays/689.py
{ "start": 0, "end": 1030 }
class ____: def maxSumOfThreeSubarrays(self, nums: list[int], k: int) -> list[int]: n = len(nums) - k + 1 # sums[i] := sum(nums[i..i + k)) sums = [0] * n # l[i] := the index in [0..i] that has the maximum sums[i] l = [0] * n # r[i] := the index in [i..n) that has the maximum sums[i] r = [0...
Solution
python
realpython__materials
pyqt-calculator-tutorial/pycalc/pycalc.py
{ "start": 359, "end": 2262 }
class ____(QMainWindow): """PyCalc's main window (GUI or view).""" def __init__(self): super().__init__() self.setWindowTitle("PyCalc") self.setFixedSize(WINDOW_SIZE, WINDOW_SIZE) self.generalLayout = QVBoxLayout() centralWidget = QWidget(self) centralWidget.setL...
PyCalcWindow
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/name_mangling.py
{ "start": 67, "end": 169 }
class ____(Foo): __address = None #: a member having mangled-like name _Baz__email = None
Bar
python
has2k1__plotnine
plotnine/mapping/evaluation.py
{ "start": 713, "end": 5913 }
class ____: """ Stage allows you evaluating mapping at more than one stage You can evaluate an expression of a variable in a dataframe, and later evaluate an expression that modifies the values mapped to the scale. Parameters ---------- start : str | array_like | scalar Aesthet...
stage
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 2465, "end": 2593 }
class ____(models.Manager): def get_queryset(self): return super().get_queryset().exclude(id=1)
AlternativePollManager
python
docker__docker-py
docker/types/containers.py
{ "start": 7955, "end": 23806 }
class ____(dict): def __init__(self, version, binds=None, port_bindings=None, lxc_conf=None, publish_all_ports=False, links=None, privileged=False, dns=None, dns_search=None, volumes_from=None, network_mode=None, restart_policy=None, cap_add=None, ...
HostConfig
python
encode__django-rest-framework
tests/test_serializer_nested.py
{ "start": 8462, "end": 8551 }
class ____(models.Model): address = models.CharField(max_length=100)
NestedWriteProfile