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
GoogleCloudPlatform__python-docs-samples
appengine/standard/requests/main.py
{ "start": 1546, "end": 2020 }
class ____(webapp2.RequestHandler): def get(self): self.response.headers["Content-Type"] = "text/plain" request_id = os.environ.get("REQUEST_LOG_ID") self.response.write("REQUEST_LOG_ID={}".format(request_id)) # [END gae_python_request_ids] app = webapp2.WSGIApplication( [ ("...
RequestIdHandler
python
pyca__cryptography
src/cryptography/x509/base.py
{ "start": 23208, "end": 25998 }
class ____: def __init__( self, serial_number: int | None = None, revocation_date: datetime.datetime | None = None, extensions: list[Extension[ExtensionType]] = [], ): self._serial_number = serial_number self._revocation_date = revocation_date self._extens...
RevokedCertificateBuilder
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/overloadImpl1.py
{ "start": 2496, "end": 3001 }
class ____: ... T_E = TypeVar("T_E", bound=ClassE) @overload def func9() -> None: ... @overload def func9(bar: T_E) -> T_E: ... def func9(bar: T_E | None = None) -> T_E | None: raise NotImplementedError T_int_str = TypeVar("T_int_str", int, str) @overload def func10(option: Literal["a"], var: str) -> st...
ClassE
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py
{ "start": 12650, "end": 14188 }
class ____(GeneratedAirbyteDestination): @public def __init__( self, name: str, host: str, port: int, database: str, username: str, password: Optional[str] = None, jdbc_url_params: Optional[str] = None, ): """Airbyte Destination for Mar...
MariadbColumnstoreDestination
python
huggingface__transformers
src/transformers/models/ovis2/modeling_ovis2.py
{ "start": 2023, "end": 3009 }
class ____(BaseModelOutputWithPast): r""" past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). C...
Ovis2ModelOutputWithPast
python
ray-project__ray
python/ray/serve/_private/long_poll.py
{ "start": 2172, "end": 2223 }
class ____(Enum): TIME_OUT = auto()
LongPollState
python
google__pytype
pytype/tools/xref/indexer.py
{ "start": 4722, "end": 5710 }
class ____: """Store the text and location of a docstring.""" text: str location: source.Location length: int @classmethod def from_node(cls: type[_T], ast: types.ModuleType, node) -> _T | None: """If the first element in node.body is a string, create a docstring.""" # This should only be called ...
DocString
python
joke2k__faker
tests/providers/test_company.py
{ "start": 9549, "end": 11739 }
class ____: """Test pl_PL company provider methods""" def test_regon_checksum(self): assert regon_checksum([1, 2, 3, 4, 5, 6, 7, 8]) == 5 assert regon_checksum([8, 9, 1, 9, 5, 7, 8, 8]) == 3 assert regon_checksum([2, 1, 7, 1, 5, 4, 8, 3]) == 8 assert regon_checksum([7, 9, 3, 5, ...
TestPlPl
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/runs.py
{ "start": 5258, "end": 5418 }
class ____(graphene.Union): class Meta: types = (GraphenePythonError, GrapheneRunTagKeys) name = "RunTagKeysOrError"
GrapheneRunTagKeysOrError
python
pytorch__pytorch
benchmarks/distributed/ddp/benchmark.py
{ "start": 4768, "end": 5258 }
class ____: def __init__(self, device, distributed_backend, bucket_size): self.device = device self.batch_size = 32 self.distributed_backend = distributed_backend self.bucket_size = bucket_size def __str__(self): raise NotImplementedError def create_model(self): ...
Benchmark
python
sqlalchemy__sqlalchemy
examples/dogpile_caching/model.py
{ "start": 512, "end": 712 }
class ____(Base): __tablename__ = "country" id = Column(Integer, primary_key=True) name = Column(String(100), nullable=False) def __init__(self, name): self.name = name
Country
python
Textualize__textual
src/textual/widgets/_data_table.py
{ "start": 4511, "end": 7106 }
class ____(NamedTuple): """A unique identifier for a cell in the DataTable. A cell key is a `(row_key, column_key)` tuple. Even if the cell changes visual location (i.e. moves to a different coordinate in the table), this key can still be used to retrieve it, regardless of where it currently is.""...
CellKey
python
langchain-ai__langchain
libs/core/langchain_core/tracers/memory_stream.py
{ "start": 585, "end": 2815 }
class ____(Generic[T]): def __init__( self, reader_loop: AbstractEventLoop, queue: Queue, done: object ) -> None: """Create a writer for the queue and done object. Args: reader_loop: The event loop to use for the writer. This loop will be used to sch...
_SendStream
python
bokeh__bokeh
src/bokeh/core/property/primitive.py
{ "start": 4080, "end": 4915 }
class ____(PrimitiveProperty[float]): """ Accept floating point values. Args: default (float, optional) : A default value for attributes created from this property to have. help (str or None, optional) : A documentation string for this property. (default: None) Exa...
Float
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/redshift_cluster.py
{ "start": 5497, "end": 6906 }
class ____(AwsBaseWaiterTrigger): """ Trigger for RedshiftResumeClusterOperator. The trigger will asynchronously poll the boto3 API and wait for the Redshift cluster to be in the `available` state. :param cluster_identifier: A unique identifier for the cluster. :param waiter_delay: The amount...
RedshiftResumeClusterTrigger
python
keras-team__keras
keras/src/ops/math_test.py
{ "start": 36655, "end": 38442 }
class ____(testing.TestCase): def test_extract_sequences_init_length_1_stride_1(self): extract_op = kmath.ExtractSequences( sequence_length=1, sequence_stride=1 ) self.assertIsNotNone(extract_op) self.assertEqual(extract_op.sequence_length, 1) self.assertEqual(ext...
ExtractSequencesOpTest
python
ray-project__ray
python/ray/data/_internal/execution/execution_callback.py
{ "start": 389, "end": 3198 }
class ____: """Callback interface for execution events.""" def before_execution_starts(self, executor: "StreamingExecutor"): """Called before the Dataset execution starts.""" ... def on_execution_step(self, executor: "StreamingExecutor"): """Called at each step of the Dataset execu...
ExecutionCallback
python
facelessuser__pymdown-extensions
tests/test_extensions/test_magiclink.py
{ "start": 3287, "end": 3848 }
class ____(util.MdCase): """Test cases for repo link shortening.""" extension = [ 'pymdownx.magiclink', ] extension_configs = { 'pymdownx.magiclink': { 'repo_url_shorthand': True, 'user': 'facelessuser', 'repo': 'pymdown-extensions', 'pro...
TestMagicLinkExternalShorthand
python
pytorch__pytorch
torch/_inductor/codegen/memory_planning.py
{ "start": 18331, "end": 18593 }
class ____(MemoryPlanningLine): """Abstract base class for {Alloc,Dealloc}FromPoolLine""" group: BufferGroup timestep: Optional[int] = None @property def node(self): return self.group.node @dataclasses.dataclass
PoolMemoryPlanningLine
python
has2k1__plotnine
plotnine/themes/elements/element_line.py
{ "start": 176, "end": 2005 }
class ____(element_base): """ theme element: line used for backgrounds and borders parameters ---------- color : str | tuple line color colour : str | tuple alias of color linetype : str | tuple line style. if a string, it should be one of *solid*, *dashed*, ...
element_line
python
openai__gym
tests/test_core.py
{ "start": 1996, "end": 4240 }
class ____(core.Wrapper): def __init__( self, env, observation_space=None, action_space=None, reward_range=None, metadata=None, ): super().__init__(env) if observation_space is not None: # Only set the observation space if not None to t...
NewPropertyWrapper
python
coleifer__peewee
tests/regressions.py
{ "start": 3865, "end": 3936 }
class ____(TestModel): b = ForeignKeyField(DiB) c = TextField()
DiC
python
xlwings__xlwings
xlwings/main.py
{ "start": 142099, "end": 144333 }
class ____: """ The font object can be accessed as an attribute of the range or shape object. * ``mysheet['A1'].font`` * ``mysheet.shapes[0].font`` .. versionadded:: 0.23.0 """ def __init__(self, impl): self.impl = impl @property def api(self): """ Returns...
Font
python
facebook__pyre-check
client/tests/dataclasses_merge_test.py
{ "start": 596, "end": 727 }
class ____: a: Optional[bool] = None b: Basic = field(default_factory=Basic) @dataclass_merge @dataclass(frozen=True)
Nesting
python
walkccc__LeetCode
solutions/1684. Count the Number of Consistent Strings/1684.py
{ "start": 0, "end": 172 }
class ____: def countConsistentStrings(self, allowed: str, words: list[str]) -> int: return sum(all(c in allowed for c in word) for word in words)
Solution
python
Pylons__pyramid
src/pyramid/registry.py
{ "start": 10166, "end": 10308 }
class ____(tuple): """A subtype of tuple used to represent a sequence of predicate values""" global_registry = Registry('global')
predvalseq
python
scipy__scipy
scipy/sparse/linalg/_interface.py
{ "start": 27118, "end": 27501 }
class ____(MatrixLinearOperator): def __init__(self, adjoint_array): self.A = adjoint_array.T.conj() self.args = (adjoint_array,) self.shape = adjoint_array.shape[1], adjoint_array.shape[0] @property def dtype(self): return self.args[0].dtype def _adjoint(self): ...
_AdjointMatrixOperator
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 115530, "end": 116577 }
class ____(BaseModel, extra="forbid"): """ Additional parameters of the search """ hnsw_ef: Optional[int] = Field( default=None, description="Params relevant to HNSW index Size of the beam in a beam-search. Larger the value - more accurate the result, more time required for search.", ...
SearchParams
python
django__django
tests/template_tests/filter_tests/test_safe.py
{ "start": 68, "end": 595 }
class ____(SimpleTestCase): @setup({"safe01": "{{ a }} -- {{ a|safe }}"}) def test_safe01(self): output = self.engine.render_to_string("safe01", {"a": "<b>hello</b>"}) self.assertEqual(output, "&lt;b&gt;hello&lt;/b&gt; -- <b>hello</b>") @setup({"safe02": "{% autoescape off %}{{ a }} -- {{ a...
SafeTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDict21.py
{ "start": 343, "end": 635 }
class ____(TD1, TD2): ... td1: TD1 = {"v1": 0} td2: TD2 = {"v2": ""} td3_1: TD3 = {} td3_2: TD3 = {"v1": 0} td4_1: TD4 = {**td1, **td2} # This should generate an error because td3_1 # does not include the required "v1" entry. td4_2: TD4 = {**td3_1, **td2} td4_3: TD4 = {**td3_2, **td2}
TD4
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 217946, "end": 218589 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("CheckAnnotationEdge"), graphql_name="edges" ) nodes = sgq...
CheckAnnotationConnection
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/news/base.py
{ "start": 275, "end": 3187 }
class ____(BaseReader): """ Simple news article reader. Reads news articles from the web and parses them using the `newspaper` library. Args: text_mode (bool): Whether to load a text version or HTML version of the content (default=True). use_nlp (bool): Whether to use NLP to extract ad...
NewsArticleReader
python
pydata__xarray
xarray/tests/test_conventions.py
{ "start": 22891, "end": 23195 }
class ____(WritableCFDataStore, InMemoryDataStore): def encode_variable(self, var, name=None): """encode one variable""" coder = coding.strings.EncodedStringCoder(allows_unicode=True) var = coder.encode(var, name=name) return var @requires_netCDF4
CFEncodedInMemoryStore
python
pytorch__pytorch
test/functorch/test_vmap.py
{ "start": 227564, "end": 231136 }
class ____(Namespace.TestVmapBase): def _vmap_test(self, *args, **kwargs): return _vmap_test(self, *args, **kwargs) def test__is_all_true(self, device): def test(): def f(x, *, expected_result): result = torch.ops.aten._is_all_true(x) self.assertFalse...
TestVmapDeviceType
python
kamyu104__LeetCode-Solutions
Python/as-far-from-land-as-possible.py
{ "start": 58, "end": 1029 }
class ____(object): def maxDistance(self, grid): """ :type grid: List[List[int]] :rtype: int """ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] q = collections.deque([(i, j) for i in xrange(len(grid)) for j in xrange(len(grid[0])...
Solution
python
pytorch__pytorch
torch/backends/xeon/run_cpu.py
{ "start": 11232, "end": 37716 }
class ____: r"""Class for launcher.""" msg_lib_notfound = ( f"Unable to find the {{0}} library file lib{{1}}.so in $CONDA_PREFIX/lib or $VIRTUAL_ENV/lib \ or /.local/lib/ or /usr/local/lib/ or /usr/local/lib64/ or /usr/lib or /usr/lib64 or \ {expanduser('~')}/.local/lib/ so the LD_PRELOAD environment v...
_Launcher
python
doocs__leetcode
solution/1300-1399/1302.Deepest Leaves Sum/Solution2.py
{ "start": 192, "end": 646 }
class ____: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: def dfs(root, i): nonlocal ans, mx if root is None: return if i == mx: ans += root.val elif i > mx: ans = root.val mx = i ...
Solution
python
tensorflow__tensorflow
tensorflow/python/framework/ops_test.py
{ "start": 115067, "end": 116588 }
class ____(test_util.TensorFlowTestCase): def _get_test_attrs(self): x = gen_control_flow_ops.no_op() try: a = compat.as_text(x.get_attr("_A")) except ValueError: a = None try: b = compat.as_text(x.get_attr("_B")) except ValueError: b = None return (a, b) @test_util...
AttrScopeTest
python
great-expectations__great_expectations
great_expectations/data_context/store/gx_cloud_store_backend.py
{ "start": 2275, "end": 31892 }
class ____(StoreBackend, metaclass=ABCMeta): PAYLOAD_ATTRIBUTES_KEYS: Dict[GXCloudRESTResource, str] = { GXCloudRESTResource.CHECKPOINT: "checkpoint_config", GXCloudRESTResource.DATASOURCE: "datasource_config", GXCloudRESTResource.DATA_CONTEXT: "data_context_config", GXCloudRESTResou...
GXCloudStoreBackend
python
pytorch__pytorch
torch/_inductor/custom_graph_pass.py
{ "start": 3820, "end": 5881 }
class ____(ABC): """ Implement this interface for custom partitioner: 1) The __call__() method contains the implementation of the custom partitioner. 2) The uuid() method enables inductor to cache compiled graphs when your custom partitioner are applied. This method can return any identifier as lo...
CustomPartitionerFn
python
xlwings__xlwings
xlwings/conversion/standard.py
{ "start": 2964, "end": 3654 }
class ____: def __init__(self, options): self.options = options dates_as = options.get("dates", datetime.datetime) self.empty_as = options.get("empty", None) self.dates_handler = _date_handlers.get(dates_as, dates_as) numbers_as = options.get("numbers", None) self.num...
CleanDataFromReadStage
python
Farama-Foundation__Gymnasium
gymnasium/wrappers/stateful_observation.py
{ "start": 1162, "end": 3846 }
class ____( gym.ObservationWrapper[ObsType, ActType, ObsType], gym.utils.RecordConstructorArgs ): """Adds a delay to the returned observation from the environment. Before reaching the :attr:`delay` number of timesteps, returned observations is an array of zeros with the same shape as the observation sp...
DelayObservation
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 22481, "end": 22614 }
class ____(VyperNode): __slots__ = ("arg", "annotation") # base class for stmt nodes. doesn't do anything except classification
arg
python
sqlalchemy__sqlalchemy
test/orm/test_relationship_criteria.py
{ "start": 55376, "end": 61143 }
class ____(testing.fixtures.DeclarativeMappedTest): @classmethod def setup_classes(cls): class HasTemporal: """Mixin that identifies a class as having a timestamp column""" timestamp = Column( DateTime, default=partial(datetime.datetime.now, datet...
TemporalFixtureTest
python
pydata__xarray
xarray/tests/test_indexes.py
{ "start": 11845, "end": 20866 }
class ____: def test_constructor(self) -> None: foo_data = np.array([0, 0, 1], dtype="int64") bar_data = np.array([1.1, 1.2, 1.3], dtype="float64") pd_idx = pd.MultiIndex.from_arrays([foo_data, bar_data], names=("foo", "bar")) index = PandasMultiIndex(pd_idx, "x") assert in...
TestPandasMultiIndex
python
huggingface__transformers
tests/models/olmo3/test_modeling_olmo3.py
{ "start": 1546, "end": 8776 }
class ____(CausalLMModelTest, unittest.TestCase): test_all_params_have_gradient = False model_tester_class = Olmo3ModelTester # Need to use `0.8` instead of `0.9` for `test_cpu_offload` # This is because we are hitting edge cases with the causal_mask buffer model_split_percents = [0.5, 0.7, 0.8] ...
Olmo3ModelTest
python
gevent__gevent
src/greentest/3.10/test_wsgiref.py
{ "start": 1181, "end": 3353 }
class ____(WSGIRequestHandler): """Non-socket HTTP handler""" def setup(self): self.connection = self.request self.rfile, self.wfile = self.connection def finish(self): pass def hello_app(environ,start_response): start_response("200 OK", [ ('Content-Type','text/plain')...
MockHandler
python
PyCQA__pylint
tests/functional/t/too/too_few_public_methods.py
{ "start": 260, "end": 380 }
class ____: """docstring""" def meth1(self): """first""" def meth2(self): """second"""
Klass
python
sqlalchemy__sqlalchemy
test/orm/test_relationships.py
{ "start": 198580, "end": 201659 }
class ____(AssertsCompiledSQL, fixtures.TestBase): """tests for #12843""" __dialect__ = "default" def test_annos_maintained(self, decl_base): class User(decl_base): __tablename__ = "user" id = Column(Integer, primary_key=True) class Address(decl_base): ...
AnnotationsMaintainedTest
python
ansible__ansible
lib/ansible/playbook/attribute.py
{ "start": 7033, "end": 7800 }
class ____(FieldAttribute): def __get__(self, obj, obj_type=None): from ansible.module_utils.compat.paramiko import _paramiko as paramiko from ansible.utils.ssh_functions import check_for_controlpersist value = super().__get__(obj, obj_type) if value == 'smart': value = ...
ConnectionFieldAttribute
python
numba__numba
numba/cuda/tests/nocuda/test_function_resolution.py
{ "start": 268, "end": 1425 }
class ____(unittest.TestCase): def test_fp16_binary_operators(self): from numba.cuda.descriptor import cuda_target ops = (operator.add, operator.iadd, operator.sub, operator.isub, operator.mul, operator.imul) for op in ops: fp16 = types.float16 typingct...
TestFunctionResolution
python
kamyu104__LeetCode-Solutions
Python/evaluate-boolean-binary-tree.py
{ "start": 1216, "end": 1679 }
class ____(object): def evaluateTree(self, root): """ :type root: Optional[TreeNode] :rtype: bool """ INF = float("inf") OP = { 2: lambda x, y: x or y, 3: lambda x, y: x and y, } def dfs(node): if node.left ...
Solution2
python
google__pytype
pytype_extensions/test_pytype_extensions.py
{ "start": 579, "end": 853 }
class ____(test_base.BaseTest): @classmethod def setUpClass(cls): super().setUpClass() cls.Check = _Wrap(cls.Check) cls.CheckWithErrors = _Wrap(cls.CheckWithErrors) cls.Infer = _Wrap(cls.Infer) cls.InferWithErrors = _Wrap(cls.InferWithErrors)
CodeTest
python
dateutil__dateutil
tests/_common.py
{ "start": 5373, "end": 6004 }
class ____(object): """ A class analogous to NaN that has operations defined for any type. """ def _op(self, other): return self # Operation with NotAValue returns NotAValue def _cmp(self, other): return False __add__ = __radd__ = _op __sub__ = __rsub__ = _op ...
NotAValueClass
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-dashvector/llama_index/vector_stores/dashvector/base.py
{ "start": 1190, "end": 7658 }
class ____(BasePydanticVectorStore): """ Dash Vector Store. In this vector store, embeddings and docs are stored within a DashVector collection. During query time, the index uses DashVector to query for the top k most similar nodes. Args: collection (Optional[dashvector.Collection...
DashVectorStore
python
walkccc__LeetCode
solutions/3127. Make a Square with the Same Color/3127.py
{ "start": 0, "end": 400 }
class ____: def canMakeSquare(self, grid: list[list[str]]) -> bool: for i in range(2): for j in range(2): black = 0 white = 0 for x in range(2): for y in range(2): if grid[i + x][j + y] == 'B': black += 1 else: white += 1 ...
Solution
python
urllib3__urllib3
test/with_dummyserver/test_https.py
{ "start": 51798, "end": 52278 }
class ____: def test_can_validate_ip_san(self, ipv4_san_server: ServerConfig) -> None: """Ensure that urllib3 can validate SANs with IP addresses in them.""" with HTTPSConnectionPool( ipv4_san_server.host, ipv4_san_server.port, cert_reqs="CERT_REQUIRED", ...
TestHTTPS_IPV4SAN
python
getsentry__sentry
src/sentry/api/helpers/actionable_items_helper.py
{ "start": 126, "end": 2787 }
class ____: HIGH = 1 MEDIUM = 2 LOW = 3 UNKNOWN = 4 fileNameBlocklist = ["@webkit-masked-url"] priority_ranking = { # Low Priority EventError.CLOCK_DRIFT: ActionPriority.LOW, EventError.FETCH_GENERIC_ERROR: ActionPriority.LOW, EventError.FUTURE_TIMESTAMP: ActionPriority.LOW, Event...
ActionPriority
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/selection.py
{ "start": 444, "end": 619 }
class ____(Enum): EMACS = "EMACS" # Yank like emacs. VI_AFTER = "VI_AFTER" # When pressing 'p' in Vi. VI_BEFORE = "VI_BEFORE" # When pressing 'P' in Vi.
PasteMode
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dataplex.py
{ "start": 40615, "end": 41728 }
class ____: @mock.patch(ENTRY_STR) @mock.patch(HOOK_STR) def test_execute(self, hook_mock, entry_mock): op = DataplexCatalogCreateEntryOperator( task_id="create_task", project_id=PROJECT_ID, location=REGION, entry_id=ENTRY_NAME, entry_group...
TestDataplexCatalogCreateEntryOperator
python
getsentry__sentry
src/sentry/seer/anomaly_detection/types.py
{ "start": 2099, "end": 2501 }
class ____(StrEnum): """All combinations of multi select fields for anomaly detection alerts We do not anticipate adding more """ AUTO = "auto" HOURLY = "hourly" DAILY = "daily" WEEKLY = "weekly" HOURLY_DAILY = "hourly_daily" HOURLY_WEEKLY = "hourly_weekly" HOURLY_DAILY_WEEKLY =...
AnomalyDetectionSeasonality
python
huggingface__transformers
src/transformers/models/wav2vec2_bert/modular_wav2vec2_bert.py
{ "start": 38622, "end": 41097 }
class ____(Wav2Vec2ConformerForAudioFrameClassification): def __init__(self, config): super().__init__(config) def freeze_feature_encoder(self): raise AttributeError("Not needed for Wav2Vec2Bert") def forward( self, input_features: Optional[torch.Tensor], attention_...
Wav2Vec2BertForAudioFrameClassification
python
falconry__falcon
tests/test_response_context.py
{ "start": 235, "end": 1556 }
class ____: def test_default_response_context(self, resp_type): resp = resp_type() resp.context.hello = 'World!' assert resp.context.hello == 'World!' assert resp.context['hello'] == 'World!' resp.context['note'] = 'Default Response.context_type used to be dict.' as...
TestResponseContext
python
huggingface__transformers
src/transformers/models/chameleon/image_processing_chameleon_fast.py
{ "start": 1053, "end": 4042 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.LANCZOS image_mean = [1.0, 1.0, 1.0] image_std = [1.0, 1.0, 1.0] size = {"shortest_edge": 512} default_to_square = False crop_size = {"height": 512, "width": 512} do_resize = True do_center_crop = True do_rescale = Tru...
ChameleonImageProcessorFast
python
django__django
django/views/debug.py
{ "start": 3598, "end": 11965 }
class ____: """ Use annotations made by the sensitive_post_parameters and sensitive_variables decorators to filter out sensitive information. """ cleansed_substitute = "********************" hidden_settings = _lazy_re_compile( "API|AUTH|TOKEN|KEY|SECRET|PASS|SIGNATURE|HTTP_COOKIE", flag...
SafeExceptionReporterFilter
python
anthropics__anthropic-sdk-python
src/anthropic/_base_client.py
{ "start": 31529, "end": 47993 }
class ____(BaseClient[httpx.Client, Stream[Any]]): _client: httpx.Client _default_stream_cls: type[Stream[Any]] | None = None def __init__( self, *, version: str, base_url: str | URL, max_retries: int = DEFAULT_MAX_RETRIES, timeout: float | Timeout | None | N...
SyncAPIClient
python
pytorch__pytorch
test/distributed/checkpoint/test_file_system_checkpoint_cpu.py
{ "start": 4686, "end": 6125 }
class ____(TestCase): @parametrize("thread_count", _THREAD_COUNTS) def test_read_write_tensor_and_blob(self, thread_count) -> None: with tempfile.TemporaryDirectory() as path: state_dict_to_save = MyTestModule().state_dict() state_dict_to_save["test_blob"] = BlobState(b"SomeBlobF...
TestDistributedStateDictSaveLoadRot13
python
streamlit__streamlit
lib/streamlit/errors.py
{ "start": 6641, "end": 7075 }
class ____(LocalizableStreamlitException): """Exception raised when an invalid URL is specified for any of the menu items except for “About”.""" def __init__(self, url: str) -> None: super().__init__( '"{url}" is a not a valid URL. ' 'You must use a fully qualified domain beginn...
StreamlitInvalidURLError
python
skorch-dev__skorch
skorch/tests/callbacks/test_scoring.py
{ "start": 18421, "end": 31727 }
class ____: @pytest.fixture(params=[{'use_caching': True}, {'use_caching': False}]) def scoring_cls(self, request): from skorch.callbacks import BatchScoring return partial(BatchScoring, **request.param) @pytest.fixture def mse_scoring(self, scoring_cls): return scoring_cls( ...
TestBatchScoring
python
readthedocs__readthedocs.org
readthedocs/projects/filters.py
{ "start": 3300, "end": 5723 }
class ____(OrderingFilter): """ Project list sort ordering django_filters filter. Django-filter is highly opionated, and the default model filters do not work well with empty/null values in the filter choices. In our case, empty/null values are used for a default query. So, to make this work, we wi...
ProjectSortOrderingFilter
python
apache__airflow
providers/slack/src/airflow/providers/slack/hooks/slack_webhook.py
{ "start": 2466, "end": 16989 }
class ____(BaseHook): """ This class provide a thin wrapper around the ``slack_sdk.WebhookClient``. This hook allows you to post messages to Slack by using Incoming Webhooks. .. seealso:: - :ref:`Slack Incoming Webhook connection <howto/connection:slack-incoming-webhook>` - https://api...
SlackWebhookHook
python
python-pillow__Pillow
src/PIL/GifImagePlugin.py
{ "start": 1452, "end": 1963 }
class ____(IntEnum): """.. versionadded:: 9.1.0""" RGB_AFTER_FIRST = 0 RGB_AFTER_DIFFERENT_PALETTE_ONLY = 1 RGB_ALWAYS = 2 #: .. versionadded:: 9.1.0 LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST # -------------------------------------------------------------------- # Identify/read GIF files ...
LoadingStrategy
python
PrefectHQ__prefect
src/prefect/cache_policies.py
{ "start": 10357, "end": 10890 }
class ____(CachePolicy): """ Returns either the prevailing flow run ID, or if not found, the prevailing task run ID. """ def compute_key( self, task_ctx: TaskRunContext, inputs: dict[str, Any], flow_parameters: dict[str, Any], **kwargs: Any, ) -> Optional...
RunId
python
kamyu104__LeetCode-Solutions
Python/lfu-cache.py
{ "start": 1908, "end": 2099 }
class ____(object): def __init__(self, key, value, freq): self.key = key self.val = value self.freq = freq self.next = None self.prev = None
ListNode
python
justquick__django-activity-stream
actstream/drf/views.py
{ "start": 2038, "end": 7118 }
class ____(DefaultModelViewSet): queryset = models.Action.objects.public().order_by('-timestamp', '-id').prefetch_related() serializer_class = serializers.ActionSerializer @action(detail=False, permission_classes=[permissions.IsAuthenticated], methods=['POST'], serializer_class=serializers.SendActionSerial...
ActionViewSet
python
tensorflow__tensorflow
tensorflow/python/ops/linalg/linear_operator_circulant.py
{ "start": 28766, "end": 40797 }
class ____(_BaseLinearOperatorCirculant): """`LinearOperator` acting like a circulant matrix. This operator acts like a circulant matrix `A` with shape `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is an `N x N` m...
LinearOperatorCirculant
python
MongoEngine__mongoengine
tests/queryset/test_field_list.py
{ "start": 108, "end": 2518 }
class ____: def test_empty(self): q = QueryFieldList() assert not q q = QueryFieldList(always_include=["_cls"]) assert not q def test_include_include(self): q = QueryFieldList() q += QueryFieldList( fields=["a", "b"], value=QueryFieldList.ONLY, _only...
TestQueryFieldList
python
nedbat__coveragepy
tests/test_context.py
{ "start": 8178, "end": 8343 }
class ____: def meth(self) -> str | None: return get_qualname() @property def a_property(self) -> str | None: return get_qualname()
Parent
python
pdm-project__pdm
src/pdm/formats/base.py
{ "start": 499, "end": 895 }
class ____(Exception): """A special exception that preserves the partial metadata that are already resolved.""" def __init__(self, errors: list[str], *, data: dict[str, Any], settings: dict[str, Any]) -> None: self.errors = errors self.data = data self.settings = settings def __str...
MetaConvertError
python
weaviate__weaviate-python-client
weaviate/collections/classes/grpc.py
{ "start": 7361, "end": 7537 }
class ____(_WeaviateInput): """Define how the query's rerank operation should be performed.""" prop: str query: Optional[str] = Field(default=None) @dataclass
Rerank
python
django__django
tests/modeladmin/test_checks.py
{ "start": 36930, "end": 37484 }
class ____(CheckTestCase): def test_invalid_type(self): class TestModelAdmin(ModelAdmin): list_select_related = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_select_related' must be a boolean, tuple or list.", ...
ListSelectRelatedCheckTests
python
huggingface__transformers
tests/models/idefics/test_modeling_idefics.py
{ "start": 25679, "end": 36018 }
class ____(IdeficsModelTest, GenerationTesterMixin, unittest.TestCase): all_model_classes = (IdeficsForVisionText2Text,) if is_torch_available() else () def setUp(self): self.model_tester = IdeficsModelTester( self, modality_type_vocab_size=3, ) self.config_teste...
IdeficsForVisionText2TextTest
python
bokeh__bokeh
tests/unit/bokeh/colors/test_color__colors.py
{ "start": 1141, "end": 2964 }
class ____: def test_clamp(self) -> None: assert bcc.Color.clamp(10) == 10 assert bcc.Color.clamp(10, 20) == 10 assert bcc.Color.clamp(10, 5) == 5 assert bcc.Color.clamp(-10) == 0 def test_darken(self) -> None: c = bcc.HSL(10, 0.2, 0.2, 0.2) c2 = c.darken(0.1) ...
Test_Color
python
fastapi__sqlmodel
docs_src/tutorial/one/tutorial003.py
{ "start": 100, "end": 1645 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_u...
Hero
python
pytest-dev__pytest
src/_pytest/warning_types.py
{ "start": 1113, "end": 1270 }
class ____(PytestDeprecationWarning): """Warning class for features that will be removed in pytest 9.""" __module__ = "pytest"
PytestRemovedIn9Warning
python
sanic-org__sanic
sanic/signals.py
{ "start": 3054, "end": 4011 }
class ____: """A record representing a future waiting for a signal""" signal: Signal event_definition: str trigger: str = "" requirements: Optional[dict[str, str]] = None exclusive: bool = True future: Optional[asyncio.Future] = None async def wait(self): """Block until the si...
SignalWaiter
python
spack__spack
lib/spack/spack/vendor/pyrsistent/_precord.py
{ "start": 953, "end": 4448 }
class ____(PMap, CheckedType, metaclass=_PRecordMeta): """ A PRecord is a PMap with a fixed set of specified fields. Records are declared as python classes inheriting from PRecord. Because it is a PMap it has full support for all Mapping methods such as iteration and element access using subscript notat...
PRecord
python
ray-project__ray
python/ray/air/execution/resources/request.py
{ "start": 744, "end": 6282 }
class ____: """Request for resources. This class is used to define a resource request. A resource request comprises one or more bundles of resources and instructions on the scheduling behavior. The resource request can be submitted to a resource manager, which will schedule the resources. Dependin...
ResourceRequest
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/core/serialization/serialized_data.py
{ "start": 822, "end": 1206 }
class ____: webserver_url: str dag_id: str task_id: str metadata: dict[str, Any] @property def dag_url(self) -> str: return f"{self.webserver_url}/dags/{self.dag_id}" @cached_property def downstream_task_ids(self) -> list[str]: return check.is_list(self.metadata["downst...
TaskInfo
python
dagster-io__dagster
python_modules/libraries/dagstermill/dagstermill/examples/repository.py
{ "start": 3428, "end": 3592 }
class ____(Config): greeting: str = "hello" hello_world_config_struct = test_nb_op("hello_world_config_struct", config_schema=HelloWorldConfig)
HelloWorldConfig
python
ray-project__ray
python/ray/serve/scripts.py
{ "start": 28608, "end": 30124 }
class ____(yaml.SafeDumper): """YAML dumper object with custom formatting for ServeDeploySchema. Reformat config to follow this spacing with appropriate line breaks: --------------------------------------------------------------- proxy_location: EveryNode http_options: host: 0.0.0.0 po...
ServeDeploySchemaDumper
python
pandas-dev__pandas
pandas/io/json/_json.py
{ "start": 35668, "end": 42743 }
class ____: _split_keys: tuple[str, ...] _default_orient: str _STAMP_UNITS = ("s", "ms", "us", "ns") _MIN_STAMPS = { "s": 31536000, "ms": 31536000000, "us": 31536000000000, "ns": 31536000000000000, } json: str def __init__( self, json: str, ...
Parser
python
celery__celery
celery/concurrency/prefork.py
{ "start": 3150, "end": 5850 }
class ____(BasePool): """Multiprocessing Pool implementation.""" Pool = AsynPool BlockingPool = BlockingPool uses_semaphore = True write_stats = None def on_start(self): forking_enable(self.forking_enable) Pool = (self.BlockingPool if self.options.get('threads', True) ...
TaskPool
python
huggingface__transformers
tests/models/gemma3/test_modeling_gemma3.py
{ "start": 15346, "end": 20447 }
class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): all_model_classes = ( ( Gemma3Model, Gemma3ForConditionalGeneration, Gemma3ForSequenceClassification, ) if is_torch_available() else () ) all_generative_model_classes =...
Gemma3Vision2TextModelTest
python
pandas-dev__pandas
pandas/tests/indexes/string/test_indexing.py
{ "start": 1672, "end": 3668 }
class ____: @pytest.mark.parametrize( "method,expected", [ ("pad", [-1, 0, 1, 1]), ("backfill", [0, 0, 1, -1]), ], ) def test_get_indexer_strings(self, any_string_dtype, method, expected): expected = np.array(expected, dtype=np.intp) index = In...
TestGetIndexer
python
py-pdf__pypdf
pypdf/generic/_data_structures.py
{ "start": 57776, "end": 63488 }
class ____(TreeObject): """ A class representing a destination within a PDF file. See section 12.3.2 of the PDF 2.0 reference. Args: title: Title of this destination. page: Reference to the page of this destination. Should be an instance of :class:`IndirectObject<pypdf.gene...
Destination
python
coleifer__peewee
tests/models.py
{ "start": 128585, "end": 130371 }
class ____(BaseTestCase): def test_foreign_key_field_descriptors(self): class User(Model): pass class T0(Model): user = ForeignKeyField(User) class T1(Model): user = ForeignKeyField(User, column_name='uid') class T2(Model): user = ForeignKeyField(U...
TestForeignKeyFieldDescriptors
python
lazyprogrammer__machine_learning_examples
supervised_class/dt.py
{ "start": 738, "end": 5567 }
class ____: def __init__(self, depth=1, max_depth=None): print('depth:', depth) self.depth = depth self.max_depth = max_depth if self.max_depth is not None and self.max_depth < self.depth: raise Exception("depth > max_depth") def fit(self, X, Y): if len(Y) ==...
TreeNode
python
huggingface__transformers
src/transformers/models/glm46v/image_processing_glm46v_fast.py
{ "start": 1697, "end": 7503 }
class ____(BaseImageProcessorFast): do_resize = True resample = PILImageResampling.BICUBIC size = {"shortest_edge": 112 * 112, "longest_edge": 28 * 28 * 15000} do_rescale = True do_normalize = True image_mean = OPENAI_CLIP_MEAN image_std = OPENAI_CLIP_STD do_convert_rgb = True patch_...
Glm46VImageProcessorFast
python
vyperlang__vyper
vyper/compiler/phases.py
{ "start": 1189, "end": 14219 }
class ____: """ Object for fetching and storing compiler data for a Vyper contract. This object acts as a wrapper over the pure compiler functions, triggering compilation phases as needed and providing the data for use when generating the final compiler outputs. Attributes ---------- v...
CompilerData