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 | celery__celery | t/unit/security/case.py | {
"start": 16,
"end": 109
} | class ____:
def setup_method(self):
pytest.importorskip('cryptography')
| SecurityCase |
python | tornadoweb__tornado | tornado/test/httpclient_test.py | {
"start": 3814,
"end": 4453
} | class ____(RequestHandler):
def get(self) -> None:
# set Content-Encoding manually to avoid automatic gzip encoding
self.set_header("Content-Type", "text/plain")
self.set_header("Content-Encoding", "gzip")
# Triggering the potential bug seems to depend on input length.
# This... | InvalidGzipHandler |
python | eth-brownie__brownie | brownie/test/managers/runner.py | {
"start": 19163,
"end": 21034
} | class ____(PytestBrownieRunner):
"""
Brownie plugin xdist worker hooks.
Hooks in this class are loaded on worker processes when using xdist.
"""
def __init__(self, config, project):
self.workerid = int("".join(i for i in config.workerinput["workerid"] if i.isdigit()))
# network ID... | PytestBrownieXdistRunner |
python | pytorch__pytorch | torch/utils/checkpoint.py | {
"start": 42565,
"end": 45819
} | class ____(RuntimeError):
pass
def _get_debug_context_and_cb() -> Tuple[Callable[[], Any], Callable[[CheckpointError], None]]:
# This function returns the context_fn and error_cb to be used by the
# checkpointing mechanism. error_cb is invoked when an error is detected
# during unpack.
# record_c... | CheckpointError |
python | getsentry__sentry | tests/snuba/sessions/test_sessions.py | {
"start": 34732,
"end": 41070
} | class ____(TestCase, BaseMetricsTestCase):
"""
TestClass that tests that `get_current_and_previous_crash_free_rates` returns the correct
`currentCrashFreeRate` and `previousCrashFreeRate` for each project
TestData:
Project 1:
In the last 24h -> 2 Exited Sessions / 2 Total Sessions -> 100% C... | GetCrashFreeRateTestCase |
python | ipython__ipython | IPython/core/formatters.py | {
"start": 27458,
"end": 27967
} | class ____(BaseFormatter):
"""A PNG formatter.
To define the callables that compute the PNG representation of your
objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
or :meth:`for_type_by_name` methods to register functions that handle
this.
The return value of this format... | PNGFormatter |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchClass1.py | {
"start": 12155,
"end": 12226
} | class ____(Generic[T]):
__match_args__ = ("x",)
x: list[T]
| ClassE |
python | anthropics__anthropic-sdk-python | src/anthropic/types/raw_message_start_event.py | {
"start": 225,
"end": 321
} | class ____(BaseModel):
message: Message
type: Literal["message_start"]
| RawMessageStartEvent |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 93401,
"end": 95418
} | class ____(Response):
"""
Response of projects.get_hyperparam_values endpoint.
:param total: Total number of distinct parameter values
:type total: int
:param values: The list of the unique values for the parameter
:type values: Sequence[str]
"""
_service = "projects"
_action = "ge... | GetHyperparamValuesResponse |
python | networkx__networkx | networkx/algorithms/tests/test_euler.py | {
"start": 5889,
"end": 6429
} | class ____:
def testfind_path_start(self):
find_path_start = nx.algorithms.euler._find_path_start
# Test digraphs return correct starting node.
G = nx.path_graph(6, create_using=nx.DiGraph)
assert find_path_start(G) == 0
edges = [(0, 1), (1, 2), (2, 0), (4, 0)]
assert... | TestFindPathStart |
python | readthedocs__readthedocs.org | readthedocs/core/admin.py | {
"start": 2323,
"end": 4170
} | class ____(ExtraSimpleHistoryAdmin, UserAdminImpersonateMixin, UserAdmin):
"""Admin configuration for User."""
list_display = (
"username",
"email",
"first_name",
"last_name",
"is_staff",
"is_banned",
)
list_filter = (UserProjectFilter,) + UserAdmin.list_... | UserAdminExtra |
python | django-mptt__django-mptt | tests/myapp/models.py | {
"start": 3711,
"end": 3923
} | class ____(MPTTModel):
parent = TreeForeignKey(
"self", null=True, blank=True, related_name="children", on_delete=models.CASCADE
)
class MPTTMeta:
left_attr = "testing"
| NewStyleMPTTMeta |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/ValueLabel.py | {
"start": 116,
"end": 3501
} | class ____(QtWidgets.QLabel):
"""
QLabel specifically for displaying numerical values.
Extends QLabel adding some extra functionality:
- displaying units with si prefix
- built-in exponential averaging
"""
def __init__(self, parent=None, suffix='', siPrefix=False, averageTime=0, fo... | ValueLabel |
python | doocs__leetcode | solution/1000-1099/1041.Robot Bounded In Circle/Solution.py | {
"start": 0,
"end": 373
} | class ____:
def isRobotBounded(self, instructions: str) -> bool:
k = 0
dist = [0] * 4
for c in instructions:
if c == 'L':
k = (k + 1) % 4
elif c == 'R':
k = (k + 3) % 4
else:
dist[k] += 1
return (dist... | Solution |
python | tensorflow__tensorflow | tensorflow/python/distribute/collective_all_reduce_strategy.py | {
"start": 9807,
"end": 11538
} | class ____(
CollectiveAllReduceStrategy,
metaclass=_CollectiveAllReduceStrategyExperimentalMeta,
):
__doc__ = CollectiveAllReduceStrategy.__doc__
@deprecation.deprecated(
None, "use distribute.MultiWorkerMirroredStrategy instead"
)
def __init__(
self,
communication=collective_util.Co... | _CollectiveAllReduceStrategyExperimental |
python | run-llama__llama_index | llama-index-integrations/indices/llama-index-indices-managed-postgresml/llama_index/indices/managed/postgresml/retriever.py | {
"start": 499,
"end": 3348
} | class ____(BaseRetriever):
"""
PostgresML Retriever.
Args:
index (PostgresMLIndex): the PostgresML Index
"""
def __init__(
self,
index: PostgresMLIndex,
callback_manager: Optional[CallbackManager] = None,
pgml_query: Optional[Dict[str, Any]] = None,
... | PostgresMLRetriever |
python | astropy__astropy | astropy/units/tests/test_quantity.py | {
"start": 32268,
"end": 64278
} | class ____:
scalarintq = u.Quantity(1, unit="m", dtype=int)
scalarfloatq = u.Quantity(1.3, unit="m")
arrq = u.Quantity([1, 2.3, 8.9], unit="m")
scalar_complex_q = u.Quantity(complex(1.0, 2.0))
scalar_big_complex_q = u.Quantity(complex(1.0, 2.0e27) * 1e25)
scalar_big_neg_complex_q = u.Quantity(c... | TestQuantityDisplay |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/interfaces.py | {
"start": 3610,
"end": 4180
} | class ____(Protocol):
"""protocol representing a :pep:`249` database connection.
.. versionadded:: 2.0
.. seealso::
`Connection Objects <https://www.python.org/dev/peps/pep-0249/#connection-objects>`_
- in :pep:`249`
""" # noqa: E501
def close(self) -> None: ...
def commit... | DBAPIConnection |
python | huggingface__transformers | tests/models/xglm/test_modeling_xglm.py | {
"start": 13165,
"end": 20784
} | class ____(unittest.TestCase):
def tearDown(self):
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
cleanup(torch_device, gc_collect=True)
def _test_lm_generate_xglm_helper(
self,
gradient_checkpointing=False,
verify_outputs=True,
... | XGLMModelLanguageGenerationTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/ingestion/data_sinks.py | {
"start": 582,
"end": 4065
} | class ____(Enum):
@classmethod
def from_component(
cls, component: BasePydanticVectorStore
) -> "ConfigurableComponent":
component_class = type(component)
for component_type in cls:
if component_type.value.component_type == component_class:
return componen... | ConfigurableComponent |
python | pytorch__pytorch | torch/_inductor/config.py | {
"start": 83706,
"end": 88045
} | class ____:
# master switch for all debugging flags below
enabled = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1"
# save real tensors
save_real_tensors = os.environ.get("TORCH_COMPILE_DEBUG_SAVE_REAL", "0") == "1"
# Save debug information to a temporary directory
# If not specified, a temp... | trace |
python | falconry__falcon | falcon/inspect.py | {
"start": 9151,
"end": 9815
} | class ____:
__visit_name__ = 'N/A'
def to_string(self, verbose: bool = False, internal: bool = False) -> str:
"""Return a string representation of this class.
Args:
verbose (bool, optional): Adds more information. Defaults to False.
internal (bool, optional): Also inclu... | _Traversable |
python | jina-ai__jina | tests/integration/hub_usage/dummyhub_pretrained/__init__.py | {
"start": 208,
"end": 430
} | class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
raise ModelCheckpointNotExist
def craft(self, *args, **kwargs) -> Dict:
pass
| DummyPretrainedExecutor |
python | huggingface__transformers | src/transformers/models/altclip/processing_altclip.py | {
"start": 775,
"end": 1556
} | class ____(ProcessorMixin):
r"""
Constructs a AltCLIP processor which wraps a CLIP image processor and a XLM-Roberta tokenizer into a single
processor.
[`AltCLIPProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`XLMRobertaTokenizerFast`]. See
the [`~AltCLIPProcessor.__call__... | AltCLIPProcessor |
python | has2k1__plotnine | plotnine/stats/stat_bin_2d.py | {
"start": 246,
"end": 5305
} | class ____(stat):
"""
2 Dimensional bin counts
{usage}
Parameters
----------
{common_parameters}
bins : int, default=30
Number of bins. Overridden by binwidth.
breaks : array_like | tuple[array_like, array_like] , default=None
Bin boundaries. This supersedes the `binwid... | stat_bin_2d |
python | readthedocs__readthedocs.org | readthedocs/api/v3/views.py | {
"start": 14782,
"end": 16222
} | class ____(BuildsViewSet, CreateModelMixin):
def get_serializer_class(self):
if self.action == "create":
return BuildCreateSerializer
return super().get_serializer_class()
def create(self, request, **kwargs): # pylint: disable=arguments-differ
project = self._get_parent_pr... | BuildsCreateViewSet |
python | openai__openai-python | src/openai/types/responses/response_input_item_param.py | {
"start": 2125,
"end": 2774
} | class ____(TypedDict, total=False):
content: Required[ResponseInputMessageContentListParam]
"""
A list of one or many input items to the model, containing different content
types.
"""
role: Required[Literal["user", "system", "developer"]]
"""The role of the message input. One of `user`, `sy... | Message |
python | ray-project__ray | python/ray/data/tests/test_autoscaler.py | {
"start": 11853,
"end": 12075
} | class ____:
def __init__(self, barrier):
self._barrier = barrier
def __call__(self, x):
ray.get(self._barrier.wait.remote(), timeout=10)
return x
@ray.remote(max_concurrency=10)
| BarrierWaiter |
python | bokeh__bokeh | tests/unit/bokeh/core/test_has_props.py | {
"start": 15072,
"end": 15213
} | class ____(hp.HasProps, hp.Local):
f4 = Int(default=4)
f3 = Int(default=3)
f2 = Int(default=2)
f1 = Int(default=1)
| Some3HasProps |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_scatter11.py | {
"start": 315,
"end": 1590
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_scatter11.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.g... | TestCompareXLSXFiles |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ROI.py | {
"start": 66538,
"end": 69518
} | class ____(object):
"""Implements default mouse drag behavior for ROI (not for ROI handles).
"""
def __init__(self, roi):
self.roi = roi
self.dragMode = None
self.startState = None
self.snapModifier = QtCore.Qt.KeyboardModifier.ControlModifier
self.translateModifier =... | MouseDragHandler |
python | kamyu104__LeetCode-Solutions | Python/take-gifts-from-the-richest-pile.py | {
"start": 59,
"end": 450
} | class ____(object):
def pickGifts(self, gifts, k):
"""
:type gifts: List[int]
:type k: int
:rtype: int
"""
for i, x in enumerate(gifts):
gifts[i] = -x
heapq.heapify(gifts)
for _ in xrange(k):
x = heapq.heappop(gifts)
... | Solution |
python | ray-project__ray | release/train_tests/benchmark/recsys/torchrec_runner.py | {
"start": 481,
"end": 4674
} | class ____(TrainLoopRunner):
def _setup(self):
if self.factory.benchmark_config.mock_gpu:
raise ValueError("Mock GPU is not supported for running TorchRec.")
self.model = self.factory.get_model()
# TODO: This code depends on the model having a fused_optimizer,
# which i... | TorchRecRunner |
python | protocolbuffers__protobuf | python/python_version_test.py | {
"start": 380,
"end": 849
} | class ____(unittest.TestCase):
def testPython3(self):
"""Test that we can import nested import public messages."""
exp = os.getenv('KOKORO_PYTHON_VERSION', '')
if not exp:
print('No system python version found, skipping check', file=sys.stderr)
return
self.assertTrue(
sys.version... | PythonVersionTest |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 121301,
"end": 121451
} | class ____:
xlTextVisualLTR = 1 # from enum XlTextVisualLayoutType
xlTextVisualRTL = 2 # from enum XlTextVisualLayoutType
| TextVisualLayoutType |
python | getsentry__sentry | src/sentry/analytics/events/eventuser_equality_check.py | {
"start": 81,
"end": 330
} | class ____(analytics.Event):
event_id: str
project_id: int
group_id: int
snuba_eventuser_equality: bool
event_eventuser_equality: bool
snuba_event_equality: bool
analytics.register(EventUserEqualityCheck)
| EventUserEqualityCheck |
python | ray-project__ray | python/ray/tests/spark/test_basic.py | {
"start": 9430,
"end": 10054
} | class ____(RayOnSparkCPUClusterTestBase):
@classmethod
def setup_class(cls):
cls.num_total_cpus = 2
cls.num_total_gpus = 0
cls.num_cpus_per_spark_task = 1
cls.num_gpus_per_spark_task = 0
cls.max_spark_tasks = 2
os.environ["SPARK_WORKER_CORES"] = "2"
cls.sp... | TestBasicSparkCluster |
python | python-pillow__Pillow | src/PIL/Image.py | {
"start": 13275,
"end": 107360
} | class ____:
"""
This class represents an image object. To create
:py:class:`~PIL.Image.Image` objects, use the appropriate factory
functions. There's hardly ever any reason to call the Image constructor
directly.
* :py:func:`~PIL.Image.open`
* :py:func:`~PIL.Image.new`
* :py:func:`~PI... | Image |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/non_slot_assignment.py | {
"start": 220,
"end": 462
} | class ____:
__slots__ = ("name", "surname")
def __init__(self, name, middle_name):
self.name = name
self.middle_name = middle_name # [assigning-non-slot]
self.setup()
def setup(self):
pass
| StudentB |
python | getsentry__sentry | tests/sentry/tasks/test_statistical_detectors.py | {
"start": 41906,
"end": 54559
} | class ____(ProfilesSnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.now = before_now(minutes=10)
self.hour_ago = (self.now - timedelta(hours=1)).replace(minute=0, second=0, microsecond=0)
self.projects = [
self.create_project(organization=self.organization, ... | FunctionsTasksTest |
python | spack__spack | lib/spack/spack/fetch_strategy.py | {
"start": 22227,
"end": 23100
} | class ____(URLFetchStrategy):
def __init__(self, *, url: str, checksum: Optional[str] = None, **kwargs):
super().__init__(url=url, checksum=checksum, **kwargs)
self._urlopen = kwargs.get("_urlopen", spack.oci.opener.urlopen)
@_needs_stage
def fetch(self):
file = self.stage.save_fil... | OCIRegistryFetchStrategy |
python | tensorflow__tensorflow | tensorflow/python/eager/context.py | {
"start": 7537,
"end": 9908
} | class ____:
"""Options applied at call sites of eager functions.
Eager functions are functions decorated with tf.contrib.eager.defun.
"""
__slots__ = ["_config_proto_serialized", "_executor_type"]
def __init__(self, executor_type=None, config_proto=None):
"""Constructor.
Args:
executor_type:... | FunctionCallOptions |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 502950,
"end": 503267
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("ProjectNext", graphql_name="node")
| ProjectNextEdge |
python | patrick-kidger__equinox | equinox/internal/_getkey.py | {
"start": 392,
"end": 1088
} | class ____:
"""Designed for use as a fixture in tests.
!!! Example
```python
# tests/conftest.py
@pytest.fixture
def getkey():
return eqxi.GetKey()
```
Do not use this in any other context; the random seed generation gives deliberate
non-determinis... | GetKey |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/hash_test4/package.py | {
"start": 217,
"end": 687
} | class ____(Package):
"""This package isn't compared with others, but it contains constructs
that package hashing logic has tripped over in the past.
"""
homepage = "http://www.hashtest4.org"
url = "http://www.hashtest1.org/downloads/hashtest4-1.1.tar.bz2"
version("1.1", md5="a" * 32)
def ... | HashTest4 |
python | wandb__wandb | wandb/sdk/data_types/audio.py | {
"start": 302,
"end": 6385
} | class ____(BatchableMedia):
"""W&B class for audio clips."""
_log_type = "audio-file"
def __init__(
self,
data_or_path: Union[
str,
pathlib.Path,
list,
"np.ndarray",
],
sample_rate: Optional[int] = None,
caption: Optio... | Audio |
python | optuna__optuna | tests/storages_tests/rdb_tests/test_models.py | {
"start": 16452,
"end": 16888
} | class ____:
@staticmethod
def test_version_info_id_constraint(session: Session) -> None:
session.add(VersionInfoModel(schema_version=1, library_version="0.0.1"))
session.commit()
# Test check constraint of version_info_id.
session.add(VersionInfoModel(version_info_id=2, schema_v... | TestVersionInfoModel |
python | doocs__leetcode | lcci/08.10.Color Fill/Solution.py | {
"start": 0,
"end": 606
} | class ____:
def floodFill(
self, image: List[List[int]], sr: int, sc: int, newColor: int
) -> List[List[int]]:
def dfs(i, j):
if (
not 0 <= i < m
or not 0 <= j < n
or image[i][j] != oc
or image[i][j] == newColor
... | Solution |
python | django__django | django/db/models/functions/window.py | {
"start": 2622,
"end": 2727
} | class ____(Func):
function = "RANK"
output_field = IntegerField()
window_compatible = True
| Rank |
python | has2k1__plotnine | plotnine/composition/_compose.py | {
"start": 877,
"end": 14236
} | class ____:
"""
Base class for those that create plot compositions
As a user, you will never directly work with this class, except
through the operators that it makes possible.
The operators are of two kinds:
### 1. Composing Operators
The combine plots or compositions into a single compo... | Compose |
python | getsentry__sentry | src/sentry/incidents/models/incident.py | {
"start": 5593,
"end": 8391
} | class ____(Model):
"""
An Incident represents the overarching period during an AlertRule's "unhealthy" state.
An AlertRule can have multiple IncidentTriggers during an Incident (ie. Critical -> Warning -> Critical)
but if it has been resolved, will end the Incident.
An AlertRule may have multiple I... | Incident |
python | pandas-dev__pandas | asv_bench/benchmarks/categoricals.py | {
"start": 9348,
"end": 9776
} | class ____:
def setup(self):
N = 10**5
self.ci = pd.CategoricalIndex(np.arange(N)).sort_values()
self.c = self.ci.values
self.key = self.ci.categories[1]
def time_categorical_index_contains(self):
self.ci.searchsorted(self.key)
def time_categorical_contains(self):
... | SearchSorted |
python | gevent__gevent | src/gevent/tests/test__socket.py | {
"start": 20635,
"end": 22637
} | class ____(greentest.TestCase):
@greentest.ignores_leakcheck
# Creating new types in the function takes a cycle to cleanup.
def test_wait_timeout(self):
# Issue #635
from gevent import socket as gsocket
class io(object):
callback = None
def start(self, *_arg... | TestFunctions |
python | pandas-dev__pandas | pandas/tests/indexes/datetimes/methods/test_round.py | {
"start": 223,
"end": 7846
} | class ____:
def test_round_daily(self):
dti = date_range("20130101 09:10:11", periods=5)
result = dti.round("D")
expected = date_range("20130101", periods=5)
tm.assert_index_equal(result, expected)
dti = dti.tz_localize("UTC").tz_convert("US/Eastern")
result = dti.ro... | TestDatetimeIndexRound |
python | tox-dev__tox | src/tox/config/source/setup_cfg.py | {
"start": 183,
"end": 598
} | class ____(IniSource):
"""Configuration sourced from a tox.ini file."""
CORE_SECTION = IniSection("tox", "tox")
FILENAME = "setup.cfg"
def __init__(self, path: Path) -> None:
super().__init__(path)
if not self._parser.has_section(self.CORE_SECTION.key):
msg = f"section {sel... | SetupCfg |
python | ethereum__web3.py | web3/_utils/empty.py | {
"start": 38,
"end": 132
} | class ____:
def __bool__(self) -> Literal[False]:
return False
empty = Empty()
| Empty |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/llms/fake_llm.py | {
"start": 312,
"end": 1833
} | class ____(LLM):
"""Fake LLM wrapper for testing purposes."""
queries: Mapping | None = None
sequential_responses: bool | None = False
response_index: int = 0
@model_validator(mode="before")
@classmethod
def check_queries_required(cls, values: dict) -> dict:
if values.get("sequenti... | FakeLLM |
python | huggingface__transformers | src/transformers/models/vivit/modeling_vivit.py | {
"start": 3295,
"end": 7752
} | class ____(nn.Module):
"""
Vivit Embeddings.
Creates embeddings from a video using VivitTubeletEmbeddings, adds CLS token and positional embeddings.
"""
def __init__(self, config: VivitConfig):
super().__init__()
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))... | VivitEmbeddings |
python | Pylons__pyramid | tests/test_registry.py | {
"start": 13740,
"end": 13807
} | class ____(Interface):
pass
@implementer(IDummyEvent)
| IDummyEvent |
python | gevent__gevent | src/gevent/libuv/watcher.py | {
"start": 28626,
"end": 28968
} | class ____(check):
_watcher_skip_ffi = True
def __make_cb(self, func):
stop = self.stop
@functools.wraps(func)
def cb(*args):
stop()
return func(*args)
return cb
def start(self, callback, *args):
return check.start(self, self.__make_cb(callb... | OneShotCheck |
python | dagster-io__dagster | python_modules/libraries/dagster-azure/dagster_azure/blob/resources.py | {
"start": 1245,
"end": 4337
} | class ____(ConfigurableResource):
"""Resource for interacting with Azure Blob Storage.
Examples:
.. code-block:: python
import os
from dagster import Definitions, asset, EnvVar
from dagster_azure.blob import (
AzureBlobStorageResource,
... | AzureBlobStorageResource |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-google/llama_index/readers/google/gmail/base.py | {
"start": 286,
"end": 6491
} | class ____(BaseReader, BaseModel):
"""
Gmail reader.
Reads emails
Args:
max_results (int): Defaults to 10.
query (str): Gmail query. Defaults to None.
service (Any): Gmail service. Defaults to None.
results_per_page (Optional[int]): Max number of results per page. Defau... | GmailReader |
python | scrapy__scrapy | tests/AsyncCrawlerProcess/asyncio_deferred_signal.py | {
"start": 519,
"end": 1180
} | class ____(Spider):
name = "url_spider"
start_urls = ["data:,"]
custom_settings = {
"ITEM_PIPELINES": {UppercasePipeline: 100},
}
def parse(self, response):
yield {"url": response.url}
if __name__ == "__main__":
ASYNCIO_EVENT_LOOP: str | None
try:
ASYNCIO_EVENT_LOO... | UrlSpider |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/lambda4.py | {
"start": 824,
"end": 899
} | class ____(Protocol):
def __call__(self, *p0: str) -> bool: ...
| Callable3 |
python | huggingface__transformers | src/transformers/models/glm4v/modeling_glm4v.py | {
"start": 36091,
"end": 40975
} | class ____(Glm4vPreTrainedModel):
config: Glm4vTextConfig
input_modalities = ("text",)
def __init__(self, config: Glm4vTextConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vo... | Glm4vTextModel |
python | plotly__plotly.py | plotly/graph_objs/bar/_insidetextfont.py | {
"start": 233,
"end": 17164
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "bar"
_path_str = "bar.insidetextfont"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
"sizes... | Insidetextfont |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_emr_serverless_job.py | {
"start": 1001,
"end": 1790
} | class ____:
def setup_method(self):
self.app_id = "vzwemreks"
self.job_run_id = "job1234"
self.sensor = EmrServerlessJobSensor(
task_id="test_emrcontainer_sensor",
application_id=self.app_id,
job_run_id=self.job_run_id,
aws_conn_id="aws_default... | TestEmrServerlessJobSensor |
python | astropy__astropy | astropy/coordinates/spectral_quantity.py | {
"start": 582,
"end": 12384
} | class ____(SpecificTypeQuantity):
"""
One or more value(s) with spectral units.
The spectral units should be those for frequencies, wavelengths, energies,
wavenumbers, or velocities (interpreted as Doppler velocities relative to a
rest spectral value). The advantage of using this class over the reg... | SpectralQuantity |
python | langchain-ai__langchain | libs/langchain/langchain_classic/retrievers/document_compressors/cross_encoder.py | {
"start": 38,
"end": 362
} | class ____(ABC):
"""Interface for cross encoder models."""
@abstractmethod
def score(self, text_pairs: list[tuple[str, str]]) -> list[float]:
"""Score pairs' similarity.
Args:
text_pairs: List of pairs of texts.
Returns:
List of scores.
"""
| BaseCrossEncoder |
python | langchain-ai__langchain | libs/langchain/langchain_classic/evaluation/string_distance/base.py | {
"start": 4816,
"end": 9682
} | class ____(StringEvaluator, _RapidFuzzChainMixin):
"""Compute string distances between the prediction and the reference.
Examples:
----------
>>> from langchain_classic.evaluation import StringDistanceEvalChain
>>> evaluator = StringDistanceEvalChain()
>>> evaluator.evaluate_strings(
... | StringDistanceEvalChain |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E743.py | {
"start": 40,
"end": 99
} | class ____:
def O(self):
pass
def x():
pass
| X |
python | getsentry__sentry | src/sentry/web/frontend/shared_group_details.py | {
"start": 305,
"end": 1273
} | class ____(GenericReactPageView):
def meta_tags(
self, request: HttpRequest, *, share_id: str = "", **kwargs: Any
) -> dict[str, str]:
org_slug = getattr(request, "subdomain", None)
if org_slug:
group = issue_service.get_shared_for_org(slug=org_slug, share_id=share_id)
... | SharedGroupDetailsView |
python | facebookresearch__faiss | tests/test_fast_scan.py | {
"start": 5773,
"end": 8064
} | class ____: # (unittest.TestCase):
def do_loop5_kernel(self, nq, bb):
""" unit test for the accumulation kernel """
nb = bb * 32 # databse size
nsp = 24 # number of sub-quantizers
rs = np.random.RandomState(123)
codes = rs.randint(256, size=(nb, nsp // 2)).astype('u... | ThisIsNotATestLoop5 |
python | huggingface__transformers | src/transformers/models/electra/modeling_electra.py | {
"start": 29400,
"end": 34642
} | class ____(nn.Module):
r"""
Compute a single vector summary of a sequence hidden states.
Args:
config ([`ElectraConfig`]):
The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
config class of your model for the default va... | ElectraSequenceSummary |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/prefect_dbt/cli/configs/bigquery.py | {
"start": 513,
"end": 5575
} | class ____(BaseTargetConfigs):
"""
Target configs contain credentials and
settings, specific to BigQuery.
To find valid keys, head to the [BigQuery Profile](
https://docs.getdbt.com/reference/warehouse-profiles/bigquery-profile)
page.
Attributes:
credentials: The credentials to use ... | BigQueryTargetConfigs |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 28069,
"end": 28717
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.relu = torch.nn.ReLU()
self.layer = torch.nn.Sequential(
collections.OrderedDict(
[
("linear1", torch.nn.Linear(10, 20)),
("relu1", self.relu),... | SequentialWithDuplicatedModule2 |
python | rapidsai__cudf | python/cudf/cudf/core/buffer/spillable_buffer.py | {
"start": 2399,
"end": 12957
} | class ____(BufferOwner):
"""A Buffer that supports spilling memory off the GPU to avoid OOMs.
This buffer supports spilling the represented data to host memory.
Spilling can be done manually by calling `.spill(target="cpu")` but
usually the associated spilling manager triggers spilling based on current... | SpillableBufferOwner |
python | pennersr__django-allauth | allauth/socialaccount/providers/clever/views.py | {
"start": 280,
"end": 1703
} | class ____(OAuth2Adapter):
provider_id = "clever"
access_token_url = "https://clever.com/oauth/tokens" # nosec
authorize_url = "https://clever.com/oauth/authorize"
identity_url = "https://api.clever.com/v3.0/me"
user_details_url = "https://api.clever.com/v3.0/users"
def complete_login(self, r... | CleverOAuth2Adapter |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_step_function.py | {
"start": 1568,
"end": 4266
} | class ____:
TASK_ID = "step_function_get_execution_output"
@pytest.fixture(autouse=True)
def _setup_test_cases(self):
with mock.patch(
"airflow.providers.amazon.aws.links.step_function.StateMachineExecutionsDetailsLink.persist"
) as executions_details_link:
self.mock... | TestStepFunctionGetExecutionOutputOperator |
python | django__django | tests/contenttypes_tests/operations_migrations/0001_initial.py | {
"start": 43,
"end": 258
} | class ____(migrations.Migration):
operations = [
migrations.CreateModel(
"Foo",
[
("id", models.AutoField(primary_key=True)),
],
),
]
| Migration |
python | celery__celery | celery/exceptions.py | {
"start": 6372,
"end": 6466
} | class ____(CeleryError):
"""Celery is somehow improperly configured."""
| ImproperlyConfigured |
python | getsentry__sentry | src/sentry/utils/http.py | {
"start": 6256,
"end": 6546
} | class ____(HttpRequest):
"""typing-only: to help with hinting for `.subdomain`"""
subdomain: str
def is_using_customer_domain(request: HttpRequest) -> TypeGuard[_HttpRequestWithSubdomain]:
return bool(hasattr(request, "subdomain") and request.subdomain)
| _HttpRequestWithSubdomain |
python | pytorch__pytorch | torch/_guards.py | {
"start": 17456,
"end": 18258
} | class ____:
nn_modules: dict[str, torch.nn.Module] = {}
def __init__(self, nn_modules: dict[str, torch.nn.Module]) -> None:
self.nn_modules = nn_modules
def diff(self, other: ModuleContextCheckpointState) -> Optional[set[str]]:
"""
Produces a delta against another ModuleContextChec... | ModuleContextCheckpointState |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 325399,
"end": 327414
} | class ____:
@pytest.mark.parametrize('scale, expected',
[(1.0, 2.3283064359965952e-170),
(3.5, 5.987114417447875e-153)])
def test_delta_cdf(self, scale, expected):
# Expected value computed with mpmath:
#
# def burr12sf(x, c, d,... | TestBurr12 |
python | mwaskom__seaborn | tests/_stats/test_density.py | {
"start": 278,
"end": 6861
} | class ____:
@pytest.fixture
def df(self, rng):
n = 100
return pd.DataFrame(dict(
x=rng.uniform(0, 7, n).round(),
y=rng.normal(size=n),
color=rng.choice(["a", "b", "c"], n),
alpha=rng.choice(["x", "y"], n),
))
def get_groupby(self, df... | TestKDE |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-square-free-subsets.py | {
"start": 111,
"end": 1723
} | class ____(object):
def squareFreeSubsets(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def linear_sieve_of_eratosthenes(n): # Time: O(n), Space: O(n)
primes = []
spf = [-1]*(n+1) # the smallest prime factor
for i in xrange(2, n+... | Solution |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_web_search_tool_result_error.py | {
"start": 290,
"end": 437
} | class ____(BaseModel):
error_code: BetaWebSearchToolResultErrorCode
type: Literal["web_search_tool_result_error"]
| BetaWebSearchToolResultError |
python | huggingface__transformers | tests/models/granite_speech/test_modeling_granite_speech.py | {
"start": 7187,
"end": 11121
} | class ____(
ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase
):
"""
Model tester for `GraniteSpeechForConditionalGeneration`.
"""
all_model_classes = (GraniteSpeechForConditionalGeneration,) if is_torch_available() else ()
pipeline_model_mapping = {"any-to-any": G... | GraniteSpeechForConditionalGenerationModelTest |
python | scikit-learn__scikit-learn | sklearn/externals/array_api_extra/testing.py | {
"start": 1000,
"end": 11975
} | class ____(enum.Enum):
"""Unique type for deprecated parameters."""
DEPRECATED = 1
DEPRECATED = Deprecated.DEPRECATED
def lazy_xp_function(
func: Callable[..., Any],
*,
allow_dask_compute: bool | int = False,
jax_jit: bool = True,
static_argnums: Deprecated = DEPRECATED,
static_argn... | Deprecated |
python | conda__conda | conda/gateways/connection/adapters/ftp.py | {
"start": 1351,
"end": 9554
} | class ____(BaseAdapter):
"""A Requests Transport Adapter that handles FTP urls."""
def __init__(self):
super().__init__()
# Build a dictionary keyed off the methods we support in upper case.
# The values of this dictionary should be the functions we use to
# send the specific q... | FTPAdapter |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/repository_origin.py | {
"start": 418,
"end": 1677
} | class ____(graphene.ObjectType):
id = graphene.NonNull(graphene.String)
repository_location_name = graphene.NonNull(graphene.String)
repository_name = graphene.NonNull(graphene.String)
repository_location_metadata = non_null_list(GrapheneRepositoryMetadata)
class Meta:
name = "RepositoryOri... | GrapheneRepositoryOrigin |
python | ansible__ansible | lib/ansible/plugins/action/include_vars.py | {
"start": 541,
"end": 11436
} | class ____(ActionBase):
TRANSFERS_FILES = False
VALID_FILE_EXTENSIONS = ['yaml', 'yml', 'json']
VALID_DIR_ARGUMENTS = ['dir', 'depth', 'files_matching', 'ignore_files', 'extensions', 'ignore_unknown_extensions']
VALID_FILE_ARGUMENTS = ['file', '_raw_params']
VALID_ALL = ['name', 'hash_behaviour']
... | ActionModule |
python | pytorch__pytorch | torch/_dynamo/aot_compile.py | {
"start": 1571,
"end": 2107
} | class ____(pickle.Pickler):
@classmethod
def _unpickle_cell(cls, val: Any) -> Any:
def _() -> Any:
return val
assert _.__closure__ is not None
return _.__closure__[0]
# pyrefly: ignore [bad-override]
def reducer_override(self, obj: Any) -> Any:
if isinstance... | AOTCompilePickler |
python | great-expectations__great_expectations | great_expectations/core/freshness_diagnostics.py | {
"start": 3095,
"end": 3594
} | class ____(_ParentFreshnessDiagnostics):
parent_error_class: ClassVar[Type[GreatExpectationsError]] = ValidationDefinitionNotAddedError
children_error_classes: ClassVar[Tuple[Type[GreatExpectationsError], ...]] = (
ExpectationSuiteNotAddedError,
BatchDefinitionNotAddedError,
)
raise_for_... | ValidationDefinitionFreshnessDiagnostics |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 116319,
"end": 118408
} | class ____(Response):
"""
Response of tasks.clone endpoint.
:param id: ID of the new task
:type id: str
:param new_project: In case the new_project_name was specified returns the
target project details
:type new_project: dict
"""
_service = "tasks"
_action = "clone"
_ve... | CloneResponse |
python | pytorch__pytorch | torch/_higher_order_ops/cond.py | {
"start": 1260,
"end": 10471
} | class ____(HigherOrderOperator):
def __init__(self):
super().__init__("cond")
def __call__(self, pred, true_fn, false_fn, operands):
validate_subgraph_args_types(operands)
return super().__call__(pred, true_fn, false_fn, operands)
# pyrefly: ignore [bad-override]
def gen_schema... | CondOp |
python | wandb__wandb | wandb/sdk/artifacts/_generated/run_input_artifacts.py | {
"start": 239,
"end": 325
} | class ____(GQLResult):
project: Optional[RunInputArtifactsProject]
| RunInputArtifacts |
python | doocs__leetcode | solution/0400-0499/0477.Total Hamming Distance/Solution.py | {
"start": 0,
"end": 246
} | class ____:
def totalHammingDistance(self, nums: List[int]) -> int:
ans, n = 0, len(nums)
for i in range(32):
a = sum(x >> i & 1 for x in nums)
b = n - a
ans += a * b
return ans
| Solution |
python | getsentry__sentry | tests/sentry/uptime/autodetect/test_ranking.py | {
"start": 7419,
"end": 7980
} | class ____(UptimeTestCase):
def test(self) -> None:
bucket = datetime(2024, 7, 18, 0, 47)
delete_organization_bucket(bucket)
dummy_org_id = 1487
self.project.organization = Organization(id=dummy_org_id)
self.project.organization_id = dummy_org_id
add_base_url_to_rank(... | DeleteOrganizationBucketTest |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_imsi_belong_to_country_code.py | {
"start": 996,
"end": 2081
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.imsi_belong_to_country_code"
condition_value_keys = ("country_code",)
# This method implements the core logic for the PandasExecutionEngine
@column_conditi... | ColumnValuesImsiBelongToCountryCode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.