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
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/distlib/locators.py
{ "start": 37288, "end": 38169 }
class ____(Locator): """ This locator finds installed distributions in a path. It can be useful for adding to an :class:`AggregatingLocator`. """ def __init__(self, distpath, **kwargs): """ Initialise an instance. :param distpath: A :class:`DistributionPath` instance to sear...
DistPathLocator
python
huggingface__transformers
src/transformers/models/sam3/modeling_sam3.py
{ "start": 54640, "end": 59417 }
class ____(Sam3PreTrainedModel): """ DETR-style encoder that processes multi-level vision features with text fusion. This encoder processes vision features from multiple levels (e.g., FPN features at different resolutions) and fuses them with text prompts through a stack of transformer encoder layers. ...
Sam3DetrEncoder
python
xlwings__xlwings
xlwings/constants.py
{ "start": 51078, "end": 51247 }
class ____: xlDataBarColor = 0 # from enum XlDataBarNegativeColorType xlDataBarSameAsPositive = 1 # from enum XlDataBarNegativeColorType
DataBarNegativeColorType
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/resizing.py
{ "start": 566, "end": 11968 }
class ____(BaseImagePreprocessingLayer): """A preprocessing layer which resizes images. This layer resizes an image input to a target height and width. The input should be a 4D (batched) or 3D (unbatched) tensor in `"channels_last"` format. Input pixel values can be of any range (e.g. `[0., 1.)` or...
Resizing
python
catalyst-team__catalyst
catalyst/engines/torch.py
{ "start": 5867, "end": 7789 }
class ____(Engine): """Distributed XLA-based engine.""" def __init__(self, *args, **kwargs): """Init.""" self._args = args self._kwargs = kwargs def spawn(self, fn: Callable, *args, **kwargs): """Spawns processes with specified ``fn`` and ``args``/``kwargs``. Args:...
DistributedXLAEngine
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 570797, "end": 571557 }
class ____(sgqlc.types.relay.Connection): """The connection type for DeploymentRequest.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("DeploymentRequestEdge"), graphql_name="edges") """A list of edges."""...
DeploymentRequestConnection
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_format22.py
{ "start": 315, "end": 1025 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("format22.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with automatic color.""" workbook = W...
TestCompareXLSXFiles
python
huggingface__transformers
src/transformers/models/vjepa2/modeling_vjepa2.py
{ "start": 22550, "end": 26611 }
class ____(nn.Module): def __init__(self, config: VJEPA2Config): super().__init__() self.config = config self.gradient_checkpointing = False self.embeddings = VJEPA2PredictorEmbeddings(config) drop_path_rates = [ ( config.drop_path_rate * i / (conf...
VJEPA2Predictor
python
pennersr__django-allauth
allauth/socialaccount/providers/steam/views.py
{ "start": 591, "end": 944 }
class ____(OpenIDLoginView): provider_class = SteamOpenIDProvider def get_form(self): items = dict(list(self.request.GET.items()) + list(self.request.POST.items())) items["openid"] = STEAM_OPENID_URL return self.form_class(items) def get_callback_url(self): return reverse(s...
SteamOpenIDLoginView
python
doocs__leetcode
solution/0200-0299/0228.Summary Ranges/Solution.py
{ "start": 0, "end": 433 }
class ____: def summaryRanges(self, nums: List[int]) -> List[str]: def f(i: int, j: int) -> str: return str(nums[i]) if i == j else f'{nums[i]}->{nums[j]}' i = 0 n = len(nums) ans = [] while i < n: j = i while j + 1 < n and nums[j + 1] == ...
Solution
python
walkccc__LeetCode
solutions/375. Guess Number Higher or Lower II/375.py
{ "start": 0, "end": 366 }
class ____: def getMoneyAmount(self, n: int) -> int: @functools.lru_cache(None) def dp(i: int, j: int) -> int: """Returns the minimum money you need to guarantee a win of picking i..j. """ if i >= j: return 0 return min(max(dp(i, k - 1), dp(k + 1, j)) + k for k...
Solution
python
langchain-ai__langchain
libs/cli/langchain_cli/integration_template/integration_template/tools.py
{ "start": 208, "end": 687 }
class ____(BaseModel): """Input schema for __ModuleName__ tool. This docstring is **not** part of what is sent to the model when performing tool calling. The Field default values and descriptions **are** part of what is sent to the model when performing tool calling. """ # TODO: Add input args...
__ModuleName__ToolInput
python
allegroai__clearml
clearml/errors.py
{ "start": 31, "end": 142 }
class ____(RuntimeError): """An exception raised for illegal usage of clearml objects""" pass
UsageError
python
apache__avro
lang/py/avro/test/test_script.py
{ "start": 4594, "end": 7442 }
class ____(unittest.TestCase): def setUp(self): self.json_file = _tempfile() + ".json" with Path(self.json_file).open("w") as fo: for record in looney_records(): json.dump(record, fo) fo.write("\n") self.csv_file = _tempfile() + ".csv" get...
TestWrite
python
django__django
tests/validation/models.py
{ "start": 6179, "end": 6655 }
class ____(models.Model): name = models.CharField(max_length=255) color = models.CharField(max_length=31, null=True, blank=True) class Meta: required_db_features = {"supports_partial_indexes"} constraints = [ models.UniqueConstraint( fields=["name"], ...
UniqueConstraintConditionProduct
python
spyder-ide__spyder
spyder/utils/syntaxhighlighters.py
{ "start": 31992, "end": 42514 }
class ____(BaseSH): """C/C++ Syntax Highlighter""" # Syntax highlighting rules: PROG = re.compile(make_cpp_patterns(), re.S) # Syntax highlighting states (from one text block to another): NORMAL = 0 INSIDE_COMMENT = 1 def __init__(self, parent, font=None, color_scheme=None): BaseSH._...
CppSH
python
huggingface__transformers
src/transformers/models/mm_grounding_dino/modular_mm_grounding_dino.py
{ "start": 15783, "end": 18153 }
class ____(GroundingDinoModel, MMGroundingDinoPreTrainedModel): def __init__(self, config: MMGroundingDinoConfig): MMGroundingDinoPreTrainedModel.__init__(self, config) # Create backbone + positional encoding backbone = MMGroundingDinoConvEncoder(config) position_embeddings = build_...
MMGroundingDinoModel
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-service-now/tests/test_snow_kb_reader.py
{ "start": 397, "end": 1933 }
class ____: """Mock ServiceNow client for testing.""" def __init__(self, *args, **kwargs): self.attachment_api = MagicMock() self.attachment_api.get_file = MagicMock(return_value=b"mock file content") def GlideRecord(self, table): """Mock GlideRecord for ServiceNow table operations...
MockServiceNowClient
python
explosion__spaCy
spacy/lang/tn/__init__.py
{ "start": 293, "end": 392 }
class ____(Language): lang = "tn" Defaults = SetswanaDefaults __all__ = ["Setswana"]
Setswana
python
cython__cython
Cython/Debugger/libcython.py
{ "start": 20124, "end": 20254 }
class ____(CythonParameter): """ Tell cygdb about the user's terminal background (light or dark). """
TerminalBackground
python
airbytehq__airbyte
airbyte-integrations/connectors/source-posthog/source_posthog/components.py
{ "start": 2122, "end": 5920 }
class ____(Cursor, CartesianProductStreamSlicer): """Connector requires support of nested state - each project should have own timestamp value, like: { "project_id1": { "timestamp": "2021-02-01T10:21:35.003000Z" }, "project_idX": { "timestamp": "2022-11-17:00:00.00000...
EventsCartesianProductStreamSlicer
python
wntrblm__nox
nox/_parametrize.py
{ "start": 930, "end": 6985 }
class ____: """A class that encapsulates a single set of parameters to a parametrized session. Args: args (List[Any]): The list of args to pass to the invoked function. arg_names (Sequence[str]): The names of the args. id (str): An optional ID for this set of parameters. If unspecif...
Param
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1251909, "end": 1252429 }
class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData): """Audit log entry for a org.invite_member event.""" __schema__ = github_schema __field_names__ = ("email", "organization_invitation") email = sgqlc.types.Field(String, graphql_name="email") """The email address of the orga...
OrgInviteMemberAuditEntry
python
PyCQA__pylint
tests/checkers/unittest_variables.py
{ "start": 1042, "end": 6064 }
class ____(CheckerTestCase): CHECKER_CLASS = variables.VariablesChecker def setup_method(self) -> None: super().setup_method() self._to_consume_backup = self.checker._to_consume self.checker._to_consume = [] def teardown_method(self) -> None: self.checker._to_consume = self...
TestVariablesCheckerWithTearDown
python
viewflow__viewflow
tests/components/test_utils__viewprop.py
{ "start": 258, "end": 558 }
class ____(TestCase): # noqa: D101 def test_default_viewprop_value(self): viewset = Viewset() self.assertEqual(viewset.view, 'default') def test_redefine_viewprop_succeed(self): viewset = Viewset(view='new value') self.assertEqual(viewset.view, 'new value')
Test
python
vyperlang__vyper
vyper/compiler/input_bundle.py
{ "start": 2100, "end": 2200 }
class ____(Exception): pass # an opaque object which consumers can get/set attributes on
_NotFound
python
astropy__astropy
astropy/nddata/nduncertainty.py
{ "start": 37501, "end": 40882 }
class ____(_VariancePropagationMixin, NDUncertainty): """ Variance uncertainty assuming first order Gaussian error propagation. This class implements uncertainty propagation for ``addition``, ``subtraction``, ``multiplication`` and ``division`` with other instances of `VarianceUncertainty`. The...
VarianceUncertainty
python
walkccc__LeetCode
solutions/3196. Maximize Total Cost of Alternating Subarrays/3196-2.py
{ "start": 0, "end": 411 }
class ____: def maximumTotalCost(self, nums: list[int]) -> int: # A small trick so that we don't need to handle the edge case and can use # ranged-based for loop. keep = -math.inf # the maximum cost if the last number is kept flip = 0 # the maximum cost if the last number is flipped for num in ...
Solution
python
fastai__fastai
fastai/vision/widgets.py
{ "start": 2246, "end": 4291 }
class ____: "A widget that displays all images in `fns` along with a `Dropdown`" def __init__(self, opts:tuple=(), # Options for the `Dropdown` menu height:int=128, # Thumbnail Height width:int=256, # Thumbnail Width max_n:int=30 # Max number of images to display ): o...
ImagesCleaner
python
langchain-ai__langchain
libs/langchain/tests/unit_tests/retrievers/parrot_retriever.py
{ "start": 100, "end": 541 }
class ____(BaseRetriever): """Test util that parrots the query back as documents.""" def _get_relevant_documents( # type: ignore[override] self, query: str, ) -> list[Document]: return [Document(page_content=query)] async def _aget_relevant_documents( # type: ignore[override]...
FakeParrotRetriever
python
numpy__numpy
doc/neps/nep-0016-benchmark.py
{ "start": 72, "end": 123 }
class ____: __array_implementer__ = True
AttrArray
python
PrefectHQ__prefect
src/integrations/prefect-kubernetes/prefect_kubernetes/credentials.py
{ "start": 4147, "end": 8710 }
class ____(Block): """Credentials block for generating configured Kubernetes API clients. Attributes: cluster_config: A `KubernetesClusterConfig` block holding a JSON kube config for a specific kubernetes context. Example: Load stored Kubernetes credentials: ```python ...
KubernetesCredentials
python
redis__redis-py
redis/exceptions.py
{ "start": 1963, "end": 2078 }
class ____(Exception): """ Base exception for the RedisCluster client """ pass
RedisClusterException
python
doocs__leetcode
solution/2300-2399/2395.Find Subarrays With Equal Sum/Solution.py
{ "start": 0, "end": 234 }
class ____: def findSubarrays(self, nums: List[int]) -> bool: vis = set() for a, b in pairwise(nums): if (x := a + b) in vis: return True vis.add(x) return False
Solution
python
numba__numba
numba/cpython/unicode_support.py
{ "start": 1973, "end": 13957 }
class ____(IntEnum): ALPHA_MASK = 0x01 DECIMAL_MASK = 0x02 DIGIT_MASK = 0x04 LOWER_MASK = 0x08 LINEBREAK_MASK = 0x10 SPACE_MASK = 0x20 TITLE_MASK = 0x40 UPPER_MASK = 0x80 XID_START_MASK = 0x100 XID_CONTINUE_MASK = 0x200 PRINTABLE_MASK = 0x400 NUMERIC_MASK = 0x800 CASE...
_PyUnicode_TyperecordMasks
python
getsentry__sentry
src/sentry/integrations/source_code_management/repository.py
{ "start": 987, "end": 1743 }
class ____(ABC): @abstractmethod def get_repositories( self, query: str | None = None, page_number_limit: int | None = None ) -> list[dict[str, Any]]: """ Get a list of available repositories for an installation >>> def get_repositories(self): >>> return self.get...
BaseRepositoryIntegration
python
doocs__leetcode
solution/0300-0399/0327.Count of Range Sum/Solution.py
{ "start": 0, "end": 339 }
class ____: def __init__(self, n): self.n = n self.c = [0] * (n + 1) def update(self, x, v): while x <= self.n: self.c[x] += v x += x & -x def query(self, x): s = 0 while x > 0: s += self.c[x] x -= x & -x retur...
BinaryIndexedTree
python
dask__dask
dask/utils.py
{ "start": 34751, "end": 35107 }
class ____: """Attribute access on this object returns a methodcaller for that attribute. Examples -------- >>> a = [1, 3, 3] >>> M.count(a, 3) == a.count(3) True """ def __getattr__(self, item): return methodcaller(item) def __dir__(self): return list(_method_...
MethodCache
python
realpython__materials
python-tic-tac-toe-game-tkinter/source_code_step_2/tic_tac_toe.py
{ "start": 407, "end": 1456 }
class ____: def __init__(self, players=DEFAULT_PLAYERS, board_size=BOARD_SIZE): self._players = cycle(players) self.board_size = board_size self.current_player = next(self._players) self.winner_combo = [] self._current_moves = [] self._has_winner = False self....
TicTacToeGame
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/type/definition.py
{ "start": 14224, "end": 14936 }
class ____(object): __slots__ = 'name', 'value', 'deprecation_reason', 'description' def __init__(self, value=None, deprecation_reason=None, description=None, name=None): self.name = name self.value = value self.deprecation_reason = deprecation_reason self.description = descript...
GraphQLEnumValue
python
gevent__gevent
src/greentest/3.10/test_selectors.py
{ "start": 13773, "end": 15908 }
class ____: # see issue #18963 for why it's skipped on older OS X versions @support.requires_mac_ver(10, 5) @unittest.skipUnless(resource, "Test needs resource module") def test_above_fd_setsize(self): # A scalable implementation should have no problem with more than # FD_SETSIZE file d...
ScalableSelectorMixIn
python
TheAlgorithms__Python
data_structures/linked_list/has_loop.py
{ "start": 108, "end": 1702 }
class ____: def __init__(self, data: Any) -> None: self.data: Any = data self.next_node: Node | None = None def __iter__(self): node = self visited = set() while node: if node in visited: raise ContainsLoopError visited.add(node) ...
Node
python
python-openxml__python-docx
src/docx/opc/pkgreader.py
{ "start": 5549, "end": 6410 }
class ____: """Value object for an OPC package part. Provides access to the partname, content type, blob, and serialized relationships for the part. """ def __init__(self, partname, content_type, reltype, blob, srels): super(_SerializedPart, self).__init__() self._partname = partna...
_SerializedPart
python
ray-project__ray
python/ray/util/tracing/tracing_helper.py
{ "start": 5024, "end": 19076 }
class ____: def inject_current_context() -> Dict[Any, Any]: """Inject trace context into otel propagator.""" context_dict: Dict[Any, Any] = {} _opentelemetry.propagate.inject(context_dict) return context_dict def extract(context_dict: Dict[Any, Any]) -> "_opentelemetry.Context":...
_DictPropagator
python
astropy__astropy
astropy/modeling/functional_models.py
{ "start": 21330, "end": 22579 }
class ____(Fittable1DModel): """ Multiply a model by a quantity or number. Parameters ---------- factor : float Factor by which to multiply a coordinate. """ factor = Parameter(default=1, description="Factor by which to multiply a model") linear = True fittable = True ...
Multiply
python
ray-project__ray
python/ray/data/_internal/datasource/databricks_uc_datasource.py
{ "start": 420, "end": 7347 }
class ____(Datasource): def __init__( self, host: str, token: str, warehouse_id: str, catalog: str, schema: str, query: str, ): self.host = host self.token = token self.warehouse_id = warehouse_id self.catalog = catalog ...
DatabricksUCDatasource
python
python-attrs__attrs
tests/test_make.py
{ "start": 11542, "end": 24468 }
class ____: """ Tests for the `attrs`/`attr.s` class decorator. """ def test_sets_attrs(self): """ Sets the `__attrs_attrs__` class attribute with a list of `Attribute`s. """ @attr.s class C: x = attr.ib() assert "x" == C.__attrs_attrs__[0]....
TestAttributes
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/freshness.py
{ "start": 1137, "end": 1450 }
class ____: """Event that is emitted when the freshness state of an asset changes.""" key: AssetKey new_state: FreshnessState previous_state: FreshnessState state_change_timestamp: float INTERNAL_FRESHNESS_POLICY_METADATA_KEY = "dagster/internal_freshness_policy" @public
FreshnessStateChange
python
celery__celery
celery/exceptions.py
{ "start": 6815, "end": 6967 }
class ____(KeyError, TaskError): """The task is not registered.""" def __repr__(self): return UNREGISTERED_FMT.format(self)
NotRegistered
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-oxylabs/llama_index/readers/oxylabs/amazon_reviews.py
{ "start": 135, "end": 890 }
class ____(OxylabsBaseReader): """ Get data about Amazon product reviews. https://developers.oxylabs.io/scraper-apis/web-scraper-api/targets/amazon/reviews """ top_level_header: str = "Reviews" def __init__(self, username: str, password: str, **data) -> None: super().__init__(username...
OxylabsAmazonReviewsReader
python
dagster-io__dagster
python_modules/dagster/dagster/_config/pythonic_config/typing_utils.py
{ "start": 6877, "end": 9147 }
class ____: """Implementation of the Python descriptor protocol (https://docs.python.org/3/howto/descriptor.html) to adjust the types of resource inputs and outputs, e.g. resource dependencies can be passed in as PartialResources or Resources, but will always be returned as Resources. For example, give...
TypecheckAllowPartialResourceInitParams
python
Lightning-AI__lightning
tests/tests_pytorch/strategies/test_deepspeed.py
{ "start": 2170, "end": 21788 }
class ____(BoringModel): def __init__(self): super().__init__() self.layer = None def training_step(self, batch, batch_idx): opt = self.optimizers() loss = self.step(batch) opt.zero_grad() self.manual_backward(loss) opt.step() def configure_model(sel...
ModelParallelBoringModelManualOptim
python
encode__django-rest-framework
tests/test_generics.py
{ "start": 14768, "end": 15143 }
class ____(TestCase): def test_m2m_in_browsable_api(self): """ Test for particularly ugly regression with m2m in browsable API """ request = factory.get('/', HTTP_ACCEPT='text/html') view = ExampleView().as_view() response = view(request).render() assert respo...
TestM2MBrowsableAPI
python
pytorch__pytorch
torch/nn/parallel/distributed.py
{ "start": 11401, "end": 109859 }
class ____(Module, Joinable): r"""Implement distributed data parallelism based on ``torch.distributed`` at module level. This container provides data parallelism by synchronizing gradients across each model replica. The devices to synchronize across are specified by the input ``process_group``, which i...
DistributedDataParallel
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py
{ "start": 3909, "end": 5184 }
class ____(StrictBaseModel): """Schema for updating TaskInstance to a deferred state.""" state: Annotated[ Literal[IntermediateTIState.DEFERRED], # Specify a default in the schema, but not in code, so Pydantic marks it as required. WithJsonSchema( { "type": "...
TIDeferredStatePayload
python
ray-project__ray
python/ray/air/execution/resources/request.py
{ "start": 6282, "end": 8541 }
class ____(abc.ABC): """Base class for resources that have been acquired. Acquired resources can be associated to Ray objects, which can then be scheduled using these resources. Internally this can point e.g. to a placement group, a placement group bundle index, or just raw resources. The mai...
AcquiredResources
python
kubernetes-client__python
kubernetes/client/models/v1_network_device_data.py
{ "start": 383, "end": 6424 }
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...
V1NetworkDeviceData
python
urllib3__urllib3
test/test_ssltransport.py
{ "start": 11826, "end": 18897 }
class ____(SocketDummyServerTestCase): """ Creates a TLS in TLS tunnel by chaining a 'SocketProxyDummyServer' and a `SocketDummyServerTestCase`. Client will first connect to the proxy, who will then proxy any bytes send to the destination server. First TLS layer terminates at the proxy, second ...
TlsInTlsTestCase
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/elements.py
{ "start": 118076, "end": 118350 }
class ____(Cast[_T]): """Represent a TRY_CAST expression. Details on :class:`.TryCast` usage is at :func:`.try_cast`. .. seealso:: :func:`.try_cast` :ref:`tutorial_casts` """ __visit_name__ = "try_cast" inherit_cache = True
TryCast
python
PrefectHQ__prefect
src/integrations/prefect-redis/prefect_redis/messaging.py
{ "start": 2236, "end": 3487 }
class ____(PrefectBaseSettings): """Settings for the Redis messaging consumer. No settings are required to be set by the user but any of the settings can be overridden by the user using environment variables. Example: ``` PREFECT_REDIS_MESSAGING_CONSUMER_BLOCK=10 PREFECT_REDIS_...
RedisMessagingConsumerSettings
python
huggingface__transformers
src/transformers/models/patchtst/modeling_patchtst.py
{ "start": 47106, "end": 51937 }
class ____(PatchTSTPreTrainedModel): def __init__(self, config: PatchTSTConfig): super().__init__(config) self.scaler = PatchTSTScaler(config) self.patchifier = PatchTSTPatchify(config) self.do_mask_input = config.do_mask_input # get num_patches information from PatchTSTPatc...
PatchTSTModel
python
huggingface__transformers
src/transformers/convert_slow_tokenizer.py
{ "start": 15178, "end": 16687 }
class ____(Converter): def converted( self, vocab: Optional[dict[str, int]] = None, merges: Optional[list[tuple[str, str]]] = None ) -> Tokenizer: if not vocab: vocab = self.original_tokenizer.encoder if not merges: merges = list(self.original_tokenizer.bpe_ranks....
Qwen2Converter
python
pytorch__pytorch
test/distributed/checkpoint/test_state_dict_stager.py
{ "start": 33529, "end": 52258 }
class ____(DTensorTestBase): """ Test suite for _ReplicationStager functionality. Tests replication of state_dict across training ranks using CPU tensors only. """ @property def backend(self) -> str: return "cpu:gloo,cuda:nccl" def _create_simple_state_dict(self, rank: int) -> dict...
TestReplicationStager
python
astropy__astropy
astropy/utils/masked/tests/test_function_helpers.py
{ "start": 1122, "end": 1860 }
class ____(MaskedArraySetup): def check(self, func, *args, **kwargs): out = func(self.ma, *args, **kwargs) expected = Masked( func(self.a, *args, **kwargs), mask=func(self.mask_a, *args, **kwargs) ) assert_masked_equal(out, expected) def check2(self, func, *args, **k...
BasicTestSetup
python
pypa__setuptools
pkg_resources/tests/test_pkg_resources.py
{ "start": 566, "end": 4064 }
class ____: finalizers: list[EggRemover] = [] ref_time = datetime.datetime(2013, 5, 12, 13, 25, 0) "A reference time for a file modification" @classmethod def setup_class(cls): "create a zip egg and add it to sys.path" egg = tempfile.NamedTemporaryFile(suffix='.egg', delete=False) ...
TestZipProvider
python
walkccc__LeetCode
solutions/279. Perfect Squares/279.py
{ "start": 0, "end": 280 }
class ____: def numSquares(self, n: int) -> int: dp = [n] * (n + 1) # 1^2 x n dp[0] = 0 # no way dp[1] = 1 # 1^2 for i in range(2, n + 1): j = 1 while j * j <= i: dp[i] = min(dp[i], dp[i - j * j] + 1) j += 1 return dp[n]
Solution
python
encode__django-rest-framework
rest_framework/serializers.py
{ "start": 10611, "end": 12808 }
class ____(type): """ This metaclass sets a dictionary named `_declared_fields` on the class. Any instances of `Field` included as attributes on either the class or on any of its superclasses will be include in the `_declared_fields` dictionary. """ @classmethod def _get_declared_field...
SerializerMetaclass
python
numba__numba
numba/cuda/compiler.py
{ "start": 3954, "end": 15773 }
class ____(CompilerBase): def define_pipelines(self): dpb = DefaultPassBuilder pm = PassManager('cuda') untyped_passes = dpb.define_untyped_pipeline(self.state) pm.passes.extend(untyped_passes.passes) typed_passes = dpb.define_typed_pipeline(self.state) pm.passes.ex...
CUDACompiler
python
langchain-ai__langchain
libs/core/langchain_core/indexing/in_memory.py
{ "start": 559, "end": 3283 }
class ____(DocumentIndex): """In memory document index. This is an in-memory document index that stores documents in a dictionary. It provides a simple search API that returns documents by the number of counts the given query appears in the document. """ store: dict[str, Document] = Field(def...
InMemoryDocumentIndex
python
PyCQA__pylint
pylint/checkers/dataclass_checker.py
{ "start": 1091, "end": 4502 }
class ____(BaseChecker): """Checker that detects invalid or problematic usage in dataclasses. Checks for * invalid-field-call """ name = "dataclass" msgs = { "E3701": ( "Invalid usage of field(), %s", "invalid-field-call", "The dataclasses.field() sp...
DataclassChecker
python
MorvanZhou__Reinforcement-learning-with-tensorflow
contents/10_A3C/A3C_continuous_action.py
{ "start": 885, "end": 4602 }
class ____(object): def __init__(self, scope, globalAC=None): if scope == GLOBAL_NET_SCOPE: # get global network with tf.variable_scope(scope): self.s = tf.placeholder(tf.float32, [None, N_S], 'S') self.a_params, self.c_params = self._build_net(scope)[-2:] ...
ACNet
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/dataflow.py
{ "start": 6509, "end": 9276 }
class ____(LoggingMixin): """Helper to define and validate the dataflow job terminal state.""" @staticmethod def expected_terminal_state_is_allowed(expected_terminal_state): job_allowed_terminal_states = DataflowJobStatus.TERMINAL_STATES | { DataflowJobStatus.JOB_STATE_RUNNING }...
DataflowJobTerminalStateHelper
python
joke2k__faker
faker/providers/company/id_ID/__init__.py
{ "start": 45, "end": 933 }
class ____(CompanyProvider): formats = ( "{{company_prefix}} {{last_name}}", "{{company_prefix}} {{last_name}} {{last_name}}", "{{company_prefix}} {{last_name}} {{company_suffix}}", "{{company_prefix}} {{last_name}} {{last_name}} {{company_suffix}}", ) # From http://id.wikip...
Provider
python
optuna__optuna
optuna/artifacts/_upload.py
{ "start": 572, "end": 3913 }
class ____: """Meta information for an artifact. .. note:: All the artifact meta linked to a study or trial can be listed by :func:`~optuna.artifacts.get_all_artifact_meta`. The artifact meta can be used for :func:`~optuna.artifacts.download_artifact`. Args: artifact_id: ...
ArtifactMeta
python
django__django
django/contrib/gis/geos/prototypes/predicates.py
{ "start": 359, "end": 535 }
class ____(GEOSFuncFactory): "For GEOS unary predicate functions." argtypes = [GEOM_PTR] restype = c_byte errcheck = staticmethod(check_predicate)
UnaryPredicate
python
getsentry__sentry
src/sentry/pipeline/store.py
{ "start": 75, "end": 464 }
class ____(RedisSessionStore): uid = redis_property("uid") provider_model_id = redis_property("provider_model_id") provider_key = redis_property("provider_key") org_id = redis_property("org_id") signature = redis_property("signature") step_index = redis_property("step_index") config = redis_...
PipelineSessionStore
python
scipy__scipy
scipy/stats/_levy_stable/__init__.py
{ "start": 21903, "end": 45977 }
class ____(rv_continuous): r"""A Levy-stable continuous random variable. %(before_notes)s See Also -------- levy, levy_l, cauchy, norm Notes ----- The distribution for `levy_stable` has characteristic function: .. math:: \varphi(t, \alpha, \beta, c, \mu) = e^{it\...
levy_stable_gen
python
allegroai__clearml
examples/frameworks/tensorflow/legacy/tensorflow_eager.py
{ "start": 1556, "end": 3682 }
class ____(tf.keras.Model): """ GAN Discriminator. A network to differentiate between generated and real handwritten digits. """ def __init__(self, data_format): """Creates a model for discriminating between real and generated digits. Args: data_format: Either 'channels_fi...
Discriminator
python
getsentry__sentry
src/sentry/api/serializers/models/relayusage.py
{ "start": 123, "end": 437 }
class ____(Serializer): def serialize(self, obj, attrs, user, **kwargs): return { "relayId": obj.relay_id, "version": obj.version, "firstSeen": obj.first_seen, "lastSeen": obj.last_seen, "publicKey": obj.public_key, }
RelayUsageSerializer
python
pandas-dev__pandas
asv_bench/benchmarks/tslibs/timestamp.py
{ "start": 2451, "end": 3312 }
class ____: params = _tzs param_names = ["tz"] def setup(self, tz): self.ts = Timestamp("2017-08-25 08:16:14", tz=tz) def time_replace_tz(self, tz): self.ts.replace(tzinfo=zoneinfo.ZoneInfo("US/Eastern")) def time_replace_None(self, tz): self.ts.replace(tzinfo=None) d...
TimestampOps
python
getsentry__sentry
src/sentry/workflow_engine/handlers/condition/issue_priority_deescalating_handler.py
{ "start": 464, "end": 1466 }
class ____(DataConditionHandler[WorkflowEventData]): group = DataConditionHandler.Group.ACTION_FILTER subgroup = DataConditionHandler.Subgroup.ISSUE_ATTRIBUTES @staticmethod def evaluate_value(event_data: WorkflowEventData, comparison: Any) -> bool: group = event_data.group # we will f...
IssuePriorityDeescalatingConditionHandler
python
walkccc__LeetCode
solutions/2966. Divide Array Into Arrays With Max Difference/2966.py
{ "start": 0, "end": 277 }
class ____: def divideArray(self, nums: list[int], k: int) -> list[list[int]]: ans = [] nums.sort() for i in range(2, len(nums), 3): if nums[i] - nums[i - 2] > k: return [] ans.append([nums[i - 2], nums[i - 1], nums[i]]) return ans
Solution
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 15696, "end": 15941 }
class ____(_RerankerProvider): reranker: Union[Rerankers, _EnumLikeStr] = Field( default=Rerankers.COHERE, frozen=True, exclude=True ) model: Optional[Union[RerankerCohereModel, str]] = Field(default=None)
_RerankerCohereConfig
python
PrefectHQ__prefect
tests/server/models/test_block_schemas.py
{ "start": 11579, "end": 34234 }
class ____: @pytest.fixture async def block_schemas_with_capabilities(self, session): class CanRun(Block): _block_schema_capabilities = ["run"] def run(self): pass class CanFly(Block): _block_schema_capabilities = ["fly"] def fly...
TestReadBlockSchemas
python
facebookresearch__faiss
tests/test_fast_scan_ivf.py
{ "start": 7966, "end": 10593 }
class ____(unittest.TestCase): def test_equiv_pq(self): ds = datasets.SyntheticDataset(32, 2000, 200, 4) xq = ds.get_queries() index = faiss.index_factory(32, "IVF1,PQ16x4np") index.by_residual = False # force coarse quantizer index.quantizer.add(np.zeros((1, 32), ...
TestEquivPQ
python
pypa__build
src/build/env.py
{ "start": 485, "end": 1519 }
class ____(typing.Protocol): """Isolated build environment ABC.""" @property @abc.abstractmethod def python_executable(self) -> str: """The Python executable of the isolated environment.""" @abc.abstractmethod def make_extra_environ(self) -> Mapping[str, str] | None: """Generat...
IsolatedEnv
python
tiangolo__fastapi
fastapi/exceptions.py
{ "start": 4527, "end": 4714 }
class ____(ValidationException): def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None: super().__init__(errors) self.body = body
RequestValidationError
python
spyder-ide__spyder
spyder/plugins/projects/widgets/main_widget.py
{ "start": 2357, "end": 2453 }
class ____: Recent = 'recent_section' Extras = 'extras_section'
RecentProjectsMenuSections
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 41909, "end": 42043 }
class ____(Base): token: Mapped[str] client: Mapped[str] = mapped_column(unique=True) expiration: Mapped[DateTime]
CsrfToken
python
sympy__sympy
sympy/functions/elementary/hyperbolic.py
{ "start": 24595, "end": 29879 }
class ____(HyperbolicFunction): r""" ``coth(x)`` is the hyperbolic cotangent of ``x``. The hyperbolic cotangent function is $\frac{\cosh(x)}{\sinh(x)}$. Examples ======== >>> from sympy import coth >>> from sympy.abc import x >>> coth(x) coth(x) See Also ======== sym...
coth
python
pytorch__pytorch
test/distributed/test_nvshmem.py
{ "start": 930, "end": 9088 }
class ____(MultiProcContinuousTest): def _init_device(self) -> None: # TODO: relieve this (seems to hang if without) device_module.set_device(self.device) # Set NVSHMEM as SymmMem backend symm_mem.set_backend("NVSHMEM") @property def device(self) -> torch.device: ret...
NVSHMEMSymmetricMemoryTest
python
getsentry__sentry
tests/sentry/api/endpoints/test_debug_files.py
{ "start": 1689, "end": 13699 }
class ____(DebugFilesTestCases): def test_simple_proguard_upload(self) -> None: response = self._upload_proguard(self.url, PROGUARD_UUID) assert response.status_code == 201, response.content assert len(response.data) == 1 assert response.data[0]["headers"] == {"Content-Type": "text/x...
DebugFilesTest
python
bokeh__bokeh
tests/unit/bokeh/embed/test_bundle.py
{ "start": 10048, "end": 13489 }
class ____: def test_without_mathjax(self) -> None: assert beb._use_mathjax(beb._all_objs([plot()])) is False assert beb._use_mathjax(beb._all_objs([plot(), glplot()])) is False assert beb._use_mathjax(beb._all_objs([plot(), table()])) is False assert beb._use_mathjax(beb._all_objs([...
Test__use_mathjax
python
plotly__plotly.py
plotly/graph_objs/layout/_template.py
{ "start": 251, "end": 4852 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout" _path_str = "layout.template" _valid_props = {"data", "layout"} @property def data(self): """ The 'data' property is an instance of Data that may be specified as: - An instance of :class:`plotly.grap...
Template
python
django__django
tests/gis_tests/layermap/models.py
{ "start": 1322, "end": 1439 }
class ____(ICity1): dt_time = models.DateTimeField(auto_now=True) class Meta(ICity1.Meta): pass
ICity2
python
encode__django-rest-framework
tests/test_atomic_requests.py
{ "start": 932, "end": 1393 }
class ____(APIView): @transaction.non_atomic_requests def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): BasicModel.objects.all() raise Http404 urlpatterns = ( path('', NonAtomicAPIExceptionView.as_view()), ) ...
NonAtomicAPIExceptionView
python
getsentry__sentry
src/sentry/integrations/api/serializers/rest_framework/doc_integration.py
{ "start": 4076, "end": 4470 }
class ____(Serializer): avatar_photo = AvatarField(required=True) avatar_type = serializers.ChoiceField(choices=(("upload", "upload"))) def validate(self, attrs): attrs = super().validate(attrs) if not attrs.get("avatar_photo"): raise serializers.ValidationError({"avatar_photo"...
DocIntegrationAvatarSerializer
python
google__pytype
pytype/imports/builtin_stubs.py
{ "start": 3291, "end": 4479 }
class ____(base.BuiltinLoader): """Load builtins from the pytype source tree.""" def __init__(self, options): self.options = options def _parse_predefined(self, pytd_subdir, module, as_package=False): """Parse a pyi/pytd file in the pytype source tree.""" try: filename, src = GetPredefinedFile...
BuiltinLoader
python
modin-project__modin
modin/tests/pandas/native_df_interoperability/test_compiler_caster.py
{ "start": 3116, "end": 4165 }
class ____(CalculatorTestQc): "Represents a cloud-hosted query compiler" def get_backend(self): return "Cloud" @classmethod def max_cost(cls): return QCCoercionCost.COST_IMPOSSIBLE def move_to_cost(self, other_qc_cls, api_cls_name, op, arguments): assert op is not None ...
CloudQC
python
joblib__joblib
joblib/numpy_pickle_compat.py
{ "start": 2402, "end": 4163 }
class ____(object): """An object to be persisted instead of numpy arrays. The only thing this object does, is to carry the filename in which the array has been persisted, and the array subclass. """ def __init__(self, filename, subclass, allow_mmap=True): """Constructor. Store the useful i...
NDArrayWrapper