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
walkccc__LeetCode
solutions/1536. Minimum Swaps to Arrange a Binary Grid/1536.py
{ "start": 0, "end": 647 }
class ____: def minSwaps(self, grid: list[list[int]]) -> int: n = len(grid) ans = 0 # suffixZeros[i] := the number of suffix zeros in the i-th row suffixZeros = [n if 1 not in row else row[::-1].index(1) for row in grid] for i in range(n): neededZeros = n - 1 - i # Get the first row w...
Solution
python
openai__openai-python
src/openai/types/responses/tool_param.py
{ "start": 6293, "end": 8151 }
class ____(TypedDict, total=False): type: Required[Literal["image_generation"]] """The type of the image generation tool. Always `image_generation`.""" background: Literal["transparent", "opaque", "auto"] """Background type for the generated image. One of `transparent`, `opaque`, or `auto`. Defaul...
ImageGeneration
python
astropy__astropy
astropy/table/bst.py
{ "start": 3452, "end": 14710 }
class ____: """ A basic binary search tree in pure Python, used as an engine for indexing. Parameters ---------- data : Table Sorted columns of the original table row_index : Column object Row numbers corresponding to data columns unique : bool Whether the values...
BST
python
tiangolo__fastapi
tests/test_get_model_definitions_formfeed_escape.py
{ "start": 489, "end": 4428 }
class ____(BaseModel): id: str address: Address app = FastAPI() client = TestClient(app) @app.get("/facilities/{facility_id}") def get_facility(facility_id: str) -> Facility: ... openapi_schema = { "components": { "schemas": { "Address": { # NOTE: the description o...
Facility
python
Netflix__metaflow
test/extensions/packages/card_via_extinit/metaflow_extensions/card_via_extinit/plugins/cards/card_b/__init__.py
{ "start": 42, "end": 359 }
class ____(MetaflowCard): type = "card_ext_init_b" def __init__(self, options={"key": "task"}, **kwargs): self._key = options["key"] if "key" in options else "task" def render(self, task): task_data = task[self._key].data return "%s" % task_data CARDS = [TestMockCard]
TestMockCard
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/concepts/types/object_type.py
{ "start": 70, "end": 433 }
class ____: def __init__(self, num): assert num % 2 == 0 self.num = num EvenDagsterType = PythonObjectDagsterType(EvenType, name="EvenDagsterType") # end_object_type # start_use_object_type @op def double_even(even_num: EvenDagsterType) -> EvenDagsterType: # type: ignore return EvenType(eve...
EvenType
python
getsentry__sentry
src/sentry/sentry_metrics/indexer/postgres/postgres_v2.py
{ "start": 12854, "end": 13007 }
class ____(StaticStringIndexer): def __init__(self) -> None: super().__init__(CachingIndexer(indexer_cache, PGStringIndexerV2()))
PostgresIndexer
python
tensorflow__tensorflow
tensorflow/lite/python/interpreter_test.py
{ "start": 20988, "end": 26413 }
class ____(test_util.TensorFlowTestCase): def setUp(self): super(InterpreterDelegateTest, self).setUp() self._delegate_file = resource_loader.get_path_to_datafile( 'testdata/test_delegate.so') self._model_file = resource_loader.get_path_to_datafile( 'testdata/permute_float.tflite') #...
InterpreterDelegateTest
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_resolver.py
{ "start": 823, "end": 2253 }
class ____(TestCase): def setUp(self): self.owner = create_user(username="owner", password="test") self.tester = create_user(username="tester", password="test") self.pip = fixture.get( Project, slug="pip", users=[self.owner], main_language_proj...
ResolverBase
python
doocs__leetcode
solution/1000-1099/1019.Next Greater Node In Linked List/Solution.py
{ "start": 151, "end": 614 }
class ____: def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]: nums = [] while head: nums.append(head.val) head = head.next stk = [] n = len(nums) ans = [0] * n for i in range(n - 1, -1, -1): while stk and stk[-1] <= ...
Solution
python
Netflix__metaflow
metaflow/plugins/aws/secrets_manager/aws_secrets_manager_secrets_provider.py
{ "start": 444, "end": 594 }
class ____(MetaflowException): """Raised when the response from AWS Secrets Manager contains duplicate keys"""
MetaflowAWSSecretsManagerDuplicateKey
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 73428, "end": 73953 }
class ____(GeneratedAirbyteSource): @public def __init__(self, name: str, since: str, api_key: str): """Airbyte Source for Delighted. Args: name (str): The name of the destination. since (str): The date from which you'd like to replicate the data api_key (str...
DelightedSource
python
getsentry__sentry
src/sentry/status_checks/warnings.py
{ "start": 190, "end": 1170 }
class ____(StatusCheck): def __init__(self, warning_set: WarningSet) -> None: self.__warning_set = warning_set def check(self) -> list[Problem]: if self.__warning_set: return [ Problem( "There {} {} {} with your system configuration.".format( ...
WarningStatusCheck
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 109036, "end": 111874 }
class ____(Expr): _projection_passthrough = False _expr_cls: AnyType | None = None def _divisions(self): if {df.npartitions for df in self.args} == {1}: divs = [] for df in self.args: divs.extend(list(df.divisions)) try: return min...
MaybeAlignPartitions
python
astropy__astropy
astropy/units/tests/test_quantity_ufuncs.py
{ "start": 50085, "end": 51549 }
class ____: """Test 'outer' methods for ufuncs Just a few spot checks, since it uses the same code as the regular ufunc call """ def test_one_argument_ufunc_outer(self): # one argument cannot be used s = np.arange(10.0) * u.radian with pytest.raises(ValueError): ...
TestUfuncOuter
python
python-openxml__python-docx
src/docx/oxml/simpletypes.py
{ "start": 8230, "end": 8273 }
class ____(XsdInt): pass
ST_DecimalNumber
python
kamyu104__LeetCode-Solutions
Python/maximum-xor-of-two-non-overlapping-subtrees.py
{ "start": 81, "end": 837 }
class ____(object): def __init__(self, bit_length): self.__root = {} self.__bit_length = bit_length def insert(self, num): node = self.__root for i in reversed(xrange(self.__bit_length)): curr = (num>>i) & 1 if curr not in node: no...
Trie
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_write_sheet_pr.py
{ "start": 301, "end": 1561 }
class ____(unittest.TestCase): """ Test the Worksheet _write_sheet_pr() method. """ def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def test_write_sheet_pr_fit_to_page(self): """Test the _write_sheet_pr() m...
TestWriteSheetPr
python
ray-project__ray
python/ray/train/tests/lightning_test_utils.py
{ "start": 3677, "end": 5743 }
class ____(pl.LightningModule): def __init__(self, lr: float, layer_1: int, layer_2: int): super(LightningMNISTClassifier, self).__init__() self.lr = lr # mnist images are (1, 28, 28) (channels, width, height) self.layer_1 = torch.nn.Linear(28 * 28, layer_1) self.layer_2 = t...
LightningMNISTClassifier
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/metadata.py
{ "start": 3778, "end": 3992 }
class ____(graphene.ObjectType): runId = graphene.NonNull(graphene.String) class Meta: interfaces = (GrapheneMetadataEntry,) name = "PipelineRunMetadataEntry"
GraphenePipelineRunMetadataEntry
python
google__pytype
pytype/errors/error_types.py
{ "start": 3553, "end": 3832 }
class ____(InvalidParameters): """E.g. an arg "x" is passed to a function that doesn't have an "x" param.""" def __init__(self, sig, passed_args, ctx, extra_keywords): super().__init__(sig, passed_args, ctx) self.extra_keywords = tuple(extra_keywords)
WrongKeywordArgs
python
dask__dask
dask/cache.py
{ "start": 206, "end": 1980 }
class ____(Callback): """Use cache for computation Examples -------- >>> cache = Cache(1e9) # doctest: +SKIP The cache can be used locally as a context manager around ``compute`` or ``get`` calls: >>> with cache: # doctest: +SKIP ... result = x.compute() You can also regis...
Cache
python
jazzband__django-simple-history
simple_history/tests/external/models.py
{ "start": 510, "end": 740 }
class ____(models.Model): history = HistoricalRecords( inherit=True, app="external", custom_model_name=lambda x: f"Audit{x}" ) class Meta: abstract = True app_label = "external"
AbstractExternal3
python
PyCQA__pyflakes
pyflakes/checker.py
{ "start": 7048, "end": 7369 }
class ____(Definition): """A definition created for all Python builtins.""" def __init__(self, name): super().__init__(name, None) def __repr__(self): return '<{} object {!r} at 0x{:x}>'.format( self.__class__.__name__, self.name, id(self) )
Builtin
python
dagster-io__dagster
helm/dagster/schema/schema/charts/dagster/subschema/rabbitmq.py
{ "start": 336, "end": 504 }
class ____(BaseModel): enabled: bool image: ExternalImage rabbitmq: RabbitMQConfiguration service: Service volumePermissions: VolumePermissions
RabbitMQ
python
catalyst-team__catalyst
examples/self_supervised/src/runner.py
{ "start": 766, "end": 8956 }
class ____(IRunner): """IRunner for experiments with contrastive model. Args: input_key: key in ``runner.batch`` dict mapping for model input target_key: key in ``runner.batch`` dict mapping for target loss_key: key for ``runner.batch_metrics`` to store criterion loss output aug...
ISelfSupervisedRunner
python
Pylons__pyramid
tests/test_path.py
{ "start": 2109, "end": 2900 }
class ____(unittest.TestCase): def _callFUT(self, *arg, **kw): from pyramid.path import caller_package return caller_package(*arg, **kw) def test_it_level_1(self): import tests result = self._callFUT(1) self.assertEqual(result, tests) def test_it_level_2(self): ...
TestCallerPackage
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_S.py
{ "start": 26117, "end": 27290 }
class ____(Benchmark): r""" Shubert 1 objective function. This class defines the Shubert 1 [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Shubert01}}(x) = \prod_{i=1}^{n}\left(\sum_{j=1}^{5} ...
Shubert01
python
pypa__pip
src/pip/_vendor/rich/prompt.py
{ "start": 246, "end": 336 }
class ____(Exception): """Exception base class for prompt related errors."""
PromptError
python
django__django
tests/admin_views/models.py
{ "start": 22834, "end": 23020 }
class ____(models.Model): """ Model whose show_delete in admin change_view has been disabled Refs #10057. """ name = models.CharField(max_length=255)
UndeletableObject
python
tox-dev__tox
src/tox/config/loader/ini/replace.py
{ "start": 582, "end": 3911 }
class ____(ReplaceReference): def __init__(self, conf: Config, loader: IniLoader) -> None: self.conf = conf self.loader = loader def __call__(self, value: str, conf_args: ConfigLoadArgs) -> str | None: # noqa: C901 # a return value of None indicates could not replace pattern = ...
ReplaceReferenceIni
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/extension1/package.py
{ "start": 228, "end": 745 }
class ____(Package): """A package which extends another package""" homepage = "http://www.example.com" url = "http://www.example.com/extension1-1.0.tar.gz" extends("extendee") version("1.0", md5="0123456789abcdef0123456789abcdef") version("2.0", md5="abcdef0123456789abcdef0123456789") de...
Extension1
python
pytorch__pytorch
torch/distributed/_tools/fsdp2_mem_tracker.py
{ "start": 3977, "end": 25408 }
class ____(MemTracker): """ A ``TorchDispatchMode`` based context manager that extends ``torch.distributed._tools.mem_tracker.MemTracker`` to track and categorize the peak memory and module-wise memory usage of FSDP modules. It tracks the peak memory usage across all the devices of all the FSDP modules...
FSDPMemTracker
python
anthropics__anthropic-sdk-python
src/anthropic/types/tool_bash_20250124_param.py
{ "start": 320, "end": 692 }
class ____(TypedDict, total=False): name: Required[Literal["bash"]] """Name of the tool. This is how the tool will be called by the model and in `tool_use` blocks. """ type: Required[Literal["bash_20250124"]] cache_control: Optional[CacheControlEphemeralParam] """Create a cache control br...
ToolBash20250124Param
python
sqlalchemy__sqlalchemy
test/dialect/mysql/test_compiler.py
{ "start": 53815, "end": 56375 }
class ____(testing.AssertsCompiledSQL): def setup_test(self): self.table = table( "mytable", column("myid", String), column("name", String) ) def test_regexp_match(self): self.assert_compile( self.table.c.myid.regexp_match("pattern"), "mytable.myid RE...
RegexpCommon
python
vyperlang__vyper
vyper/venom/passes/memmerging.py
{ "start": 685, "end": 2912 }
class ____: # abstract "copy" operation which contains a list of copy instructions # and can fuse them into a single copy operation. dst: int src: int length: int insts: list[IRInstruction] @classmethod def memzero(cls, dst, length, insts): # factory method to simplify creation ...
_Copy
python
pyca__cryptography
src/cryptography/x509/extensions.py
{ "start": 33873, "end": 34776 }
class ____(ExtensionType): oid = ExtensionOID.INHIBIT_ANY_POLICY def __init__(self, skip_certs: int) -> None: if not isinstance(skip_certs, int): raise TypeError("skip_certs must be an integer") if skip_certs < 0: raise ValueError("skip_certs must be a non-negative inte...
InhibitAnyPolicy
python
openai__openai-python
tests/api_resources/beta/test_assistants.py
{ "start": 469, "end": 9435 }
class ____: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: assistant = client.beta.assistants.create( model="gpt-4o", ) assert_matches_type(Assistan...
TestAssistants
python
Pylons__pyramid
tests/test_config/test_assets.py
{ "start": 30536, "end": 33292 }
class ____: def test_get_filename(self): source = self._makeOne('') self.assertEqual( source.get_filename('test_assets.py'), os.path.join(here, 'test_assets.py'), ) def test_get_filename_with_prefix(self): source = self._makeOne('test_assets.py') ...
AssetSourceIntegrationTests
python
astropy__astropy
astropy/cosmology/_src/tests/io/test_row.py
{ "start": 391, "end": 4976 }
class ____(ToFromTestMixinBase): """ Tests for a Cosmology[To/From]Format with ``format="astropy.row"``. This class will not be directly called by :mod:`pytest` since its name does not begin with ``Test``. To activate the contained tests this class must be inherited in a subclass. Subclasses must de...
ToFromRowTestMixin
python
pypa__setuptools
setuptools/_vendor/typeguard/_importhook.py
{ "start": 1459, "end": 3061 }
class ____(SourceFileLoader): @staticmethod def source_to_code( data: Buffer | str | ast.Module | ast.Expression | ast.Interactive, path: Buffer | str | PathLike[str] = "<string>", ) -> CodeType: if isinstance(data, (ast.Module, ast.Expression, ast.Interactive)): tree = d...
TypeguardLoader
python
cython__cython
Cython/Build/Cache.py
{ "start": 1945, "end": 6855 }
class ____: def __init__(self, path, cache_size=None): if path is None: self.path = join_path(get_cython_cache_dir(), "compiler") else: self.path = path self.cache_size = cache_size if cache_size is not None else MAX_CACHE_SIZE if not os.path.exists(self.path)...
Cache
python
scrapy__scrapy
scrapy/core/downloader/webclient.py
{ "start": 664, "end": 2982 }
class ____(HTTPClient): delimiter = b"\n" def __init__(self): warnings.warn( "ScrapyHTTPPageGetter is deprecated and will be removed in a future Scrapy version.", category=ScrapyDeprecationWarning, stacklevel=2, ) super().__init__() def connectio...
ScrapyHTTPPageGetter
python
mkdocstrings__mkdocstrings
src/mkdocstrings/_internal/inventory.py
{ "start": 354, "end": 2856 }
class ____: """Inventory item.""" def __init__( self, name: str, domain: str, role: str, uri: str, priority: int = 1, dispname: str | None = None, ): """Initialize the object. Arguments: name: The item name. do...
InventoryItem
python
pytorch__pytorch
test/distributed/tensor/test_utils.py
{ "start": 30735, "end": 33226 }
class ____(LocalDTensorTestBase): @property def world_size(self) -> int: return 32 @with_comms def test_StridedShard_to_shard_order(self): with LocalTensorMode(ranks=self.world_size): mesh = DeviceMesh("cpu", torch.arange(self.world_size).view(2, 2, 2, 2, 2)) sha...
Test_StridedShard_with_shard_order
python
huggingface__transformers
src/transformers/models/janus/configuration_janus.py
{ "start": 9752, "end": 14620 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`JanusModel`]. It is used to instantiate an Janus model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configur...
JanusConfig
python
pikepdf__pikepdf
src/pikepdf/jbig2.py
{ "start": 1355, "end": 4213 }
class ____(JBIG2DecoderInterface): """JBIG2 decoder implementation.""" def __init__(self, *, subprocess_run=run, creationflags=CREATION_FLAGS): """Initialize the decoder.""" self._run = subprocess_run self._creationflags = creationflags def check_available(self) -> None: ""...
JBIG2Decoder
python
openai__openai-python
src/openai/types/beta/chatkit/chat_session_chatkit_configuration_param.py
{ "start": 794, "end": 1070 }
class ____(TypedDict, total=False): enabled: bool """Enables chat users to access previous ChatKit threads. Defaults to true.""" recent_threads: int """Number of recent ChatKit threads users have access to. Defaults to unlimited when unset. """
History
python
tornadoweb__tornado
tornado/test/iostream_test.py
{ "start": 1395, "end": 7278 }
class ____(AsyncTestCase): # We want to run these tests with both AsyncHTTPTestCase and AsyncHTTPSTestCase, # but this leads to some tricky inheritance situations. We want this class's # get_app, but the test classes's get_http_port and fetch. There's no way to make # the method resolution order to do w...
TestIOStreamWebMixin
python
pytorch__pytorch
torch/distributed/checkpoint/metadata.py
{ "start": 832, "end": 3271 }
class ____: """Properties used to create :class:`Tensor`""" # Regular tensor fields dtype: torch.dtype = field(default_factory=torch.get_default_dtype) # This field is deprecated. layout: torch.layout = field(default=torch.strided) # This field is deprecated. requires_grad: bool = False ...
TensorProperties
python
mamba-org__mamba
docs/source/tools/mermaid.py
{ "start": 1054, "end": 1738 }
class ____(nodes.General, nodes.Inline, nodes.Element): pass def figure_wrapper(directive, node, caption): figure_node = nodes.figure("", node) if "align" in node: figure_node["align"] = node.attributes.pop("align") parsed = nodes.Element() directive.state.nested_parse(ViewList([caption],...
mermaid
python
pytorch__pytorch
torch/_export/serde/schema.py
{ "start": 14668, "end": 14816 }
class ____: # name is not the unique identifier of the node name: Annotated[str, 10] node: Annotated[Node, 20] @dataclass
ExternKernelNode
python
facebookresearch__faiss
tests/test_rabitq.py
{ "start": 61126, "end": 65910 }
class ____(unittest.TestCase): """Test IndexIVFRaBitQ with multi-bit support.""" def do_test_ivf_basic_operations(self, metric, nb_bits, qb): """Test IVF train/add/search pipeline.""" ds = create_test_dataset(d=128, nb=500, nq=20, nt=300) k = 10 nlist = 16 # Create IVF ...
TestMultiBitIndexIVFRaBitQ
python
pypa__pip
src/pip/_internal/distributions/wheel.py
{ "start": 392, "end": 1364 }
class ____(AbstractDistribution): """Represents a wheel distribution. This does not need any preparation as wheels can be directly unpacked. """ @property def build_tracker_id(self) -> str | None: return None def get_metadata_distribution(self) -> BaseDistribution: """Loads th...
WheelDistribution
python
ray-project__ray
rllib/examples/_old_api_stack/policy/random_policy.py
{ "start": 402, "end": 3214 }
class ____(Policy): """Hand-coded policy that returns random actions.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Whether for compute_actions, the bounds given in action_space # should be ignored (default: False). This is to test action-clipping ...
RandomPolicy
python
pytorch__pytorch
test/dynamo/test_higher_order_ops.py
{ "start": 220319, "end": 223216 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[3, 3]", L_v_: "f32[3, 3]"): l_x_ = L_x_ l_v_ = L_v_ _set_fwd_grad_enabled = torch._C._set_fwd_grad_enabled(False); _set_fwd_grad_enabled = None _jvp_increment_nesting = torch._C._functorch._jvp_increment_nesting(); _jvp_inc...
GraphModule
python
kamyu104__LeetCode-Solutions
Python/maximum-score-from-grid-operations.py
{ "start": 1499, "end": 2849 }
class ____(object): def maximumScore(self, grid): """ :type grid: List[List[int]] :rtype: int """ prefix = [0]*(len(grid)+1) for i in xrange(len(grid)): prefix[i+1] = prefix[i]+grid[i][0] # dp[0][i]: the maximum score from 0 to the current column, ...
Solution2
python
joke2k__faker
faker/providers/ssn/no_NO/__init__.py
{ "start": 775, "end": 3297 }
class ____(SsnProvider): scale1 = (3, 7, 6, 1, 8, 9, 4, 5, 2) scale2 = (5, 4, 3, 2, 7, 6, 5, 4, 3, 2) def ssn(self, dob: Optional[str] = None, gender: Optional[SexLiteral] = None) -> str: """ Returns 11 character Norwegian personal identity code (Fødselsnummer). A Norwegian persona...
Provider
python
spyder-ide__spyder
spyder/plugins/externalterminal/widgets/run_conf.py
{ "start": 4035, "end": 8324 }
class ____(RunExecutorConfigurationGroup): """External terminal shell run configuration options.""" def __init__( self, parent, context: Context, input_extension: str, input_metadata: RunConfigurationMetadata ): super().__init__(parent, context, input_extension, inpu...
GenericExternalTerminalShConfiguration
python
neetcode-gh__leetcode
python/0167-two-sum-ii-input-array-is-sorted.py
{ "start": 0, "end": 355 }
class ____: def twoSum(self, numbers: List[int], target: int) -> List[int]: l, r = 0, len(numbers) - 1 while l < r: curSum = numbers[l] + numbers[r] if curSum > target: r -= 1 elif curSum < target: l += 1 else: ...
Solution
python
ray-project__ray
release/ray_release/tests/test_cluster_manager.py
{ "start": 1325, "end": 1845 }
class ____: def __init__( self, callback: Callable[[], None], finish_after: float, before: APIDict, after: APIDict, ): self.callback = callback self.finish_after = time.monotonic() + finish_after self.before = before self.after = after ...
_DelayedResponse
python
django__django
tests/model_formsets/models.py
{ "start": 5939, "end": 6161 }
class ____(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) parent = models.ForeignKey(UUIDPKParent, models.CASCADE)
UUIDPKChild
python
ray-project__ray
doc/source/templates/03_serving_stable_diffusion/app.py
{ "start": 1159, "end": 1894 }
class ____: def __init__(self): model_id = "stabilityai/stable-diffusion-2" scheduler = EulerDiscreteScheduler.from_pretrained( model_id, subfolder="scheduler" ) self.pipe = StableDiffusionPipeline.from_pretrained( model_id, scheduler=scheduler, revision="fp1...
StableDiffusionV2
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_lookup.py
{ "start": 38387, "end": 38806 }
class ____(int): def __init__(self, value: int, /) -> None: if not isinstance(value, int): raise TypeError @given(...) def test_from_type_resolves_required_posonly_args(n: CustomInteger): # st.builds() does not infer for positional arguments, but st.from_type() # does. See e.g. https:...
CustomInteger
python
matplotlib__matplotlib
lib/matplotlib/ticker.py
{ "start": 11464, "end": 12158 }
class ____(Formatter): """ Use an old-style ('%' operator) format string to format the tick. The format string should have a single variable format (%) in it. It will be applied to the value (not the position) of the tick. Negative numeric values (e.g., -1) will use a dash, not a Unicode minus; ...
FormatStrFormatter
python
pytorch__pytorch
torch/fx/experimental/migrate_gradual_types/constraint.py
{ "start": 11986, "end": 13407 }
class ____(Constraint): def __init__( self, maxpool_result, input_var, kernel, padding, stride, dilation, matching_constraint_vars, ): """ :param maxpool_result: the result of maxpool :param input_var: input to convolution ...
CalcMaxPool
python
numba__numba
numba/cuda/tests/cudapy/test_sm.py
{ "start": 426, "end": 2876 }
class ____(CUDATestCase): def test_issue_953_sm_linkage_conflict(self): @cuda.jit(device=True) def inner(): inner_arr = cuda.shared.array(1, dtype=int32) # noqa: F841 @cuda.jit def outer(): outer_arr = cuda.shared.array(1, dtype=int32) # noqa: F841 ...
TestSharedMemoryIssue
python
apache__airflow
airflow-core/src/airflow/timetables/simple.py
{ "start": 3668, "end": 5203 }
class ____(_TrivialTimetable): """ Timetable that schedules continually, while still respecting start_date and end_date. This corresponds to ``schedule="@continuous"``. """ description: str = "As frequently as possible, but only one run at a time." active_runs_limit = 1 # Continuous DAGRuns ...
ContinuousTimetable
python
pdm-project__pdm
src/pdm/cli/commands/venv/backends.py
{ "start": 415, "end": 469 }
class ____(ProjectError): pass
VirtualenvCreateError
python
pydata__xarray
xarray/tests/test_sparse.py
{ "start": 17913, "end": 28020 }
class ____: @pytest.fixture(autouse=True) def setUp(self): self.sp_ar = sparse.random((4, 6), random_state=0, density=0.5) self.sp_xr = xr.DataArray( self.sp_ar, coords={"x": range(4)}, dims=("x", "y"), name="foo" ) self.ds_ar = self.sp_ar.todense() self.ds_xr...
TestSparseDataArrayAndDataset
python
sympy__sympy
sympy/solvers/diophantine/diophantine.py
{ "start": 36243, "end": 122444 }
class ____(DiophantineEquationType): """ Representation of the diophantine equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0` where `e` is an even, integer power. Examples ======== >>> from sympy.solvers.diophantine.diophantine import GeneralSumOfEvenPowers >>> from sympy.abc imp...
GeneralSumOfEvenPowers
python
Pylons__pyramid
src/pyramid/authorization.py
{ "start": 958, "end": 1016 }
class ____(_AllPermissionsList): pass
AllPermissionsList
python
ApeWorX__ape
src/ape/cli/choices.py
{ "start": 1522, "end": 2390 }
class ____(click.Choice): """ A ``click.Choice`` for loading account aliases for the active project at runtime. Provide an ``account_type`` to limit the type of account to choose from. Defaults to all account types in ``choices()``. """ name = "alias" def __init__(self, key: _ACCOUNT_TYPE...
Alias
python
mkdocs__mkdocs
mkdocs/tests/utils/utils_tests.py
{ "start": 19142, "end": 21630 }
class ____(unittest.TestCase): def setUp(self): self.log = logging.getLogger('dummy') self.log.propagate = False self.log.setLevel(1) self.counter = utils.CountHandler() self.log.addHandler(self.counter) def tearDown(self): self.log.removeHandler(self.counter) ...
LogCounterTests
python
django__django
tests/transactions/tests.py
{ "start": 19135, "end": 22452 }
class ____(TransactionTestCase): available_apps = ["transactions"] def test_wrap_callable_instance(self): """#20028 -- Atomic must support wrapping callable instances.""" class Callable: def __call__(self): pass # Must not raise an exception transac...
AtomicMiscTests
python
python-attrs__attrs
src/attr/validators.py
{ "start": 20247, "end": 21458 }
class ____: validators = attrib() def __call__(self, inst, attr, value): for v in self.validators: try: v(inst, attr, value) except Exception: # noqa: BLE001, PERF203, S112 continue else: return msg = f"None o...
_OrValidator
python
huggingface__transformers
tests/models/groupvit/test_modeling_groupvit.py
{ "start": 19440, "end": 22356 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (GroupViTModel,) if is_torch_available() else () pipeline_model_mapping = {"feature-extraction": GroupViTModel} if is_torch_available() else {} test_resize_embeddings = False test_attention_outputs = False de...
GroupViTModelTest
python
django__django
tests/migrations/test_migrations_squashed_complex_multi_apps/app2/2_auto.py
{ "start": 35, "end": 182 }
class ____(migrations.Migration): dependencies = [("app2", "1_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
Migration
python
PyCQA__pylint
tests/functional/o/overridden_final_method_py38.py
{ "start": 592, "end": 693 }
class ____(BaseConditional): def my_method(self): # [overridden-final-method] pass
Subclass2
python
catalyst-team__catalyst
examples/detection/callbacks.py
{ "start": 9354, "end": 12849 }
class ____(Callback): """Compute mAP for Object Detection task.""" def __init__( self, num_classes=1, metric_key="mAP", output_type="ssd", iou_threshold=0.5, confidence_threshold=0.5, ): """ Args: num_classes (int): Number of class...
DetectionMeanAveragePrecision
python
doocs__leetcode
solution/3000-3099/3042.Count Prefix and Suffix Pairs I/Solution2.py
{ "start": 0, "end": 123 }
class ____: __slots__ = ["children", "cnt"] def __init__(self): self.children = {} self.cnt = 0
Node
python
fluentpython__example-code-2e
21-async/mojifinder/bottle.py
{ "start": 135868, "end": 150565 }
class ____(object): ''' Parser for stpl templates. ''' _re_cache = {} #: Cache for compiled re patterns # This huge pile of voodoo magic splits python code into 8 different tokens. # 1: All kinds of python strings (trust me, it works) _re_tok = '([urbURB]?(?:\'\'(?!\')|""(?!")|\'{6}|"{6}' \ ...
StplParser
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 914993, "end": 915561 }
class ____(sgqlc.types.Type): """Represents an author of a reaction.""" __schema__ = github_schema __field_names__ = ("cursor", "node", "reacted_at") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field(s...
ReactorEdge
python
tornadoweb__tornado
tornado/locale.py
{ "start": 17661, "end": 18832 }
class ____(Locale): """Locale implementation using tornado's CSV translation format.""" def __init__(self, code: str, translations: Dict[str, Dict[str, str]]) -> None: self.translations = translations super().__init__(code) def translate( self, message: str, plural_...
CSVLocale
python
Pylons__pyramid
tests/test_util.py
{ "start": 36485, "end": 37071 }
class ____(unittest.TestCase): class Dummy: def run(self): # pragma: no cover return 'OK' def _callFUT(self, val): from pyramid.util import is_unbound_method return is_unbound_method(val) def test_bound_method(self): self.assertFalse(self._callFUT(self.Dummy()...
TestUnboundMethods
python
kamyu104__LeetCode-Solutions
Python/build-binary-expression-tree-from-infix-expression.py
{ "start": 66, "end": 219 }
class ____(object): def __init__(self, val=" ", left=None, right=None): self.val = val self.left = left self.right = right
Node
python
PrefectHQ__prefect
tests/utilities/schema_tools/test_validation.py
{ "start": 23642, "end": 24844 }
class ____: def test_prioritize_placeholder_errors(self): errors = [ # error we want to throw away MockValidationError( message="InvalidJSON() is not of type 'string", relative_path=["x"], instance=InvalidJSON(), validat...
TestPrioritizePlaceholderErrors
python
jmcnamara__XlsxWriter
xlsxwriter/contenttypes.py
{ "start": 951, "end": 8980 }
class ____(xmlwriter.XMLwriter): """ A class for writing the Excel XLSX ContentTypes file. """ ########################################################################### # # Public API. # ########################################################################### def __init__(se...
ContentTypes
python
pyca__cryptography
tests/hazmat/primitives/test_ed25519.py
{ "start": 2096, "end": 13101 }
class ____: def test_sign_verify_input(self, backend, subtests): vectors = load_vectors_from_file( os.path.join("asymmetric", "Ed25519", "sign.input"), load_ed25519_vectors, ) for vector in vectors: with subtests.test(): sk = binascii.unhex...
TestEd25519Signing
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_gtk3.py
{ "start": 18903, "end": 21811 }
class ____(backend_tools.ToolHelpBase): def _normalize_shortcut(self, key): """ Convert Matplotlib key presses to GTK+ accelerator identifiers. Related to `FigureCanvasGTK3._get_key`. """ special = { 'backspace': 'BackSpace', 'pagedown': 'Page_Down', ...
HelpGTK3
python
imageio__imageio
imageio/plugins/_tifffile.py
{ "start": 115380, "end": 123046 }
class ____(object): """Sequence of TIFF image file directories.""" def __init__(self, parent): """Initialize instance from file. Read first TiffPage from file. The file position must be at an offset to an offset to a TiffPage. """ self.parent = parent self.pages = [] ...
TiffPages
python
ZoranPandovski__al-go-rithms
puzzles/CollectRubicCube/Python/solve_rubic_cube.py
{ "start": 10629, "end": 10916 }
class ____: def __init__(self, vertexId): self.Id = vertexId self.Neighbors = [] def getId(self): return self.Id def addNeighbor(self, Vertex): self.Neighbors.append(Vertex) def getNeighbors(self): return self.Neighbors
GraphVertex
python
viewflow__viewflow
viewflow/workflow/nodes/split.py
{ "start": 342, "end": 1718 }
class ____(Activation): """Parallel split gateway activation.""" def __init__(self, *args, **kwargs): # noqa D102 self.next_tasks = [] super().__init__(*args, **kwargs) @Activation.status.super() def activate(self): """Calculate nodes list to activate.""" for node, con...
SplitActivation
python
MongoEngine__mongoengine
mongoengine/queryset/visitor.py
{ "start": 321, "end": 633 }
class ____: """Base visitor class for visiting Q-object nodes in a query tree.""" def visit_combination(self, combination): """Called by QCombination objects.""" return combination def visit_query(self, query): """Called by (New)Q objects.""" return query
QNodeVisitor
python
pypa__hatch
backend/src/hatchling/version/source/plugin/interface.py
{ "start": 74, "end": 1852 }
class ____(ABC): # no cov """ Example usage: ```python tab="plugin.py" from hatchling.version.source.plugin.interface import VersionSourceInterface class SpecialVersionSource(VersionSourceInterface): PLUGIN_NAME = "special" ... ``` ```python tab="hooks.py" from hatch...
VersionSourceInterface
python
yaml__pyyaml
lib/yaml/tokens.py
{ "start": 1509, "end": 1557 }
class ____(Token): id = '}'
FlowMappingEndToken
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu.py
{ "start": 65585, "end": 72309 }
class ____(control_flow_ops.XLAControlFlowContext): """A `ControlFlowContext` for nodes inside a TPU inference computation. The primary role of `_TPUInferenceContext` is to indicate the mode of operation and possibly sanity check operators inside a tpu.rewrite_for_inference() computation. """ def __init__...
_TPUInferenceContext
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_shutdown_repository_location.py
{ "start": 669, "end": 1236 }
class ____(ReadonlyGraphQLContextTestMatrix): def test_shutdown_repository_location_permission_failure(self, graphql_context): result = execute_dagster_graphql( graphql_context, SHUTDOWN_REPOSITORY_LOCATION_MUTATION, {"repositoryLocationName": main_repo_location_name()}, ...
TestShutdownRepositoryLocationReadOnly
python
numba__numba
numba/core/typing/npdatetime.py
{ "start": 5156, "end": 5251 }
class ____(TimedeltaOrderedCmpOp): key = operator.lt @infer_global(operator.le)
TimedeltaCmpLt
python
jmcnamara__XlsxWriter
xlsxwriter/test/workbook/test_get_worksheet_by_name.py
{ "start": 299, "end": 2155 }
class ____(unittest.TestCase): """ Test assembling a complete Workbook file. """ def test_get_worksheet_by_name01(self): """Test get_worksheet_by_name()""" fh = StringIO() workbook = Workbook() workbook._set_filehandle(fh) exp = workbook.add_worksheet() ...
TestAssembleWorkbook