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
django__django
django/utils/datastructures.py
{ "start": 10290, "end": 10863 }
class ____: """ Wrap a dict, allowing deferred access to a sub-dict under a given key. The value at ``deferred_key`` must itself be a dict. Accessing ``DeferredSubDict(parent_dict, deferred_key)[key]`` retrieves ``parent_dict[deferred_key][key]`` at access time, so updates to the parent dict ar...
DeferredSubDict
python
h5py__h5py
h5py/tests/test_dataset.py
{ "start": 24005, "end": 24626 }
class ____(BaseDataset): """ Feature: Datasets created from an existing named type """ def test_named(self): """ Named type object works and links the dataset to type """ name = make_name("type") self.f[name] = np.dtype('f8') dt = self.f[name] dset = self.f....
TestCreateNamedType
python
readthedocs__readthedocs.org
readthedocs/projects/filters.py
{ "start": 5723, "end": 6527 }
class ____(ModelFilterSet): """ Project list filter set for project list view. This filter set enables list view sorting using a custom filter, and provides search-as-you-type lookup filter as well. """ slug = FilteredModelChoiceFilter( label=_("Project"), empty_label=_("All pr...
ProjectListFilterSet
python
miyuchina__mistletoe
mistletoe/token.py
{ "start": 577, "end": 2992 }
class ____: """ Base token class. `Token` has two subclasses: * `block_token.BlockToken`, for all block level tokens. A block level token is text which occupies the entire horizontal width of the "page" and is offset for the surrounding sibling block with line breaks. * `span_token.Sp...
Token
python
tqdm__tqdm
tqdm/rich.py
{ "start": 461, "end": 1376 }
class ____(ProgressColumn): """Renders completed/total, e.g. '0.5/2.3 G'.""" def __init__(self, unit_scale=False, unit_divisor=1000): self.unit_scale = unit_scale self.unit_divisor = unit_divisor super().__init__() def render(self, task): """Calculate common unit for complet...
FractionColumn
python
getsentry__sentry
tests/sentry/post_process_forwarder/test_post_process_forwarder.py
{ "start": 1696, "end": 6250 }
class ____(TestCase): def _get_producer(self, cluster_name: str) -> Producer: conf = settings.KAFKA_CLUSTERS[cluster_name]["common"] return Producer(conf) def setUp(self) -> None: super().setUp() self.consumer_and_topic_suffix = uuid.uuid4().hex self.events_topic = f"eve...
PostProcessForwarderTest
python
kamyu104__LeetCode-Solutions
Python/island-perimeter.py
{ "start": 51, "end": 996 }
class ____(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ count, repeat = 0, 0 for i in xrange(len(grid)): for j in xrange(len(grid[i])): if grid[i][j] == 1: count += 1 ...
Solution
python
pytest-dev__pytest-django
pytest_django/plugin.py
{ "start": 25051, "end": 25454 }
class ____: def __init__(self, db_blocker: DjangoDbBlocker) -> None: self._db_blocker = db_blocker def __enter__(self) -> None: pass def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: types.TracebackType | N...
_DatabaseBlockerContextManager
python
kamyu104__LeetCode-Solutions
Python/flatten-binary-tree-to-linked-list.py
{ "start": 661, "end": 998 }
class ____(object): list_head = None # @param root, a tree node # @return nothing, do it in place def flatten(self, root): if root: self.flatten(root.right) self.flatten(root.left) root.right = self.list_head root.left = None self.list_...
Solution2
python
facelessuser__pymdown-extensions
tests/test_extensions/test_slugs.py
{ "start": 559, "end": 1157 }
class ____(util.MdCase): """Test Unicode encoded slugs.""" extension = ['markdown.extensions.toc'] extension_configs = { 'markdown.extensions.toc': { "slugify": slugs.slugify(case="lower", percent_encode=True) } } def test_slug(self): """Test the slug output."""...
TestUslugifyEncoded
python
django__django
tests/annotations/models.py
{ "start": 1052, "end": 1129 }
class ____(Store): chain = models.CharField(max_length=255)
DepartmentStore
python
huggingface__transformers
tests/repo_utils/test_tests_fetcher.py
{ "start": 2116, "end": 7514 }
class ____: ''' This is the docstring. ''' This is the code. It has been updated """ def create_tmp_repo(tmp_dir, models=None): """ Creates a repository in a temporary directory mimicking the structure of Transformers. Uses the list of models provided (which defaults to just `["bert"]`). ...
BertModel
python
joke2k__faker
tests/providers/test_internet.py
{ "start": 31843, "end": 32059 }
class ____(TestFilPh): """Test tl_PH internet provider methods""" def test_slug(self, faker): num_of_samples = 100 for _ in range(num_of_samples): assert faker.slug() != ""
TestTlPh
python
ipython__ipython
IPython/core/prefilter.py
{ "start": 21656, "end": 22287 }
class ____(PrefilterHandler): handler_name = Unicode('magic') esc_strings = List([ESC_MAGIC]) def handle(self, line_info): """Execute magic functions.""" ifun = line_info.ifun the_rest = line_info.the_rest #Prepare arguments for get_ipython().run_line_magic(magic_name, m...
MagicHandler
python
google__pytype
pytype/pyi/entire_file_parser_test.py
{ "start": 133, "end": 396 }
class ____(parser_test_base.ParserTestBase): def test_builtins(self): _, builtins = builtin_stubs.GetPredefinedFile("builtins", "builtins") self.check(builtins, expected=parser_test_base.IGNORE) if __name__ == "__main__": unittest.main()
EntireFileTest
python
walkccc__LeetCode
solutions/375. Guess Number Higher or Lower II/375-2.py
{ "start": 0, "end": 426 }
class ____: def getMoneyAmount(self, n: int) -> int: # dp[i][j] := the minimum money you need to guarantee a win of picking i..j dp = [[0] * (n + 2) for _ in range(n + 2)] for d in range(1, n + 1): for i in range(1, n - d + 1): j = i + d dp[i][j] = math.inf for k in range(i,...
Solution
python
plotly__plotly.py
plotly/graph_objs/layout/_shape.py
{ "start": 235, "end": 48186 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout" _path_str = "layout.shape" _valid_props = { "editable", "fillcolor", "fillrule", "label", "layer", "legend", "legendgroup", "legendgrouptitle", "legendrank", "leg...
Shape
python
facebook__pyre-check
client/commands/server_event.py
{ "start": 718, "end": 1501 }
class ____(enum.Enum): WATCHMAN = "Watchman" BUCK_INTERNAL = "BuckInternal" BUCK_USER = "BuckUser" PYRE = "Pyre" UNKNOWN = "Unknown" def __str__(self) -> str: return self.value @staticmethod def from_string(input_string: str) -> "ErrorKind": for item in ErrorKind: ...
ErrorKind
python
scipy__scipy
scipy/sparse/linalg/_matfuncs.py
{ "start": 5607, "end": 10215 }
class ____(LinearOperator): """ For now, this is limited to products of multiple square matrices. """ def __init__(self, *args, **kwargs): self._structure = kwargs.get('structure', None) for A in args: if len(A.shape) != 2 or A.shape[0] != A.shape[1]: raise V...
ProductOperator
python
PyCQA__isort
isort/_vendored/tomli/_parser.py
{ "start": 6263, "end": 7279 }
class ____: def __init__(self) -> None: # The parsed content of the TOML document self.dict: Dict[str, Any] = {} def get_or_create_nest( self, key: Key, *, access_lists: bool = True, ) -> dict: cont: Any = self.dict for k in key: i...
NestedDict
python
langchain-ai__langchain
libs/standard-tests/tests/unit_tests/test_decorated_tool.py
{ "start": 341, "end": 784 }
class ____(ToolsUnitTests): @property def tool_constructor(self) -> BaseTool: return parrot_multiply_tool @property def tool_invoke_params_example(self) -> dict: """Returns a dictionary representing the "args" of an example tool call. This should NOT be a ToolCall dict - i.e. i...
TestParrotMultiplyToolUnit
python
numpy__numpy
numpy/matrixlib/tests/test_defmatrix.py
{ "start": 8601, "end": 10101 }
class ____: def test_instance_methods(self): a = matrix([1.0], dtype='f8') methodargs = { 'astype': ('intc',), 'clip': (0.0, 1.0), 'compress': ([1],), 'repeat': (1,), 'reshape': (1,), 'swapaxes': (0, 0), 'dot': np.ar...
TestMatrixReturn
python
pennersr__django-allauth
tests/apps/socialaccount/providers/dingtalk/tests.py
{ "start": 244, "end": 942 }
class ____(OAuth2TestsMixin, TestCase): provider_id = DingTalkProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """{ "nick": "aiden", "unionId": "hTaCSb1nM4RXii6jaQvHZqQiEiE", "avatarUrl": "https://static-legacy....
DingTalkTests
python
pandas-dev__pandas
pandas/tests/arrays/categorical/test_indexing.py
{ "start": 10237, "end": 12967 }
class ____: def test_contains(self): # GH#21508 cat = Categorical(list("aabbca"), categories=list("cab")) assert "b" in cat assert "z" not in cat assert np.nan not in cat with pytest.raises(TypeError, match="unhashable type: 'list'"): assert [1] in cat ...
TestContains
python
falconry__falcon
tests/test_after_hooks.py
{ "start": 1362, "end": 1737 }
class ____: def __call__(self, req, resp, resource): fluffiness(req, resp, resource) def cuteness(req, resp, resource, check, postfix=' and cute'): assert resource if resp.text == check: resp.text += postfix def resource_aware_cuteness(req, resp, resource): assert resource cutene...
ResourceAwareFluffiness
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_cloud_run.py
{ "start": 13658, "end": 14735 }
class ____: def test_template_fields(self): operator = CloudRunListJobsOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, limit=2, show_deleted=False ) _assert_common_template_fields(operator.template_fields) @mock.patch(CLOUD_RUN_HOOK_PATH) def test_execu...
TestCloudRunListJobsOperator
python
pypa__pip
src/pip/_vendor/urllib3/exceptions.py
{ "start": 6817, "end": 6912 }
class ____(HTTPError): """The header provided was somehow invalid.""" pass
InvalidHeader
python
doocs__leetcode
solution/1900-1999/1948.Delete Duplicate Folders in System/Solution.py
{ "start": 134, "end": 1328 }
class ____: def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]: root = Trie() for path in paths: cur = root for name in path: if cur.children[name] is None: cur.children[name] = Trie() cur = cur.child...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/fixtures/github.py
{ "start": 673, "end": 5473 }
class ____: BASE_URL = "https://api.github.com" def __init__(self, token: str, repository: str): self.token = token self.repository = repository self.session = requests.Session() self.session.headers.update(self.get_headers(self.token)) self.branches: Optional[list] = N...
GitHubFiller
python
getsentry__sentry
tests/acceptance/test_project_alert_settings.py
{ "start": 153, "end": 1776 }
class ____(AcceptanceTestCase): def setUp(self) -> None: super().setUp() self.user = self.create_user("foo@example.com") self.org = self.create_organization(name="Rowdy Tiger", owner=None) self.team = self.create_team(organization=self.org, name="Mariachi Band") self.project ...
ProjectAlertSettingsTest
python
pandas-dev__pandas
pandas/util/version/__init__.py
{ "start": 1227, "end": 2331 }
class ____: def __repr__(self) -> str: return "-Infinity" def __hash__(self) -> int: return hash(repr(self)) def __lt__(self, other: object) -> bool: return True def __le__(self, other: object) -> bool: return True def __eq__(self, other: object) -> bool: ...
NegativeInfinityType
python
kamyu104__LeetCode-Solutions
Python/remove-all-ones-with-row-and-column-flips-ii.py
{ "start": 68, "end": 1381 }
class ____(object): def removeOnes(self, grid): """ :type grid: List[List[int]] :rtype: int """ rows = [0]*len(grid) mask, bit = 0, 1 for _ in xrange(len(grid[0])): mask += bit bit <<= 1 for i in xrange(len(grid)): r...
Solution
python
getsentry__sentry
src/sentry/grouping/enhancer/__init__.py
{ "start": 13107, "end": 26766 }
class ____: # NOTE: You must add a version to ``VERSIONS`` any time attributes are added # to this class, s.t. no enhancements lacking these attributes are loaded # from cache. # See ``GroupingConfigLoader._get_enhancements`` in src/sentry/grouping/api.py. def __init__( self, rules:...
EnhancementsConfig
python
mozilla__bleach
bleach/_vendor/html5lib/treewalkers/dom.py
{ "start": 115, "end": 1413 }
class ____(base.NonRecursiveTreeWalker): def getNodeDetails(self, node): if node.nodeType == Node.DOCUMENT_TYPE_NODE: return base.DOCTYPE, node.name, node.publicId, node.systemId elif node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): return base.TEXT, node.nodeValu...
TreeWalker
python
django__django
tests/backends/tests.py
{ "start": 25155, "end": 30915 }
class ____(TransactionTestCase): available_apps = ["backends"] def setUp(self): # Create a Reporter. self.r = Reporter.objects.create(first_name="John", last_name="Smith") def test_integrity_checks_on_creation(self): """ Try to create a model instance that violates a FK con...
FkConstraintsTests
python
doocs__leetcode
lcof2/剑指 Offer II 110. 所有路径/Solution.py
{ "start": 0, "end": 398 }
class ____: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: ans = [] def dfs(i, path): if i == len(graph) - 1: ans.append(path.copy()) return for j in graph[i]: path.append(j) dfs(j, p...
Solution
python
ray-project__ray
rllib/examples/_old_api_stack/connectors/self_play_with_policy_checkpoint.py
{ "start": 1273, "end": 4976 }
class ____(RLlibCallback): def __init__(self, checkpoint_dir): self._checkpoint_dir = checkpoint_dir super().__init__() def on_algorithm_init(self, *, algorithm, metrics_logger, **kwargs): policy = Policy.from_checkpoint( self._checkpoint_dir, policy_ids=[OPPONENT_POLICY_ID]...
AddPolicyCallback
python
django__django
tests/admin_utils/admin.py
{ "start": 658, "end": 846 }
class ____(admin.ModelAdmin): inlines = [ArticleInline] site = admin.AdminSite(name="admin") site.register(Article) site.register(ArticleProxy) site.register(Site, SiteAdmin)
SiteAdmin
python
milvus-io__pymilvus
pymilvus/bulk_writer/buffer.py
{ "start": 1032, "end": 1635 }
class ____(json.JSONEncoder): def default(self, obj: object): if isinstance(obj, np.ndarray): return obj.tolist() if isinstance(obj, np.generic): return obj.item() return json.JSONEncoder.default(self, obj) def to_raw_type(obj: dict): keys = obj.keys() for k...
NumpyEncoder
python
django-mptt__django-mptt
mptt/templatetags/mptt_tags.py
{ "start": 9202, "end": 11060 }
class ____(template.Node): def __init__(self, template_nodes, queryset_var): self.template_nodes = template_nodes self.queryset_var = queryset_var def _render_node(self, context, node): bits = [] context.push() for child in node.get_children(): bits.append(se...
RecurseTreeNode
python
apache__airflow
airflow-core/src/airflow/serialization/dag_dependency.py
{ "start": 920, "end": 4327 }
class ____: """ Dataclass for representing dependencies between dags. These are calculated during serialization and attached to serialized dags. The source and target keys store the information of what component depends on what. For an asset related dependency, a root node will have the source val...
DagDependency
python
django-extensions__django-extensions
tests/testapp/models.py
{ "start": 10050, "end": 10228 }
class ____(ShortUUIDTestModel_pk): many = models.ManyToManyField(ShortUUIDTestModel_field) class Meta: app_label = "django_extensions"
ShortUUIDTestManyToManyModel
python
cookiecutter__cookiecutter
cookiecutter/extensions.py
{ "start": 3175, "end": 5441 }
class ____(Extension): """Jinja2 Extension for dates and times.""" tags = {'now'} def __init__(self, environment: Environment) -> None: """Jinja2 Extension constructor.""" super().__init__(environment) environment.extend(datetime_format='%Y-%m-%d') def _datetime( self...
TimeExtension
python
scipy__scipy
scipy/stats/_resampling.py
{ "start": 94568, "end": 98151 }
class ____(ResamplingMethod): """Configuration information for a Monte Carlo hypothesis test. Instances of this class can be passed into the `method` parameter of some hypothesis test functions to perform a Monte Carlo version of the hypothesis tests. Attributes ---------- n_resamples : in...
MonteCarloMethod
python
pytorch__pytorch
test/distributed/test_store.py
{ "start": 11939, "end": 21722 }
class ____(TestCase, StoreTestBase): _use_libuv = False def _create_store(self): store = create_tcp_store(use_libuv=self._use_libuv) store.set_timeout(timedelta(seconds=300)) return store def _create_store_with_ws(self, addr, world_size): return create_tcp_store( ...
TCPStoreTest
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 261495, "end": 262652 }
class ____(ConditionalValueDefTextExprRef): """ ConditionalParameterValueDefTextExprRef schema wrapper. Parameters ---------- param : str, :class:`ParameterName` Filter using a parameter name. value : str, dict, :class:`Text`, Sequence[str], :class:`ExprRef` A constant value in ...
ConditionalParameterValueDefTextExprRef
python
PyCQA__pylint
tests/checkers/unittest_base_checker.py
{ "start": 648, "end": 958 }
class ____(BaseChecker): def __init__(self) -> None: super().__init__(PyLinter()) name = "basic" msgs = { "W0001": ( "Basic checker has an example.", "basic-checker-example", "Used nowhere and serves no purpose.", ) }
OtherBasicChecker
python
wandb__wandb
wandb/util.py
{ "start": 61418, "end": 63541 }
class ____: """An installed distribution. Attributes: key: The distribution name as it would be imported. version: The distribution's version string. """ key: str version: str def working_set() -> Iterable[InstalledDistribution]: """Return the working set of installed distrib...
InstalledDistribution
python
pypa__setuptools
setuptools/tests/test_build_meta.py
{ "start": 31732, "end": 33320 }
class ____(TestBuildMetaBackend): backend_name = 'setuptools.build_meta:__legacy__' # build_meta_legacy-specific tests def test_build_sdist_relative_path_import(self, tmpdir_cwd): # This must fail in build_meta, but must pass in build_meta_legacy path.build(self._relative_path_import_files)...
TestBuildMetaLegacyBackend
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-artifact-editor/llama_index/tools/artifact_editor/base.py
{ "start": 1026, "end": 16740 }
class ____(BaseToolSpec): """ A tool spec that allows you to edit an artifact in-memory. Using JSON patch operations, an LLM/Agent can be prompted to create, modify, and iterate on an artifact like a report, code, or anything that can be represented as a Pydantic model. Attributes: pydantic_cl...
ArtifactEditorToolSpec
python
lepture__authlib
tests/flask/test_oauth2/models.py
{ "start": 1767, "end": 1978 }
class ____(db.Model, OAuth2ClientMixin): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="CASCADE")) user = db.relationship("User")
Client
python
huggingface__transformers
src/transformers/pipelines/zero_shot_object_detection.py
{ "start": 632, "end": 10393 }
class ____(ChunkPipeline): """ Zero shot object detection pipeline using `OwlViTForObjectDetection`. This pipeline predicts bounding boxes of objects when you provide an image and a set of `candidate_labels`. Example: ```python >>> from transformers import pipeline >>> detector = pipeline...
ZeroShotObjectDetectionPipeline
python
pytorch__pytorch
torch/export/pt2_archive/_package_weights.py
{ "start": 2122, "end": 4780 }
class ____(dict): """ A dictionary mapping from weight name to a tuple of (tensor, TensorProperties). tensor represents the actual initial value of the weight. TensorProperties represents the properties of the weight that are needed to recover the weight. We use two separate entries because `tensor...
Weights
python
numba__numba
numba/core/typing/cffi_utils.py
{ "start": 6341, "end": 7172 }
class ____(templates.AbstractTemplate): key = 'ffi.from_buffer' def generic(self, args, kws): if kws or len(args) != 1: return [ary] = args if not isinstance(ary, types.Buffer): raise TypingError("from_buffer() expected a buffer object, got %s" ...
FFI_from_buffer
python
getsentry__sentry
tests/sentry/core/endpoints/test_organization_avatar.py
{ "start": 756, "end": 1898 }
class ____(OrganizationAvatarTestBase): method = "put" def test_upload(self) -> None: data = {"avatar_type": "upload", "avatar_photo": b64encode(self.load_fixture("avatar.jpg"))} self.get_success_response(self.organization.slug, **data) avatar = OrganizationAvatar.objects.get(organizat...
OrganizationAvatarPutTest
python
ansible__ansible
lib/ansible/plugins/lookup/lines.py
{ "start": 2241, "end": 2786 }
class ____(LookupBase): def run(self, terms, variables=None, **kwargs): ret = [] for term in terms: p = subprocess.Popen(term, cwd=self._loader.get_basedir(), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.retu...
LookupModule
python
sympy__sympy
sympy/polys/polyoptions.py
{ "start": 17250, "end": 17500 }
class ____(BooleanOption, metaclass=OptionType): """``symmetric`` option to polynomial manipulation functions. """ option = 'symmetric' requires = ['modulus'] excludes = ['greedy', 'domain', 'split', 'gaussian', 'extension']
Symmetric
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/auto_materialize_rule_evaluation.py
{ "start": 4607, "end": 4722 }
class ____(NamedTuple): ... @whitelist_for_serdes(serializer=BackcompatNullSerializer)
AutoMaterializeAssetEvaluation
python
encode__django-rest-framework
tests/browsable_api/views.py
{ "start": 779, "end": 1231 }
class ____(ModelViewSet): queryset = BasicModelWithUsers.objects.all() serializer_class = BasicSerializer permission_classes = [OrganizationPermissions] # permission_classes = [IsAuthenticated, OrganizationPermissions] renderer_classes = (renderers.BrowsableAPIRenderer, renderers.JSONRenderer) ...
BasicModelWithUsersViewSet
python
huggingface__transformers
src/transformers/models/siglip/modeling_siglip.py
{ "start": 14835, "end": 16023 }
class ____(GradientCheckpointingLayer): def __init__(self, config: Union[SiglipVisionConfig, SiglipTextConfig]): super().__init__() self.embed_dim = config.hidden_size self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) self.self_attn = SiglipAttention(config) ...
SiglipEncoderLayer
python
huggingface__transformers
src/transformers/models/bros/modeling_bros.py
{ "start": 21718, "end": 28225 }
class ____(BrosPreTrainedModel): def __init__(self, config, add_pooling_layer=True): r""" add_pooling_layer (bool, *optional*, defaults to `True`): Whether to add a pooling layer """ super().__init__(config) self.config = config self.embeddings = BrosText...
BrosModel
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 258323, "end": 259147 }
class ____(MutatingFirstArgExternKernel): def __init__(self, variable: IRNode, new_size: int) -> None: assert isinstance(new_size, int), "TODO: dynamic shapes" super().__init__( None, NoneLayout(device=variable.get_device()), self.unwrap_storage([variable]), ...
ResizeStorageBytes
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/call3.py
{ "start": 1845, "end": 2930 }
class ____: def f(self, y: Any, /): ... # This should generate an error c2: P2 = C2() def f8(a: int, b: int = 3, /): ... kwargs: Dict[str, Any] = {} # This should generate an error f8() # This should generate an error f8(**kwargs) f8(0, **kwargs) def f9(*, c: int): pass # This should gen...
C2
python
pypa__warehouse
tests/unit/admin/test_forms.py
{ "start": 156, "end": 2706 }
class ____: def test_validate_empty_string(self): """Test that empty string sets field data to None.""" form = SetUploadLimitForm(MultiDict({"upload_limit": ""})) assert form.validate() assert form.upload_limit.data is None # Verify the validator was called and returned early...
TestSetUploadLimitForm
python
xlwings__xlwings
xlwings/constants.py
{ "start": 76075, "end": 76490 }
class ____: xlMicrosoftAccess = 4 # from enum XlMSApplication xlMicrosoftFoxPro = 5 # from enum XlMSApplication xlMicrosoftMail = 3 # from enum XlMSApplication xlMicrosoftPowerPoint = 2 # from enum XlMSApplication xlMicrosoftProject = 6 # from enum XlMSApplication xlMicrosoftSchedulePlus = ...
MSApplication
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 12802, "end": 12932 }
class ____(PydanticValueError): code = 'date.not_in_the_past' msg_template = 'date is not in the past'
DateNotInThePastError
python
getsentry__sentry
tests/sentry/models/test_groupreaction.py
{ "start": 171, "end": 6220 }
class ____(TestCase): def setUp(self): super().setUp() repo = self.create_repo(project=self.project) self.commit = self.create_commit( repo=repo, project=self.project, key="pretend this is a sha", ) def test_check_constraint_both_null_fails(se...
GroupReactionTest
python
apache__airflow
scripts/in_container/verify_providers.py
{ "start": 1740, "end": 1948 }
class ____(Enum): Operators = "Operators" Transfers = "Transfers" Sensors = "Sensors" Hooks = "Hooks" Secrets = "Secrets" Trigger = "Trigger" Notification = "Notification"
EntityType
python
ray-project__ray
rllib/env/multi_agent_env.py
{ "start": 730, "end": 17949 }
class ____(gym.Env): """An environment that hosts multiple independent agents. Agents are identified by AgentIDs (string). """ # Optional mappings from AgentID to individual agents' spaces. # Set this to an "exhaustive" dictionary, mapping all possible AgentIDs to # individual agents' spaces. ...
MultiAgentEnv
python
openai__openai-python
tests/test_transform.py
{ "start": 13305, "end": 13762 }
class ____(TypedDict): foo: Annotated[Union[str, Iterable[Baz8]], PropertyInfo(alias="FOO")] @parametrize @pytest.mark.asyncio async def test_iterable_union_str(use_async: bool) -> None: assert await transform({"foo": "bar"}, TypedDictIterableUnionStr, use_async) == {"FOO": "bar"} assert cast(Any, await t...
TypedDictIterableUnionStr
python
PyCQA__mccabe
test_mccabe.py
{ "start": 5479, "end": 7998 }
class ____(unittest.TestCase): def setUp(self): self.original_complexity = mccabe.McCabeChecker.max_complexity def tearDown(self): mccabe.McCabeChecker.max_complexity = self.original_complexity def test_max_complexity_is_always_an_int(self): """Ensure bug #32 does not regress.""" ...
RegressionTests
python
dagster-io__dagster
python_modules/dagster/dagster/components/scaffold/scaffold.py
{ "start": 2542, "end": 2678 }
class ____: message: str ScaffoldFormatOptions: TypeAlias = Literal["yaml", "python"] @public @dataclass
ScaffolderUnavailableReason
python
pypa__warehouse
tests/unit/accounts/test_views.py
{ "start": 28076, "end": 47380 }
class ____: def test_get_two_factor_data_invalid_after_login(self, pyramid_request): sign_time = datetime.datetime.now(datetime.UTC) - datetime.timedelta(seconds=30) last_login_time = datetime.datetime.now(datetime.UTC) - datetime.timedelta( seconds=1 ) query_params = {"...
TestTwoFactor
python
airbytehq__airbyte
airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py
{ "start": 3595, "end": 4629 }
class ____(RkiCovidStream, ABC): state_checkpoint_interval = None @property def cursor_field(self) -> str: """ TODO Override to return the cursor field used by this stream e.g: an API entity might always use created_at as the cursor field. This is usually id or date based. T...
IncrementalRkiCovidStream
python
huggingface__transformers
src/transformers/models/vivit/modeling_vivit.py
{ "start": 14278, "end": 14870 }
class ____(nn.Module): def __init__(self, config: VivitConfig): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # We "pool" the model by simply taking th...
VivitPooler
python
davidhalter__jedi
jedi/inference/names.py
{ "start": 13835, "end": 14737 }
class ____(_ParamMixin): api_type = 'param' def get_kind(self): raise NotImplementedError def to_string(self): raise NotImplementedError def get_executed_param_name(self): """ For dealing with type inference and working around the graph, we sometimes want to ha...
ParamNameInterface
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/log.py
{ "start": 1321, "end": 1570 }
class ____(BaseModel): """Log serializer for responses.""" content: list[StructuredLogMessage] | list[str] """Either a list of parsed events, or a list of lines on parse error""" continuation_token: str | None
TaskInstancesLogResponse
python
huggingface__transformers
src/transformers/models/swin2sr/modeling_swin2sr.py
{ "start": 29586, "end": 30260 }
class ____(PreTrainedModel): config: Swin2SRConfig base_model_prefix = "swin2sr" main_input_name = "pixel_values" input_modalities = ("image",) supports_gradient_checkpointing = True @torch.no_grad() def _init_weights(self, module): """Initialize the weights""" if isinstance...
Swin2SRPreTrainedModel
python
Farama-Foundation__Gymnasium
docs/tutorials/gymnasium_basics/implementing_custom_wrappers.py
{ "start": 1854, "end": 2786 }
class ____(ObservationWrapper): def __init__(self, env): super().__init__(env) self.observation_space = Box(shape=(2,), low=-np.inf, high=np.inf) def observation(self, obs): return obs["target"] - obs["agent"] # %% # Inheriting from :class:`gymnasium.ActionWrapper` # -----------------...
RelativePosition
python
django__django
tests/queryset_pickle/models.py
{ "start": 632, "end": 907 }
class ____(models.Model): name = models.CharField(_("name"), max_length=100) objects = models.Manager() previous_django_version_objects = PreviousDjangoVersionQuerySet.as_manager() missing_django_version_objects = MissingDjangoVersionQuerySet.as_manager()
Group
python
google__jax
tests/scipy_interpolate_test.py
{ "start": 851, "end": 2349 }
class ____(jtu.JaxTestCase): """Tests for LAX-backed scipy.interpolate implementations""" @jtu.sample_product( spaces=(((0., 10., 10),), ((-15., 20., 12), (3., 4., 24))), method=("linear", "nearest"), ) def testRegularGridInterpolator(self, spaces, method): rng = jtu.rand_default(self.rng()) sc...
LaxBackedScipyInterpolateTests
python
tornadoweb__tornado
tornado/httpserver.py
{ "start": 698, "end": 1510 }
class ____ to start a server at the beginning of the process (and even that is often done indirectly via `tornado.web.Application.listen`). .. versionchanged:: 4.0 The ``HTTPRequest`` class that used to live in this module has been moved to `tornado.httputil.HTTPServerRequest`. The old name remains as an alias...
except
python
PyCQA__pyflakes
pyflakes/messages.py
{ "start": 8639, "end": 8880 }
class ____(Message): message = "'...'.format(...) has invalid format string: %s" def __init__(self, filename, loc, error): Message.__init__(self, filename, loc) self.message_args = (error,)
StringDotFormatInvalidFormat
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/endpoints-frameworks-v2/quickstart/main.py
{ "start": 4860, "end": 5439 }
class ____(remote.Service): @endpoints.method( message_types.VoidMessage, Greeting, path="greet", http_method="POST", name="greet", ) def greet(self, request): user = endpoints.get_current_user() user_name = user.email() if user else "Anonymous" ...
AuthedGreetingApi
python
ipython__ipython
docs/autogen_shortcuts.py
{ "start": 840, "end": 982 }
class ____(Filter): """Protocol reflecting non-public prompt_toolkit's `_AndList` and `_OrList`.""" filters: List[Filter]
_NestedFilter
python
mlflow__mlflow
mlflow/entities/model_registry/model_version.py
{ "start": 659, "end": 9070 }
class ____(_ModelRegistryEntity): """ MLflow entity for Model Version. """ def __init__( self, name: str, version: str, creation_timestamp: int, last_updated_timestamp: int | None = None, description: str | None = None, user_id: str | None = None,...
ModelVersion
python
weaviate__weaviate-python-client
weaviate/collections/aggregations/near_object/executor.py
{ "start": 571, "end": 6453 }
class ____(Generic[ConnectionType], _BaseExecutor[ConnectionType]): @overload def near_object( self, near_object: UUID, *, certainty: Optional[NUMBER] = None, distance: Optional[NUMBER] = None, object_limit: Optional[int] = None, filters: Optional[_Filters...
_NearObjectExecutor
python
ray-project__ray
python/ray/autoscaler/node_provider.py
{ "start": 344, "end": 10616 }
class ____: """Interface for getting and returning nodes from a Cloud. **Important**: This is an INTERNAL API that is only exposed for the purpose of implementing custom node providers. It is not allowed to call into NodeProvider methods from any Ray package outside the autoscaler, only to define n...
NodeProvider
python
networkx__networkx
networkx/generators/tests/test_geometric.py
{ "start": 5868, "end": 7905 }
class ____: """Unit tests for :func:`~networkx.geographical_threshold_graph`""" def test_number_of_nodes(self): G = nx.geographical_threshold_graph(50, 100, seed=42) assert len(G) == 50 G = nx.geographical_threshold_graph(range(50), 100, seed=42) assert len(G) == 50 def tes...
TestGeographicalThresholdGraph
python
tox-dev__tox
src/tox/tox_env/info.py
{ "start": 440, "end": 2205 }
class ____: """Stores metadata about the tox environment.""" def __init__(self, path: Path) -> None: self._path = path / ".tox-info.json" try: value = json.loads(self._path.read_text()) except (ValueError, OSError): value = {} self._content = value d...
Info
python
gevent__gevent
src/greentest/3.14/test_httpservers.py
{ "start": 1825, "end": 2776 }
class ____(threading.Thread): def __init__(self, test_object, request_handler, tls=None): threading.Thread.__init__(self) self.request_handler = request_handler self.test_object = test_object self.tls = tls def run(self): if self.tls: certfile, keyfile, passw...
TestServerThread
python
streamlit__streamlit
lib/streamlit/elements/lib/built_in_chart_utils.py
{ "start": 42777, "end": 43355 }
class ____(StreamlitAPIException): def __init__(self, color_from_user: str | Color | list[Color] | None) -> None: message = f""" This does not look like a valid color argument: `{color_from_user}`. The color argument can be: * A hex string like "#ffaa00" or "#ffaa0088". * An RGB or RGBA tuple with the red...
StreamlitInvalidColorError
python
kamyu104__LeetCode-Solutions
Python/check-if-the-rectangle-corner-is-reachable.py
{ "start": 47, "end": 1246 }
class ____(object): def canReachCorner(self, X, Y, circles): """ :type X: int :type Y: int :type circles: List[List[int]] :rtype: bool """ def check(x1, y1, r1, x2, y2, r2): return (x1-x2)**2+(y1-y2)**2 <= (r1+r2)**2 def iter_dfs(): ...
Solution
python
django__django
tests/postgres_tests/test_hstore.py
{ "start": 9012, "end": 9945 }
class ____(PostgreSQLSimpleTestCase): def test_invalid_default(self): class MyModel(PostgreSQLModel): field = HStoreField(default={}) model = MyModel() self.assertEqual( model.check(), [ checks.Warning( msg=( ...
TestChecks
python
encode__django-rest-framework
rest_framework/generics.py
{ "start": 8987, "end": 9428 }
class ____(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, GenericAPIView): """ Concrete view for retrieving or deleting a model instance. """ def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) ...
RetrieveDestroyAPIView
python
huggingface__transformers
tests/tensor_parallel/test_tensor_parallel.py
{ "start": 2908, "end": 4132 }
class ____(TestCasePlus): def test_packed_unpacked_conversion(self): WORLD_SIZE = 2 PACKED_BLOCK_SIZE = 800 SHARDING_DIM = 2 NUM_BLOCKS = 2 original_packed_weights = torch.randn(4, 512, 2 * PACKED_BLOCK_SIZE) original_packed_weights.get_dtype = lambda: "F32" # get_p...
TestTensorParallelUtils
python
nedbat__coveragepy
tests/test_context.py
{ "start": 8826, "end": 10605 }
class ____(CoverageTest): """Tests of qualname_from_frame.""" # Pylint gets confused about meth() below. # pylint: disable=no-value-for-parameter run_in_temp_dir = False def test_method(self) -> None: assert Parent().meth() == "tests.test_context.Parent.meth" def test_inherited_metho...
QualnameTest
python
fastapi__sqlmodel
sqlmodel/_compat.py
{ "start": 1094, "end": 22886 }
class ____: obj: Any update: Dict[str, Any] def __getattribute__(self, __name: str) -> Any: update = super().__getattribute__("update") obj = super().__getattribute__("obj") if __name in update: return update[__name] return getattr(obj, __name) def _is_union_ty...
ObjectWithUpdateWrapper
python
openai__openai-python
src/openai/types/responses/response_function_call_arguments_done_event.py
{ "start": 215, "end": 639 }
class ____(BaseModel): arguments: str """The function-call arguments.""" item_id: str """The ID of the item.""" name: str """The name of the function that was called.""" output_index: int """The index of the output item.""" sequence_number: int """The sequence number of this ...
ResponseFunctionCallArgumentsDoneEvent
python
spack__spack
lib/spack/spack/util/environment.py
{ "start": 12589, "end": 13151 }
class ____(NamePathModifier): def execute(self, env: MutableMapping[str, str]): tty.debug(f"RemoveFirstPath: {self.name}-{self.value}", level=3) environment_value = env.get(self.name, "") directories = environment_value.split(self.separator) directories = [path_to_os_path(os.path.nor...
RemoveFirstPath