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 | ethereum__web3.py | web3/_utils/rpc_abi.py | {
"start": 409,
"end": 8557
} | class ____:
# admin
admin_addPeer = RPCEndpoint("admin_addPeer")
admin_datadir = RPCEndpoint("admin_datadir")
admin_nodeInfo = RPCEndpoint("admin_nodeInfo")
admin_peers = RPCEndpoint("admin_peers")
admin_startHTTP = RPCEndpoint("admin_startHTTP")
admin_startWS = RPCEndpoint("admin_startWS")
... | RPC |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/cloud_sql.py | {
"start": 32571,
"end": 58562
} | class ____(BaseHook):
"""
Serves DB connection configuration for Google Cloud SQL (Connections of *gcpcloudsqldb://* type).
The hook is a "meta" one. It does not perform an actual connection.
It is there to retrieve all the parameters configured in gcpcloudsql:// connection,
start/stop Cloud SQL P... | CloudSQLDatabaseHook |
python | huggingface__transformers | src/transformers/models/vilt/configuration_vilt.py | {
"start": 781,
"end": 6857
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ViLTModel`]. It is used to instantiate an ViLT
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configurat... | ViltConfig |
python | pytest-dev__pytest-cov | src/pytest_cov/plugin.py | {
"start": 16205,
"end": 17374
} | class ____:
cov_controller: 'CovController'
def __init__(self, cov_controller):
self.cov_controller = cov_controller
def pytest_runtest_setup(self, item):
self.switch_context(item, 'setup')
def pytest_runtest_teardown(self, item):
self.switch_context(item, 'teardown')
def... | TestContextPlugin |
python | pytorch__pytorch | torch/fx/experimental/sym_node.py | {
"start": 1573,
"end": 21341
} | class ____:
"""
This is a type erased SymInt/SymFloat which we use to do actual operations.
End users don't touch this. Magic methods are NOT defined on this object.
"""
# Note [optimized_summation]: indicates that SymNode is an Add expression of the form
# a + b + c + d... etc where all terms... | SymNode |
python | pandas-dev__pandas | pandas/io/sql.py | {
"start": 94689,
"end": 104641
} | class ____(PandasSQL):
"""
Version of SQLDatabase to support SQLite connections (fallback without
SQLAlchemy). This should only be used internally.
Parameters
----------
con : sqlite connection object
"""
def __init__(self, con) -> None:
self.con = con
@contextmanager
... | SQLiteDatabase |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_tool_bash_20241022_param.py | {
"start": 355,
"end": 1044
} | class ____(TypedDict, total=False):
name: Required[Literal["bash"]]
"""Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
"""
type: Required[Literal["bash_20241022"]]
allowed_callers: List[Literal["direct", "code_execution_20250825"]]
cache_contr... | BetaToolBash20241022Param |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 650533,
"end": 651085
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("fragment", "highlights", "property")
fragment = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="fragment")
highlights = sgqlc.types.Field(
sgqlc.types.n... | TextMatch |
python | Lightning-AI__lightning | src/lightning/fabric/accelerators/mps.py | {
"start": 868,
"end": 3063
} | class ____(Accelerator):
"""Accelerator for Metal Apple Silicon GPU devices.
.. warning:: Use of this accelerator beyond import and instantiation is experimental.
"""
@override
def setup_device(self, device: torch.device) -> None:
"""
Raises:
ValueError:
... | MPSAccelerator |
python | getsentry__sentry | src/sentry/features/manager.py | {
"start": 17225,
"end": 18429
} | class ____:
"""
A batch of objects to be checked for a feature flag.
An instance of this class encapsulates a call to
``FeatureManager.has_for_batch``. The objects (such as projects) have a
common parent organization.
"""
def __init__(
self,
manager: RegisteredFeatureManage... | FeatureCheckBatch |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1117173,
"end": 1118171
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'connected' event on a given issue or pull request."""
__schema__ = github_schema
__field_names__ = ("actor", "created_at", "is_cross_repository", "source", "subject")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor ... | ConnectedEvent |
python | huggingface__transformers | src/transformers/models/emu3/modeling_emu3.py | {
"start": 10110,
"end": 11908
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: Emu3Config, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = Emu3Attention(config=config, layer_idx=layer_idx)
self.mlp = Emu3MLP(config)
self.input_layernorm = Emu3... | Emu3DecoderLayer |
python | kamyu104__LeetCode-Solutions | Python/bold-words-in-string.py | {
"start": 1272,
"end": 1948
} | class ____(object):
def boldWords(self, words, S):
"""
:type words: List[str]
:type S: str
:rtype: str
"""
lookup = [0] * len(S)
for d in words:
pos = S.find(d)
while pos != -1:
lookup[pos:pos+len(d)] = [1] * len(d)
... | Solution2 |
python | mwaskom__seaborn | seaborn/categorical.py | {
"start": 113939,
"end": 120940
} | class ____:
"""Modifies a scatterplot artist to show a beeswarm plot."""
def __init__(self, orient="x", width=0.8, warn_thresh=.05):
self.orient = orient
self.width = width
self.warn_thresh = warn_thresh
def __call__(self, points, center):
"""Swarm `points`, a PathCollectio... | Beeswarm |
python | readthedocs__readthedocs.org | readthedocs/projects/tasks/builds.py | {
"start": 9871,
"end": 43381
} | class ____(SyncRepositoryMixin, Task):
"""
The main entry point for updating documentation.
It handles all of the logic around whether a project is imported, was
created or a webhook is received. Then it will sync the repository and
build all the documentation formats and upload them to the storage... | UpdateDocsTask |
python | pytorch__pytorch | benchmarks/operator_benchmark/common/tests/pt_backward_test.py | {
"start": 288,
"end": 818
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, K):
self.input_one = torch.rand(M, N, K, requires_grad=self.auto_set())
self.input_two = torch.rand(M, N, K, requires_grad=self.auto_set())
self.set_module_name("add")
def forward(self):
return torch.add(self.input_on... | AddBenchmark |
python | django-guardian__django-guardian | example_project/articles/migrations/0001_initial.py | {
"start": 157,
"end": 2916
} | class ____(migrations.Migration):
initial = True
dependencies = [
("auth", "0001_initial"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="Article",
fields=[
("id", models.AutoFie... | Migration |
python | sanic-org__sanic | sanic/pages/directory_page.py | {
"start": 123,
"end": 256
} | class ____(TypedDict):
"""Type for file info."""
icon: str
file_name: str
file_access: str
file_size: str
| FileInfo |
python | jmcnamara__XlsxWriter | xlsxwriter/test/image/test_image_class01.py | {
"start": 291,
"end": 1629
} | class ____(unittest.TestCase):
"""
Test the properties of an Image object.
"""
def test_image_properties01(self):
"""Test the Image class properties."""
image = Image("xlsxwriter/test/comparison/images/red.png")
self.assertEqual(image.image_type, "PNG")
self.assertEqual... | TestImageProperties |
python | kamyu104__LeetCode-Solutions | Python/tallest-billboard.py | {
"start": 66,
"end": 660
} | class ____(object):
def tallestBillboard(self, rods):
"""
:type rods: List[int]
:rtype: int
"""
def dp(A):
lookup = collections.defaultdict(int)
lookup[0] = 0
for x in A:
for d, y in lookup.items():
looku... | Solution |
python | astropy__astropy | astropy/time/tests/test_basic.py | {
"start": 53637,
"end": 54455
} | class ____:
"""Test that erfa status return values are handled correctly"""
def test_bad_time(self):
iy = np.array([2000], dtype=np.intc)
im = np.array([2000], dtype=np.intc) # bad month
id = np.array([2000], dtype=np.intc) # bad day
with pytest.raises(ValueError): # bad mont... | TestSofaErrors |
python | huggingface__transformers | src/transformers/models/ministral/modeling_ministral.py | {
"start": 9756,
"end": 11622
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: MinistralConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = MinistralAttention(config=config, layer_idx=layer_idx)
self.mlp = MinistralMLP(config)
self.input_l... | MinistralDecoderLayer |
python | kamyu104__LeetCode-Solutions | Python/best-position-for-a-service-centre.py | {
"start": 1588,
"end": 2803
} | class ____(object):
def getMinDistSum(self, positions):
"""
:type positions: List[List[int]]
:rtype: float
"""
DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)]
EPS = 1e-6
def dist(positions, p):
return sum(((p[0]-x)**2 + (p[1]-y)**2)**0.5 for x, y i... | Solution2 |
python | pytorch__pytorch | torch/_inductor/codegen/memory_planning.py | {
"start": 6376,
"end": 6928
} | class ____(MemorySplitProtocol):
"""
Helper to assist in caching get_live_ranges, get_size_hint, and
get_symbolic_size.
"""
def allocate(self, block: Allocation, is_last: bool):
is_allocated = self._allocate(block, is_last)
if is_allocated:
self.clear_cache()
ret... | ClearCacheOnAllocateMixin |
python | pypa__setuptools | setuptools/tests/test_develop.py | {
"start": 960,
"end": 3072
} | class ____:
@staticmethod
def install_develop(src_dir, target):
develop_cmd = [
sys.executable,
'setup.py',
'develop',
'--install-dir',
str(target),
]
with src_dir.as_cwd():
with paths_on_pythonpath([str(target)]):
... | TestNamespaces |
python | spyder-ide__spyder | spyder/plugins/remoteclient/widgets/connectionstatus.py | {
"start": 3080,
"end": 12724
} | class ____(
QWidget,
SpyderFontsMixin,
SvgToScaledPixmap,
SpyderConfigurationAccessor,
):
CONF_SECTION = "remoteclient"
def __init__(self, parent, host_id):
super().__init__(parent)
# Attributes
self.host_id = host_id
self.status = ConnectionStatus.Inactive
... | ConnectionStatusWidget |
python | scrapy__scrapy | scrapy/exporters.py | {
"start": 5855,
"end": 8234
} | class ____(BaseItemExporter):
def __init__(self, file: BytesIO, **kwargs: Any):
self.item_element = kwargs.pop("item_element", "item")
self.root_element = kwargs.pop("root_element", "items")
super().__init__(**kwargs)
if not self.encoding:
self.encoding = "utf-8"
... | XmlItemExporter |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_cond_format07.py | {
"start": 345,
"end": 4138
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with conditional formatting."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle... | TestAssembleWorksheet |
python | PrefectHQ__prefect | src/prefect/_internal/lazy.py | {
"start": 139,
"end": 1702
} | class ____(Generic[K, V]):
"""
A dictionary-like object that defers loading its contents until first access.
Useful for module-level registries that import heavy dependencies. The loader
function is called once on first access, and the result is cached.
Example:
>>> def load_plugins() -> d... | LazyDict |
python | dask__dask | dask/dataframe/dask_expr/_shuffle.py | {
"start": 35452,
"end": 37630
} | class ____(SetIndex):
"""Shuffles the DataFrame according to its new divisions.
Simplifies the Expression to blockwise pre-processing, shuffle and
blockwise post-processing expressions.
Parameters
----------
frame: Expr
Frame-like expression where the index is set.
_other: Expr | S... | SetPartition |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/axisline_style.py | {
"start": 250,
"end": 3715
} | class ____:
class SimpleArrow(FancyArrowPatch):
"""The artist class that will be returned for SimpleArrow style."""
_ARROW_STYLE = "->"
def __init__(self, axis_artist, line_path, transform,
line_mutation_scale):
self._axis_artist = axis_artist
se... | _FancyAxislineStyle |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_katz_centrality.py | {
"start": 8207,
"end": 9958
} | class ____:
@classmethod
def setup_class(cls):
G = nx.DiGraph()
edges = [
(1, 2),
(1, 3),
(2, 4),
(3, 2),
(3, 5),
(4, 2),
(4, 5),
(4, 6),
(5, 6),
(5, 7),
(5, 8),
... | TestKatzCentralityDirected |
python | huggingface__transformers | src/transformers/models/reformer/modeling_reformer.py | {
"start": 62907,
"end": 63727
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dense = ReformerFeedForwardDense(config... | ChunkReformerFeedForward |
python | pallets__werkzeug | src/werkzeug/_reloader.py | {
"start": 9207,
"end": 9837
} | class ____(ReloaderLoop):
name = "stat"
def __enter__(self) -> ReloaderLoop:
self.mtimes: dict[str, float] = {}
return super().__enter__()
def run_step(self) -> None:
for name in _find_stat_paths(self.extra_files, self.exclude_patterns):
try:
mtime = os.... | StatReloaderLoop |
python | apache__airflow | providers/standard/tests/unit/standard/operators/test_branch_operator.py | {
"start": 1977,
"end": 2103
} | class ____(BaseBranchOperator):
def choose_branch(self, context):
return ["branch_1", "branch_2"]
| ChooseBranchOneTwo |
python | django__django | tests/admin_views/models.py | {
"start": 17194,
"end": 17308
} | class ____(Person):
code = models.CharField(max_length=20)
class Meta:
ordering = ["name"]
| Employee |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/autoVariance4.py | {
"start": 298,
"end": 539
} | class ____[T](Parent_Invariant[T]):
pass
# This should generate an error.
a1: ShouldBeInvariant[int] = ShouldBeInvariant[float]()
# This should generate an error.
a2: ShouldBeInvariant[float] = ShouldBeInvariant[int]()
| ShouldBeInvariant |
python | pytorch__pytorch | test/test_functionalization_of_rng_ops.py | {
"start": 10980,
"end": 11575
} | class ____(TestCase):
@dtypes(torch.float32)
@patch.object(torch._functorch.config, "functionalize_rng_ops", True)
def test_on_cpu(self, dtype, device):
def fn(x):
a = torch.rand_like(x) * x
a = torch.rand_like(x) * a
return a
x = torch.rand(10, device=de... | NegativeTest |
python | django-compressor__django-compressor | compressor/management/commands/mtime_cache.py | {
"start": 198,
"end": 3856
} | class ____(BaseCommand):
help = "Add or remove all mtime values from the cache"
def add_arguments(self, parser):
parser.add_argument(
"-i",
"--ignore",
action="append",
default=[],
dest="ignore_patterns",
metavar="PATTERN",
... | Command |
python | PrefectHQ__prefect | src/prefect/server/events/clients.py | {
"start": 7327,
"end": 8650
} | class ____:
_http_client: PrefectHttpxAsyncClient
def __init__(self, additional_headers: dict[str, str] = {}):
from prefect.server.api.server import create_app
# create_app caches application instances, and invoking it with no arguments
# will point it to the the currently running serv... | PrefectServerEventsAPIClient |
python | django__django | tests/generic_views/test_detail.py | {
"start": 465,
"end": 9547
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.artist1 = Artist.objects.create(name="Rene Magritte")
cls.author1 = Author.objects.create(
name="Roberto Bolaño", slug="roberto-bolano"
)
cls.author2 = Author.objects.create(
name="Scott Rosenb... | DetailViewTest |
python | Farama-Foundation__Gymnasium | gymnasium/envs/mujoco/walker2d_v4.py | {
"start": 266,
"end": 4824
} | class ____(MujocoEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
"rgbd_tuple",
],
"render_fps": 125,
}
def __init__(
self,
forward_reward_weight=1.0,
ctrl_cost_weight=1e... | Walker2dEnv |
python | huggingface__transformers | src/transformers/models/superpoint/modeling_superpoint.py | {
"start": 3155,
"end": 4667
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*):
Loss computed during training.
keypoints (`torch.FloatTensor` of shape `(batch_size, num_keypoints, 2)`):
Relative (x, y) coordinates of predicted keypoints in a given image.
scores (`torch.FloatTensor`... | SuperPointKeypointDescriptionOutput |
python | boto__boto3 | boto3/exceptions.py | {
"start": 1764,
"end": 2618
} | class ____(
Boto3Error, botocore.exceptions.DataNotFoundError
):
"""Raised when you attempt to create a resource that does not exist."""
def __init__(self, service_name, available_services, has_low_level_client):
msg = (
"The '{}' resource does not exist.\n"
"The available r... | ResourceNotExistsError |
python | graphql-python__graphene | graphene/types/tests/test_schema.py | {
"start": 290,
"end": 1621
} | class ____(ObjectType):
inner = Field(MyOtherType)
def test_schema():
schema = Schema(Query)
graphql_schema = schema.graphql_schema
assert isinstance(graphql_schema, GraphQLSchema)
query_type = graphql_schema.query_type
assert isinstance(query_type, GraphQLObjectType)
assert query_type.nam... | Query |
python | kamyu104__LeetCode-Solutions | Python/count-nodes-equal-to-sum-of-descendants.py | {
"start": 159,
"end": 1113
} | class ____(object):
def equalToDescendants(self, root):
"""
:type root: Optional[TreeNode]
:rtype: int
"""
def iter_dfs(node):
result = 0
stk = [(1, [node, [0]])]
while stk:
step, args = stk.pop()
if step == ... | Solution |
python | doocs__leetcode | solution/0800-0899/0850.Rectangle Area II/Solution.py | {
"start": 101,
"end": 1230
} | class ____:
def __init__(self, nums):
n = len(nums) - 1
self.nums = nums
self.tr = [Node() for _ in range(n << 2)]
self.build(1, 0, n - 1)
def build(self, u, l, r):
self.tr[u].l, self.tr[u].r = l, r
if l != r:
mid = (l + r) >> 1
self.build... | SegmentTree |
python | pytest-dev__pytest | src/_pytest/warning_types.py | {
"start": 1873,
"end": 2097
} | class ____(PytestWarning):
"""
Warning emitted when a test function returns a value other than ``None``.
See :ref:`return-not-none` for details.
"""
__module__ = "pytest"
@final
| PytestReturnNotNoneWarning |
python | doocs__leetcode | solution/0100-0199/0162.Find Peak Element/Solution.py | {
"start": 0,
"end": 315
} | class ____:
def findPeakElement(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) >> 1
if nums[mid] > nums[mid + 1]:
right = mid
else:
left = mid + 1
return left
| Solution |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1047450,
"end": 1048012
} | class ____(VegaLiteSchema):
"""
RowColLayoutAlign schema wrapper.
Parameters
----------
column : :class:`LayoutAlign`, Literal['all', 'each', 'none']
row : :class:`LayoutAlign`, Literal['all', 'each', 'none']
"""
_schema = {"$ref": "#/definitions/RowCol<LayoutAlign>"}
def __init... | RowColLayoutAlign |
python | pytorch__pytorch | torch/_guards.py | {
"start": 23186,
"end": 24192
} | class ____:
@abstractmethod
def add_dynamo_installed_submodule(self, fn_id: int, identifier: str) -> None: ...
@abstractmethod
def get_dynamo_installed_submodules(self, fn_id: int) -> list[str]: ...
@abstractmethod
def add_autograd_key_entry(self, identifier: str, key: Callable) -> None: ...
... | HopSubgraphCache |
python | redis__redis-py | redis/asyncio/multidb/command_executor.py | {
"start": 1136,
"end": 3562
} | class ____(CommandExecutor):
@property
@abstractmethod
def databases(self) -> Databases:
"""Returns a list of databases."""
pass
@property
@abstractmethod
def failure_detectors(self) -> List[AsyncFailureDetector]:
"""Returns a list of failure detectors."""
pass
... | AsyncCommandExecutor |
python | joke2k__faker | faker/providers/currency/th_TH/__init__.py | {
"start": 111,
"end": 6238
} | class ____(CurrencyProvider):
# Format: (code, name)
currencies = (
("AED", "ดีแรห์ม สหรัฐอาหรับเอมิเรตส์"),
("AFN", "อัฟกานิ"),
("ALL", "เลค"),
("AMD", "ดีแรห์ม อาร์เมเนีย"),
("ANG", "กิลเดอร์ เนเธอร์แลนด์แอนทิลลิส"),
("AOA", "ควันซา"),
("ARS", "เปโซ อาร์... | Provider |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 63949,
"end": 64753
} | class ____(nn.Module):
def __init__(self, config: Qwen3OmniMoeThinkerConfig):
super().__init__()
self.experts = Qwen3OmniMoeThinkerTextExperts(config)
self.router = Qwen3OmniMoeThinkerTextTopKRouter(config)
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tens... | Qwen3OmniMoeThinkerTextSparseMoeBlock |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/req/req_install.py | {
"start": 2455,
"end": 35788
} | class ____:
"""
Represents something that may be installed later on, may have information
about where to fetch the relevant requirement and also contains logic for
installing the said requirement.
"""
def __init__(
self,
req: Optional[Requirement],
comes_from: Optional[U... | InstallRequirement |
python | getsentry__sentry | src/sentry/replays/post_process.py | {
"start": 1049,
"end": 1257
} | class ____(TypedDict, total=False):
channel: str | None
runtime_version: str | None
update_id: str | None
@extend_schema_serializer(exclude_fields=["info_ids", "warning_ids"])
| OTAUpdatesResponseType |
python | getsentry__sentry | src/sentry/issues/escalating/escalating_issues_alg.py | {
"start": 354,
"end": 4907
} | class ____:
std_multiplier: int = 5
min_spike_multiplier: int = 5
max_spike_multiplier: int = 8
min_bursty_multiplier: int = 2
max_bursty_multiplier: int = 5
standard_version = ThresholdVariables()
def generate_issue_forecast(
data: GroupCount, start_time: datetime, alg_params: ThresholdVari... | ThresholdVariables |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/sglang_engine_stage.py | {
"start": 631,
"end": 1273
} | class ____(BaseModel):
"""A request to the SGLang engine."""
# The request ID for the LLM engine (unique per replica).
request_id: int
# The index of the request in the batch.
idx_in_batch: int
# The input prompt.
prompt: Optional[str]
# Alternative to text. Specify the input as token I... | SGLangEngineRequest |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 19421,
"end": 21207
} | class ____(Reduction, GroupByBase):
_chunk_cls = GroupByChunk
def _tune_down(self):
if self.operand("split_out") is None:
return self.substitute_parameters(
{
"split_out": functools.partial(
_adjust_split_out_for_group_keys, by=sel... | GroupByReduction |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 20542,
"end": 21275
} | class ____:
@staticmethod
def oidc(
*,
group: Union[str, Sequence[str]],
read: bool = False,
assign_and_revoke: bool = False,
) -> PermissionsCreateType:
permissions: List[_Permission] = []
if isinstance(group, str):
group = [group]
for g i... | GroupsPermissions |
python | pandas-dev__pandas | pandas/tests/indexing/test_at.py | {
"start": 4239,
"end": 7213
} | class ____:
# TODO: De-duplicate/parametrize
# test_at_series_raises_key_error2, test_at_frame_raises_key_error2
def test_at_series_raises_key_error(self, indexer_al):
# GH#31724 .at should match .loc
ser = Series([1, 2, 3], index=[3, 2, 1])
result = indexer_al(ser)[1]
ass... | TestAtErrors |
python | jazzband__django-oauth-toolkit | oauth2_provider/models.py | {
"start": 13760,
"end": 16970
} | class ____(models.Model):
"""
An AccessToken instance represents the actual access token to
access user's resources, as in :rfc:`5`.
Fields:
* :attr:`user` The Django user representing resources" owner
* :attr:`source_refresh_token` If from a refresh, the consumed RefeshToken
* :attr:`toke... | AbstractAccessToken |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess6.py | {
"start": 627,
"end": 1062
} | class ____(ParentA):
attr1: Column[str] = Column(str)
attr2 = Column(str)
ChildA.attr1
ChildA().attr1
ChildA.attr2
ChildA().attr2
foo = ChildA()
# This should generate an error because bar is declared as containing a
# Column[str], which doesn't provide a __set__ method.
foo.attr1 = ""
# This should genera... | ChildA |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/py_numpy/package.py | {
"start": 289,
"end": 717
} | class ____(Package, PythonExtension):
"""A package which extends python, depends on C and C++, and has a pure build dependency"""
homepage = "http://www.example.com"
url = "http://www.example.com/py-numpy-1.0.tar.gz"
version("2.3.4", md5="00000000000000000000000000000120")
extends("python")
... | PyNumpy |
python | chroma-core__chroma | chromadb/utils/embedding_functions/google_embedding_function.py | {
"start": 9321,
"end": 14381
} | class ____(EmbeddingFunction[Documents]):
"""To use this EmbeddingFunction, you must have the google.generativeai Python package installed and have a Google API key."""
def __init__(
self,
api_key: Optional[str] = None,
model_name: str = "models/embedding-001",
task_type: str = ... | GoogleGenerativeAiEmbeddingFunction |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/solids.py | {
"start": 20095,
"end": 20265
} | class ____(graphene.ObjectType):
nodes = non_null_list(GrapheneRunStepStats)
class Meta:
name = "SolidStepStatsConnection"
| GrapheneSolidStepStatsConnection |
python | getsentry__sentry | tests/sentry/feedback/__init__.py | {
"start": 1626,
"end": 1861
} | class ____:
def __init__(self, status: int, json_data: dict):
self.status = status
self.json_data = json_data
self.data = json.dumps(json_data)
def json(self):
return self.json_data
| MockSeerResponse |
python | getsentry__sentry | src/sentry/stacktraces/processing.py | {
"start": 3815,
"end": 25200
} | class ____:
def __init__(self, data, stacktrace_infos, project=None):
self.data = data
self.stacktrace_infos = stacktrace_infos
if project is None:
project = Project.objects.get_from_cache(id=data["project"])
self.project = project
def close(self):
pass
... | StacktraceProcessor |
python | jd__tenacity | tenacity/asyncio/__init__.py | {
"start": 2200,
"end": 7772
} | class ____(BaseRetrying):
def __init__(
self,
sleep: t.Callable[
[t.Union[int, float]], t.Union[None, t.Awaitable[None]]
] = _portable_async_sleep,
stop: "StopBaseT" = tenacity.stop.stop_never,
wait: "WaitBaseT" = tenacity.wait.wait_none(),
retry: "t.Union... | AsyncRetrying |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/generator12.py | {
"start": 114,
"end": 498
} | class ____:
def __iter__(self) -> Generator[int, None, bool]:
yield 1
return True
def collect1() -> Generator[str, None, bool]:
y = Yielder()
# This should generate an error because int doesn't match str.
z = yield from y
return z
def collect2():
y = Yielder()
z = yield ... | Yielder |
python | python__mypy | test-data/unit/plugins/attrhook.py | {
"start": 154,
"end": 611
} | class ____(Plugin):
def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:
if fullname == "m.Signal.__call__":
return signal_call_callback
return None
def signal_call_callback(ctx: AttributeContext) -> Type:
if isinstance(ctx.type, Instance):
... | AttrPlugin |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/prefect_dbt/cli/configs/base.py | {
"start": 5084,
"end": 9107
} | class ____(BaseTargetConfigs):
"""
Target configs contain credentials and
settings, specific to the warehouse you're connecting to.
To find valid keys, head to the [Available adapters](
https://docs.getdbt.com/docs/available-adapters) page and
click the desired adapter's "Profile Setup" hyperlin... | TargetConfigs |
python | astropy__astropy | astropy/cosmology/_src/tests/io/base.py | {
"start": 4604,
"end": 6036
} | class ____(IODirectTestBase, ToFromTestMixinBase):
"""Directly test ``to/from_<format>``.
These functions are not public API and are discouraged from public use, in
favor of ``Cosmology.to/from_format(..., format="<format>")``. They are
tested because they are used internally and because some tests for... | ToFromDirectTestBase |
python | bokeh__bokeh | examples/advanced/extensions/tool.py | {
"start": 1800,
"end": 2193
} | class ____(Tool):
__implementation__ = TypeScript(CODE)
source = Instance(ColumnDataSource)
source = ColumnDataSource(data=dict(x=[], y=[]))
plot = figure(x_range=(0,10), y_range=(0,10), title="Click and drag to draw",
background_fill_color="#efefef", tools="")
plot.add_tools(DrawTool(source=so... | DrawTool |
python | squidfunk__mkdocs-material | material/plugins/projects/structure/__init__.py | {
"start": 1660,
"end": 10260
} | class ____:
# Initialize project - note that the configuration of the projects plugin
# of the enclosing project is necessary to resolve nested projects
def __init__(self, file: str, plugin: ProjectsConfig, slug = "."):
self.config, self.plugin = self._resolve(file, plugin)
# The slug shou... | Project |
python | jina-ai__jina | jina/serve/runtimes/servers/http.py | {
"start": 9100,
"end": 9945
} | class ____(FastAPIBaseServer):
"""
:class:`HTTPServer` is a FastAPIBaseServer that uses the default FastAPI app for a given request handler
"""
@property
def app(self):
"""Get the default base API app for Server
:return: Return a FastAPI app for the default HTTPGateway
"""
... | HTTPServer |
python | readthedocs__readthedocs.org | readthedocs/api/v3/views.py | {
"start": 24425,
"end": 24880
} | class ____(
APIv3Settings,
NestedViewSetMixin,
OrganizationQuerySetMixin,
FlexFieldsMixin,
ListModelMixin,
GenericViewSet,
):
model = Team
serializer_class = TeamSerializer
permission_classes = [IsAuthenticated & IsOrganizationAdmin]
permit_list_expands = ["members"]
def get... | OrganizationsTeamsViewSet |
python | ray-project__ray | python/ray/actor.py | {
"start": 4795,
"end": 5463
} | class ____(Generic[_Ret, _T0, _T1, _T2, _T3, _T4, _T5, _T6]):
def remote(
self,
__arg0: "Union[_T0, ObjectRef[_T0]]",
__arg1: "Union[_T1, ObjectRef[_T1]]",
__arg2: "Union[_T2, ObjectRef[_T2]]",
__arg3: "Union[_T3, ObjectRef[_T3]]",
__arg4: "Union[_T4, ObjectRef[_T4]]"... | _RemoteMethod6 |
python | keras-team__keras | guides/making_new_layers_and_models_via_subclassing.py | {
"start": 17460,
"end": 17822
} | class ____(layers.Layer):
"""Uses (z_mean, z_log_var) to sample z, the vector encoding a digit."""
def call(self, inputs):
z_mean, z_log_var = inputs
batch = ops.shape(z_mean)[0]
dim = ops.shape(z_mean)[1]
epsilon = keras.random.normal(shape=(batch, dim))
return z_mean +... | Sampling |
python | pytorch__pytorch | torch/_inductor/codegen/triton.py | {
"start": 59877,
"end": 67456
} | class ____(TritonOverrides):
"""Map element-wise ops to Triton within a TritonKernel
Unlike TritonOverrides, these assume the code is going to be inserted into
the body of the main triton kernel and so it may use indexing and mask
variables which are assumed to already be defined in the current scope.
... | TritonKernelOverrides |
python | google__pytype | pytype/state.py | {
"start": 14576,
"end": 17586
} | class ____:
"""Represents a condition due to if-splitting.
Properties:
node: A CFGNode.
binding: A Binding for the condition's constraints.
"""
def __init__(self, node, dnf):
# The condition is represented by a dummy variable with a single binding
# to None. The origins for this binding are t... | Condition |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 223384,
"end": 223699
} | 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("CheckSuite", graphql_name="node")
| CheckSuiteEdge |
python | apache__airflow | devel-common/src/tests_common/test_utils/perf/perf_kit/sqlalchemy.py | {
"start": 1210,
"end": 5042
} | class ____:
"""
Track SQL queries in a code block.
:param display_num: If True, displays the query number.
:param display_time: If True, displays the query execution time.
:param display_trace: If True, displays the simplified (one-line) stack trace
:param display_sql: If True, displays the SQL... | TraceQueries |
python | walkccc__LeetCode | solutions/2458. Height of Binary Tree After Subtree Removal Queries/2458.py | {
"start": 0,
"end": 810
} | class ____:
def treeQueries(self, root: TreeNode | None, queries: list[int]) -> list[int]:
@lru_cache(None)
def height(root: TreeNode | None) -> int:
if not root:
return 0
return 1 + max(height(root.left), height(root.right))
# valToMaxHeight[val] := the maximum height without the nod... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultClass1.py | {
"start": 2982,
"end": 3318
} | class ____(Generic[*Ts5, P4, P5]): ... # OK
reveal_type(
ClassD[int, str, complex],
expected_text="type[ClassD[int, str, complex, (float, bool), (bool)]]",
)
reveal_type(
ClassD[int, str, [str, complex]],
expected_text="type[ClassD[int, str, (str, complex), (bool)]]",
)
P6 = ParamSpec("P6", default=... | ClassD |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/mnist_test.py | {
"start": 3255,
"end": 6532
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super(DTensorMNISTTest, self).setUp()
global_ids = test_util.create_device_ids_array((2,))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout_lib.Mesh(
[_BATCH_DIM],
global_ids,
lo... | DTensorMNISTTest |
python | fluentpython__example-code-2e | 24-class-metaprog/checked/metaclass/checkedlib.py | {
"start": 3732,
"end": 4880
} | class ____(metaclass=CheckedMeta):
__slots__ = () # skip CheckedMeta.__new__ processing
@classmethod
def _fields(cls) -> dict[str, type]:
return get_type_hints(cls)
def __init__(self, **kwargs: Any) -> None:
for name in self._fields():
value = kwargs.pop(name, ...)
... | Checked |
python | readthedocs__readthedocs.org | readthedocs/core/tests/test_filesystem_utils.py | {
"start": 399,
"end": 7078
} | class ____(TestCase):
def assert_files_equal(self, directory, files):
self.assertEqual(
{str(p.relative_to(directory)) for p in directory.iterdir()}, files
)
def test_copytree(self):
from_directory = Path(mkdtemp())
docroot_path = from_directory.parent
to_dir... | TestFileSystemUtils |
python | chroma-core__chroma | chromadb/utils/embedding_functions/schemas/bm25_tokenizer.py | {
"start": 3277,
"end": 4519
} | class ____:
"""Tokenizer with stopword filtering and stemming used by BM25 embeddings."""
def __init__(
self,
stemmer: SnowballStemmer,
stopwords: Iterable[str],
token_max_length: int,
) -> None:
self._stemmer = stemmer
self._stopwords = {word.lower() for wor... | Bm25Tokenizer |
python | pytorch__pytorch | torch/_export/pass_infra/proxy_value.py | {
"start": 141,
"end": 1269
} | class ____(Generic[_T]):
# pyre-ignore
def __init__(self, data: Iterable[_T], proxy: Union[torch.fx.Proxy, torch.fx.Node]):
# pyre-ignore
self.data = data
self.proxy_or_node = proxy
@property
def node(self) -> torch.fx.Node:
if isinstance(self.proxy_or_node, torch.fx.Nod... | ProxyValue |
python | pyca__cryptography | src/cryptography/hazmat/primitives/asymmetric/padding.py | {
"start": 680,
"end": 1520
} | class ____(AsymmetricPadding):
MAX_LENGTH = _MaxLength()
AUTO = _Auto()
DIGEST_LENGTH = _DigestLength()
name = "EMSA-PSS"
_salt_length: int | _MaxLength | _Auto | _DigestLength
def __init__(
self,
mgf: MGF,
salt_length: int | _MaxLength | _Auto | _DigestLength,
) -> ... | PSS |
python | scipy__scipy | scipy/stats/tests/test_generation/reference_distributions.py | {
"start": 12343,
"end": 12815
} | class ____(ReferenceDistribution):
def __init__(self, *, a, b):
super().__init__(a=a, b=b)
def _support(self, **kwargs):
return mp.zero, mp.inf
def _logpdf(self, x, a, b):
return (a - mp.one)*mp.log(x) - (a + b)*mp.log1p(x) - mp.log(mp.beta(a, b))
def _pdf(self, x, a, b):
... | BetaPrime |
python | pytorch__pytorch | test/quantization/eager/test_numeric_suite_eager.py | {
"start": 1805,
"end": 2607
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.mycat = nnq.FloatFunctional()
self.myadd = nnq.FloatFunctional()
self.mymul = nnq.FloatFunctional()
self.myadd_relu = nnq.FloatFunctional()
self.my_scalar_add = nnq.FloatFunctional()
... | ModelWithFunctionals |
python | astropy__astropy | astropy/convolution/kernels.py | {
"start": 7741,
"end": 10019
} | class ____(Kernel2D):
"""
2D Box filter kernel.
The Box filter or running mean is a smoothing filter. It is not isotropic
and can produce artifacts when applied repeatedly to the same data.
The generated kernel is normalized so that it integrates to 1.
By default, the Box kernel uses the ``li... | Box2DKernel |
python | mlflow__mlflow | dev/clint/src/clint/rules/unknown_mlflow_function.py | {
"start": 36,
"end": 356
} | class ____(Rule):
def __init__(self, function_name: str) -> None:
self.function_name = function_name
def _message(self) -> str:
return (
f"Unknown MLflow function: `{self.function_name}`. "
"This function may not exist or could be misspelled."
)
| UnknownMlflowFunction |
python | plotly__plotly.py | plotly/graph_objs/layout/scene/camera/_projection.py | {
"start": 235,
"end": 2556
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.scene.camera"
_path_str = "layout.scene.camera.projection"
_valid_props = {"type"}
@property
def type(self):
"""
Sets the projection type. The projection type could be either
"perspective" or "orthographic". Th... | Projection |
python | readthedocs__readthedocs.org | readthedocs/core/permissions.py | {
"start": 6554,
"end": 6642
} | class ____(SettingsOverrideObject):
_default_class = AdminPermissionBase
| AdminPermission |
python | pytorch__pytorch | torch/fx/experimental/migrate_gradual_types/constraint.py | {
"start": 13407,
"end": 14300
} | class ____(Constraint):
def __init__(self, res1, res2, input1, input2):
"""
:param res1: resulting tensor 1
:param res2: resulting tensor 2
:param input1: tensor variable 1
:param input2: tensor variable 2
"""
self.res1 = res1
self.res2 = res2
... | ApplyBroadcasting |
python | dagster-io__dagster | python_modules/libraries/dagster-gcp/dagster_gcp/gcs/gcs_fake_resource.py | {
"start": 2927,
"end": 3036
} | class ____:
@cached_method
def get_client(self):
return FakeGCSClient()
| FakeConfigurableGCSClient |
python | numpy__numpy | numpy/_core/tests/test_getlimits.py | {
"start": 3285,
"end": 5219
} | class ____:
def test_iinfo_repr(self):
expected = "iinfo(min=-32768, max=32767, dtype=int16)"
assert_equal(repr(np.iinfo(np.int16)), expected)
def test_finfo_repr(self):
expected = "finfo(resolution=1e-06, min=-3.4028235e+38,"\
" max=3.4028235e+38, dtype=float32)"
... | TestRepr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.