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 | spyder-ide__spyder | spyder/utils/snippets/nodes.py | {
"start": 1059,
"end": 1215
} | class ____:
TEXT = 'text'
LEAF = 'leaf'
FORMAT = 'format'
# ------------------------- Base AST Node classes -----------------------------
| NodeKind |
python | apache__airflow | providers/google/src/airflow/providers/google/marketing_platform/operators/campaign_manager.py | {
"start": 15330,
"end": 19097
} | class ____(BaseOperator):
"""
Inserts conversions.
.. seealso::
Check official API docs:
`https://developers.google.com/doubleclick-advertisers/rest/v4/conversions/batchinsert`
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref... | GoogleCampaignManagerBatchInsertConversionsOperator |
python | google__pytype | pytype/rewrite/abstract/containers.py | {
"start": 811,
"end": 1899
} | class ____(base.PythonConstant[dict[_Var, _Var]]):
"""Representation of a Python dict."""
def __init__(
self,
ctx: base.ContextType,
constant: dict[_Var, _Var],
):
assert isinstance(constant, dict), constant
super().__init__(ctx, constant)
def __repr__(self):
return f'Dict({self.... | Dict |
python | celery__celery | celery/worker/state.py | {
"start": 6031,
"end": 8583
} | class ____:
"""Stores worker state between restarts.
This is the persistent data stored by the worker when
:option:`celery worker --statedb` is enabled.
Currently only stores revoked task id's.
"""
storage = shelve
protocol = pickle_protocol
compress = zlib.compress
decompress = z... | Persistent |
python | openai__openai-python | src/openai/types/beta/file_search_tool_param.py | {
"start": 632,
"end": 1540
} | class ____(TypedDict, total=False):
max_num_results: int
"""The maximum number of results the file search tool should output.
The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number
should be between 1 and 50 inclusive.
Note that the file search tool may output fewer than `max... | FileSearch |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 693438,
"end": 693952
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of MarkPullRequestReadyForReview"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "pull_request")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client pe... | MarkPullRequestReadyForReviewPayload |
python | python-markdown__markdown | markdown/extensions/md_in_html.py | {
"start": 13789,
"end": 14146
} | class ____(Preprocessor):
"""Remove html blocks from the text and store them for later retrieval."""
def run(self, lines: list[str]) -> list[str]:
source = '\n'.join(lines)
parser = HTMLExtractorExtra(self.md)
parser.feed(source)
parser.close()
return ''.join(parser.clea... | HtmlBlockPreprocessor |
python | chardet__chardet | chardet/chardistribution.py | {
"start": 9576,
"end": 10316
} | class ____(CharDistributionAnalysis):
def __init__(self) -> None:
super().__init__()
self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER
self._table_size = JIS_TABLE_SIZE
self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str: Union[bytes, by... | EUCJPDistributionAnalysis |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_dot.py | {
"start": 115,
"end": 2434
} | class ____:
@pytest.fixture
def obj(self):
raise NotImplementedError
@pytest.fixture
def other(self) -> DataFrame:
"""
other is a DataFrame that is indexed so that obj.dot(other) is valid
"""
raise NotImplementedError
@pytest.fixture
def expected(self, o... | DotSharedTests |
python | openai__openai-python | src/openai/types/shared/response_format_json_schema.py | {
"start": 290,
"end": 1311
} | class ____(BaseModel):
name: str
"""The name of the response format.
Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length
of 64.
"""
description: Optional[str] = None
"""
A description of what the response format is for, used by the model to determine
how... | JSONSchema |
python | walkccc__LeetCode | solutions/2800. Shortest String That Contains Three Strings/2800.py | {
"start": 0,
"end": 1005
} | class ____:
def minimumString(self, a: str, b: str, c: str) -> str:
def merge(a: str, b: str) -> str:
"""Merges a and b."""
if a in b: # a is a substring of b.
return b
for i in range(len(a)):
aSuffix = a[i:]
bPrefix = b[:len(aSuffix)]
if aSuffix == bPrefix:
... | Solution |
python | matplotlib__matplotlib | lib/matplotlib/colors.py | {
"start": 23624,
"end": 37967
} | class ____:
"""
Baseclass for all scalar to RGBA mappings.
Typically, Colormap instances are used to convert data values (floats)
from the interval ``[0, 1]`` to the RGBA color that the respective
Colormap represents. For scaling of data into the ``[0, 1]`` interval see
`matplotlib.colors.Norma... | Colormap |
python | pytorch__pytorch | torch/_dynamo/variables/ctx_manager.py | {
"start": 46781,
"end": 48627
} | class ____(ContextWrappingVariable):
"""
fx.traceback.annotate is a context manager that allows users to annotate the
fx graph nodes with custom metadata. In the context of Dynamo, we don't have
to trace the body of the context manager. Instead we want to directly run
the body of the context manager... | FxTracebackAnnotateVariable |
python | readthedocs__readthedocs.org | readthedocs/core/static.py | {
"start": 226,
"end": 622
} | class ____(FileSystemFinder):
"""
Add user media paths in ``media/`` to ignore patterns.
This allows collectstatic inside ``media/`` without collecting all of the
paths that include user files
"""
def list(self, ignore_patterns):
ignore_patterns.extend(["epub", "pdf", "htmlzip", "json"... | SelectiveFileSystemFinder |
python | pypa__warehouse | warehouse/oidc/models/_core.py | {
"start": 1031,
"end": 2895
} | class ____(TypedDict, total=False):
publisher_service: OIDCPublisherService
CheckClaimCallable = Callable[[C, C, SignedClaims, Unpack[CheckNamedArguments]], bool]
def check_claim_binary(binary_func: Callable[[C, C], bool]) -> CheckClaimCallable[C]:
"""
Wraps a binary comparison function so that it takes... | CheckNamedArguments |
python | scipy__scipy | scipy/stats/_discrete_distns.py | {
"start": 51764,
"end": 53121
} | class ____(rv_discrete_frozen):
# copied from rv_frozen; we just need to bind the `_parse_args` methods
def __init__(self, dist, *args, **kwds): # verbatim
self.args = args # verbatim
self.kwds = kwds ... | poisson_binomial_frozen |
python | matplotlib__matplotlib | lib/matplotlib/_mathtext.py | {
"start": 25571,
"end": 27374
} | class ____(UnicodeFonts, metaclass=abc.ABCMeta):
_fontmap: dict[str | int, str] = {}
def __init__(self, default_font_prop: FontProperties, load_glyph_flags: LoadFlags):
# This must come first so the backend's owner is set correctly
if isinstance(self, DejaVuSerifFonts):
self._fallba... | DejaVuFonts |
python | getsentry__sentry | src/sentry/organizations/services/organization/model.py | {
"start": 2300,
"end": 2674
} | class ____(RpcModel):
id: int = -1
slug: str = ""
is_active: bool = False
role_id: str = ""
project_ids: list[int] = Field(default_factory=list)
scopes: list[str] = Field(default_factory=list)
team_id: int = -1
@property
def role(self) -> TeamRole | None:
return team_roles.g... | RpcTeamMember |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/metrics/data_profiler_metrics/data_profiler_table_column_infos.py | {
"start": 546,
"end": 2002
} | class ____(DataProfilerProfileMetricProvider):
metric_name = "data_profiler.table_column_infos"
value_keys = ("profile_path",)
@metric_value(engine=PandasExecutionEngine)
def _pandas(
cls,
execution_engine,
metric_domain_kwargs,
metric_value_kwargs,
metrics,
... | DataProfilerTableColumnInfos |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/benchmarks/unbatch_benchmark.py | {
"start": 853,
"end": 2451
} | class ____(benchmark_base.DatasetBenchmarkBase):
"""Benchmarks for `tf.data.Dataset.unbatch()`."""
def benchmark_native_unbatch(self):
batch_sizes = [1, 2, 5, 10, 20, 50]
num_elements = 10000
for batch_size in batch_sizes:
dataset = dataset_ops.Dataset.from_tensors("element").repeat(None)
... | UnbatchBenchmark |
python | openai__gym | tests/wrappers/test_pixel_observation.py | {
"start": 224,
"end": 994
} | class ____(gym.Env):
def __init__(self, render_mode="single_rgb_array"):
self.action_space = spaces.Box(shape=(1,), low=-1, high=1, dtype=np.float32)
self.render_mode = render_mode
def render(self, mode="human", width=32, height=32):
image_shape = (height, width, 3)
return np.ze... | FakeEnvironment |
python | getsentry__sentry | src/sentry/api/serializers/models/dashboard.py | {
"start": 1884,
"end": 1963
} | class ____(TypedDict):
max_values: dict[str, int]
unit: str
| ThresholdType |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/jit/rpc_test.py | {
"start": 26489,
"end": 46869
} | class ____(
RRefAPITest,
RRefTypingTest,
LocalRRefTest,
JitRpcOpTest,
FutureTypingTest,
RpcAgentTestFixture,
):
@dist_init
def test_torchscript_function(self):
dst_worker_name = worker_name((self.rank + 1) % self.world_size)
local_ret = one_arg(torch.ones(2, 2))
r... | JitRpcTest |
python | huggingface__transformers | src/transformers/models/gpt_neox/modeling_gpt_neox.py | {
"start": 25695,
"end": 29109
} | class ____(GPTNeoXPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.gpt_neox = GPTNeoXModel(config)
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
# Initialize weights and apply final proc... | GPTNeoXForSequenceClassification |
python | jupyterlab__jupyterlab | examples/federated/main.py | {
"start": 595,
"end": 1619
} | class ____(LabServerApp):
name = "lab"
load_other_extensions = False
app_name = "JupyterLab Example App with Prebuilt Extensions"
app_settings_dir = os.path.join(HERE, "data", "application_settings")
app_version = version
schemas_dir = os.path.join(HERE, "data", "schemas")
static_dir = os.pa... | ExampleApp |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_missing_org_members.py | {
"start": 316,
"end": 13658
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-missing-members"
method = "get"
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(email="owner@example.com")
self.organization = self.create_organization(owner=self.user)
self.create_member(
... | OrganizationMissingMembersTestCase |
python | doocs__leetcode | solution/1100-1199/1137.N-th Tribonacci Number/Solution2.py | {
"start": 21,
"end": 448
} | class ____:
def tribonacci(self, n: int) -> int:
if n == 0:
return 0
if n < 3:
return 1
factor = np.asmatrix([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O"))
res = np.asmatrix([(1, 1, 0)], np.dtype("O"))
n -= 3
while n:
if n & 1:
... | Solution |
python | mlflow__mlflow | dev/clint/src/clint/rules/incorrect_type_annotation.py | {
"start": 48,
"end": 664
} | class ____(Rule):
MAPPING = {
"callable": "Callable",
"any": "Any",
}
def __init__(self, type_hint: str) -> None:
self.type_hint = type_hint
@staticmethod
def check(node: ast.Name) -> bool:
return node.id in IncorrectTypeAnnotation.MAPPING
def _message(self) ->... | IncorrectTypeAnnotation |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/loop28.py | {
"start": 285,
"end": 749
} | class ____:
def __init__(self):
self.pending: Optional[Dict[Future[Any], int]]
self.foo: bool
def poll(self):
assert self.pending is not None
while True:
if self.pending:
pass
ready, _ = futures.wait(self.pending)
for future_... | A |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 33367,
"end": 33717
} | class ____(IncrementalMixin, GithubStream):
"""
API docs: https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28#list-repository-issues
"""
use_cache = True
large_stream = True
is_sorted = "asc"
stream_base_params = {
"state": "all",
"sort": "updated",
... | Issues |
python | pytorch__pytorch | torch/_tensor_str.py | {
"start": 3883,
"end": 28400
} | class ____:
def __init__(self, tensor):
self.floating_dtype = tensor.dtype.is_floating_point
self.int_mode = True
self.sci_mode = False
self.max_width = 1
with torch.no_grad():
tensor_view = tensor.reshape(-1)
if not self.floating_dtype:
for ... | _Formatter |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_arkansas_zip.py | {
"start": 747,
"end": 1751
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_arkansas_zip"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pand... | ColumnValuesToBeValidArkansasZip |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/errors.py | {
"start": 644,
"end": 767
} | class ____(HypothesisException):
"""Hypothesis can trim these tracebacks even if they're raised internally."""
| _Trimmable |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/glacier.py | {
"start": 1178,
"end": 1952
} | class ____(AwsBaseOperator[GlacierHook]):
"""
Initiate an Amazon Glacier inventory-retrieval job.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:GlacierCreateJobOperator`
:param aws_conn_id: The reference to the AWS connect... | GlacierCreateJobOperator |
python | python__mypy | mypyc/codegen/emit.py | {
"start": 4028,
"end": 4107
} | class ____(ErrorHandler):
"""Assign an error value on error."""
| AssignHandler |
python | huggingface__transformers | src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py | {
"start": 18355,
"end": 20792
} | class ____(nn.Module):
"""
SAM3_TRACKER_VIDEO's attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and
values.
"""
def __init__(self, config, downsample_rate=None):
super().__init__()
downsample_rate = config.attention_downsample... | Sam3TrackerVideoAttention |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 45401,
"end": 47402
} | class ____(nn.Module):
def __init__(self, config: GroupViTVisionConfig):
super().__init__()
self.config = config
embed_dim = config.hidden_size
self.embeddings = GroupViTVisionEmbeddings(config)
self.encoder = GroupViTVisionEncoder(config)
self.layernorm = nn.LayerNo... | GroupViTVisionTransformer |
python | google__jax | tests/pallas/tpu_pallas_test.py | {
"start": 113191,
"end": 114610
} | class ____(PallasBaseTest):
@parameterized.parameters(
(
lambda i: (i, pl.ds(0, 8), pl.ds(0, 128)), 0, False,
'dma_start(p0) c[d,:,:] -> e[...] f',
),
(
lambda i: (0, pl.ds(i, 8), pl.ds(0, 128)), 0, False,
'dma_start(p0) c[0,d:d+8,:] -> e[...] f',
),
... | PrettyPrintingTest |
python | doocs__leetcode | solution/0500-0599/0541.Reverse String II/Solution.py | {
"start": 0,
"end": 208
} | class ____:
def reverseStr(self, s: str, k: int) -> str:
cs = list(s)
for i in range(0, len(cs), 2 * k):
cs[i : i + k] = reversed(cs[i : i + k])
return "".join(cs)
| Solution |
python | numpy__numpy | benchmarks/benchmarks/bench_ufunc_strides.py | {
"start": 4057,
"end": 4162
} | class ____(BinaryFP):
data_finite = False
data_denormal = True
data_zeros = True
| BinaryFPSpecial |
python | doocs__leetcode | solution/0800-0899/0815.Bus Routes/Solution.py | {
"start": 0,
"end": 905
} | class ____:
def numBusesToDestination(
self, routes: List[List[int]], source: int, target: int
) -> int:
if source == target:
return 0
g = defaultdict(list)
for i, route in enumerate(routes):
for stop in route:
g[stop].append(i)
if ... | Solution |
python | neetcode-gh__leetcode | python/0125-valid-palindrome.py | {
"start": 0,
"end": 207
} | class ____:
def isPalindrome(self, s: str) -> bool:
new = ''
for a in s:
if a.isalpha() or a.isdigit():
new += a.lower()
return (new == new[::-1])
| Solution |
python | django__django | tests/admin_scripts/tests.py | {
"start": 13017,
"end": 16627
} | class ____(AdminScriptTestCase):
"""
A series of tests for django-admin when using a settings.py file that
contains the test application specified using a full path.
"""
def setUp(self):
super().setUp()
self.write_settings(
"settings.py",
[
"d... | DjangoAdminFullPathDefaultSettings |
python | langchain-ai__langchain | libs/partners/openai/tests/integration_tests/chat_models/test_base_standard.py | {
"start": 417,
"end": 4967
} | class ____(ChatModelIntegrationTests):
@property
def chat_model_class(self) -> type[BaseChatModel]:
return ChatOpenAI
@property
def chat_model_params(self) -> dict:
return {"model": "gpt-4o-mini"}
@property
def supports_image_inputs(self) -> bool:
return True
@prop... | TestOpenAIStandard |
python | kubernetes-client__python | kubernetes/client/api/node_api.py | {
"start": 543,
"end": 5181
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | NodeApi |
python | spyder-ide__spyder | spyder/plugins/mainmenu/api.py | {
"start": 3262,
"end": 3348
} | class ____:
New = 'new_section'
Restart = 'restart_section'
| ConsolesMenuSections |
python | openai__openai-python | src/openai/types/beta/assistant_create_params.py | {
"start": 6740,
"end": 7607
} | class ____(TypedDict, total=False):
chunking_strategy: ToolResourcesFileSearchVectorStoreChunkingStrategy
"""The chunking strategy used to chunk the file(s).
If not set, will use the `auto` strategy.
"""
file_ids: SequenceNotStr[str]
"""
A list of [file](https://platform.openai.com/docs/ap... | ToolResourcesFileSearchVectorStore |
python | tox-dev__tox | docs/tox_conf.py | {
"start": 670,
"end": 3780
} | class ____(SphinxDirective):
name = "conf"
has_content = True
option_spec: Final[ClassVar[dict[str, Any]]] = {
"keys": unchanged_required,
"version_added": unchanged,
"version_deprecated": unchanged,
"default": unchanged,
"constant": flag,
"ref_suffix": unchan... | ToxConfig |
python | Textualize__textual | src/textual/css/_style_properties.py | {
"start": 41761,
"end": 42981
} | class ____:
"""Property to expose hatch style."""
def __get__(
self, obj: StylesBase, type: type[StylesBase]
) -> tuple[str, Color] | Literal["none"]:
return obj.get_rule("hatch") # type: ignore[return-value]
def __set__(
self, obj: StylesBase, value: tuple[str, Color | str] |... | HatchProperty |
python | PyCQA__pylint | pylint/extensions/redefined_loop_name.py | {
"start": 515,
"end": 3230
} | class ____(checkers.BaseChecker):
name = "redefined-loop-name"
msgs = {
"W2901": (
"Redefining %r from loop (line %s)",
"redefined-loop-name",
"Used when a loop variable is overwritten in the loop body.",
),
}
def __init__(self, linter: PyLinter) -> ... | RedefinedLoopNameChecker |
python | getsentry__sentry | tests/sentry/integrations/slack/service/test_slack_service.py | {
"start": 1446,
"end": 2850
} | class ____(TestCase):
def setUp(self) -> None:
self.service = SlackService.default()
self.message_identifier = "1a2s3d"
def test_ignores_unsupported_activity(self) -> None:
activity = Activity.objects.create(
group=self.group,
project=self.project,
ty... | TestGetNotificationMessageToSend |
python | pytorch__pytorch | torch/_tensor_str.py | {
"start": 186,
"end": 3883
} | class ____:
precision: int = 4
threshold: float = 1000
edgeitems: int = 3
linewidth: int = 80
sci_mode: Optional[bool] = None
PRINT_OPTS = __PrinterOptions()
# We could use **kwargs, but this will give better docs
def set_printoptions(
precision=None,
threshold=None,
edgeitems=None,
... | __PrinterOptions |
python | openai__openai-python | src/openai/types/beta/chatkit/chat_session_chatkit_configuration_param.py | {
"start": 1070,
"end": 1674
} | class ____(TypedDict, total=False):
automatic_thread_titling: AutomaticThreadTitling
"""Configuration for automatic thread titling.
When omitted, automatic thread titling is enabled by default.
"""
file_upload: FileUpload
"""Configuration for upload enablement and limits.
When omitted, up... | ChatSessionChatKitConfigurationParam |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/supervised_learning/gradient_boosting.py | {
"start": 3219,
"end": 3690
} | class ____(GradientBoosting):
def __init__(self, n_estimators=200, learning_rate=0.5, min_samples_split=2,
min_var_red=1e-7, max_depth=4, debug=False):
super(GradientBoostingRegressor, self).__init__(n_estimators=n_estimators,
learning_rate=learning_rate,
min_sampl... | GradientBoostingRegressor |
python | crytic__slither | slither/detectors/compiler_bugs/uninitialized_function_ptr_in_constructor.py | {
"start": 2191,
"end": 5086
} | class ____(AbstractDetector):
"""
Uninitialized function pointer calls in constructors
"""
ARGUMENT = "uninitialized-fptr-cst"
HELP = "Uninitialized function pointer calls in constructors"
IMPACT = DetectorClassification.LOW
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://gith... | UninitializedFunctionPtrsConstructor |
python | tensorflow__tensorflow | tensorflow/python/distribute/parallel_device/parallel_device.py | {
"start": 2160,
"end": 9612
} | class ____(object):
"""A device which executes operations in parallel."""
def __init__(self, components):
"""Creates a device which executes operations in parallel on `components`.
Args:
components: A list of device names. Each operation executed on the
returned device executes on these comp... | ParallelDevice |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 10583,
"end": 10866
} | class ____(AtomicRule):
"""integrate(sqrt(a+b*x+c*x**2), x)"""
a: Expr
b: Expr
c: Expr
def eval(self) -> Expr:
step = sqrt_quadratic_rule(IntegralInfo(self.integrand, self.variable), degenerate=False)
return step.eval()
@dataclass
| SqrtQuadraticRule |
python | django__django | django/db/models/functions/text.py | {
"start": 6698,
"end": 6784
} | class ____(OracleHashMixin, Transform):
function = "MD5"
lookup_name = "md5"
| MD5 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external_data.py | {
"start": 7153,
"end": 7265
} | class ____(Enum):
ANONYMOUS = "ANONYMOUS"
TOP_LEVEL = "TOP_LEVEL"
@whitelist_for_serdes
| NestedResourceType |
python | redis__redis-py | tests/test_auth/test_token_manager.py | {
"start": 405,
"end": 18660
} | class ____:
@pytest.mark.parametrize(
"exp_refresh_ratio",
[
0.9,
0.28,
],
ids=[
"Refresh ratio = 0.9",
"Refresh ratio = 0.28",
],
)
def test_success_token_renewal(self, exp_refresh_ratio):
tokens = []
mo... | TestTokenManager |
python | ray-project__ray | python/ray/util/scheduling_strategies.py | {
"start": 428,
"end": 1462
} | class ____:
"""Placement group based scheduling strategy.
Attributes:
placement_group: the placement group this actor belongs to,
or None if it doesn't belong to any group.
placement_group_bundle_index: the index of the bundle
if the actor belongs to a placement group, w... | PlacementGroupSchedulingStrategy |
python | conda__conda | conda/gateways/connection/adapters/s3.py | {
"start": 655,
"end": 3308
} | class ____(BaseAdapter):
def send(
self,
request: PreparedRequest,
stream: bool = False,
timeout: None | float | tuple[float, float] | tuple[float, None] = None,
verify: bool | str = True,
cert: None | bytes | str | tuple[bytes | str, bytes | str] = None,
prox... | S3Adapter |
python | doocs__leetcode | solution/0400-0499/0407.Trapping Rain Water II/Solution.py | {
"start": 0,
"end": 839
} | class ____:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
m, n = len(heightMap), len(heightMap[0])
vis = [[False] * n for _ in range(m)]
pq = []
for i in range(m):
for j in range(n):
if i == 0 or i == m - 1 or j == 0 or j == n - 1:
... | Solution |
python | python__mypy | mypy/report.py | {
"start": 11201,
"end": 15074
} | class ____(TraverserVisitor):
def __init__(self, source: list[str]) -> None:
self.source = source
# For each line of source, we maintain a pair of
# * the indentation level of the surrounding function
# (-1 if not inside a function), and
# * whether the surrounding func... | LineCoverageVisitor |
python | lepture__authlib | authlib/integrations/httpx_client/oauth2_client.py | {
"start": 2010,
"end": 6808
} | class ____(_OAuth2Client, httpx.AsyncClient):
SESSION_REQUEST_PARAMS = HTTPX_CLIENT_KWARGS
client_auth_class = OAuth2ClientAuth
token_auth_class = OAuth2Auth
oauth_error_class = OAuthError
def __init__(
self,
client_id=None,
client_secret=None,
token_endpoint_auth_m... | AsyncOAuth2Client |
python | pytorch__pytorch | test/distributed/checkpoint/test_hf_safetensor_e2e.py | {
"start": 16387,
"end": 21810
} | class ____(DTensorTestBase):
"""
Test DCP reshard for DTensor with placements changes and mesh_tensor change.
"""
@with_comms
@with_temp_dir
@skip_if_lt_x_gpu(2)
def test_1d_to_2d_reshard_mesh_change(self) -> None:
if importlib.util.find_spec("safetensors") is None:
prin... | TestDTensorReshardMeshChange |
python | python__mypy | mypy/report.py | {
"start": 21493,
"end": 22654
} | class ____:
"""Container for XML and statistics mapping python modules to Cobertura package."""
def __init__(self, name: str) -> None:
self.name = name
self.classes: dict[str, Any] = {}
self.packages: dict[str, CoberturaPackage] = {}
self.total_lines = 0
self.covered_lin... | CoberturaPackage |
python | sqlalchemy__sqlalchemy | examples/association/basic_association.py | {
"start": 1764,
"end": 3716
} | class ____(Base):
__tablename__ = "orderitem"
order_id: Mapped[int] = mapped_column(
ForeignKey("order.order_id"), primary_key=True
)
item_id: Mapped[int] = mapped_column(
ForeignKey("item.item_id"), primary_key=True
)
price: Mapped[float]
def __init__(self, item: Item, pric... | OrderItem |
python | jazzband__django-oauth-toolkit | oauth2_provider/management/commands/cleartokens.py | {
"start": 91,
"end": 281
} | class ____(BaseCommand): # pragma: no cover
help = "Can be run as a cronjob or directly to clean out expired tokens"
def handle(self, *args, **options):
clear_expired()
| Command |
python | realpython__materials | chatgpt-mentor/recursion_error.py | {
"start": 393,
"end": 728
} | class ____(list):
def push(self, item):
self.append(item)
def pop(self):
return super().pop()
def __repr__(self) -> str:
return f"{type(self).__name__}({self})"
When I call repr() with an instance of this class,
I get <repr-error 'maximum recursion depth exceeded'>
Can you help me ... | Stack |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/scoping.py | {
"start": 4153,
"end": 80094
} | class ____(Generic[_S]):
"""Provides scoped management of :class:`.Session` objects.
See :ref:`unitofwork_contextual` for a tutorial.
.. note::
When using :ref:`asyncio_toplevel`, the async-compatible
:class:`_asyncio.async_scoped_session` class should be
used in place of :class:`.sc... | scoped_session |
python | kubernetes-client__python | kubernetes/client/models/v1_condition.py | {
"start": 383,
"end": 10070
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1Condition |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassTransform2.py | {
"start": 1081,
"end": 1167
} | class ____(Customer1, frozen=False):
salary: float = model_field()
| Customer1Subclass |
python | modin-project__modin | modin/core/execution/dask/implementations/pandas_on_dask/partitioning/partition.py | {
"start": 1182,
"end": 13091
} | class ____(PandasDataframePartition):
"""
The class implements the interface in ``PandasDataframePartition``.
Parameters
----------
data : distributed.Future
A reference to pandas DataFrame that need to be wrapped with this class.
length : distributed.Future or int, optional
Len... | PandasOnDaskDataframePartition |
python | Textualize__textual | src/textual/events.py | {
"start": 21207,
"end": 21918
} | class ____(Event, bubble=False):
"""Sent when a widget is focussed.
- [ ] Bubbles
- [ ] Verbose
Args:
from_app_focus: True if this focus event has been sent because the app itself has
regained focus (via an AppFocus event). False if the focus came from within
the Textua... | Focus |
python | google__pytype | pytype/overlays/chex_overlay.py | {
"start": 619,
"end": 839
} | class ____(overlay.Overlay):
def __init__(self, ctx):
member_map = {
"dataclass": Dataclass.make,
}
ast = ctx.loader.import_name("chex")
super().__init__(ctx, "chex", member_map, ast)
| ChexOverlay |
python | ansible__ansible | lib/ansible/plugins/callback/minimal.py | {
"start": 673,
"end": 3237
} | class ____(CallbackBase):
"""
This is the default callback interface, which simply prints messages
to stdout when new callback events are received.
"""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
CALLBACK_NAME = 'minimal'
def _command_generic_msg(self, host, result, caption):
... | CallbackModule |
python | python__mypy | mypyc/irbuild/for_helpers.py | {
"start": 38476,
"end": 39055
} | class ____(ForDictionaryCommon):
"""Generate optimized IR for a for loop over dictionary values."""
dict_next_op = dict_next_value_op
dict_iter_op = dict_value_iter_op
def begin_body(self) -> None:
builder = self.builder
line = self.line
# Value is stored at the third place in... | ForDictionaryValues |
python | django__django | tests/validation/models.py | {
"start": 2377,
"end": 2682
} | class ____(models.Model):
other = models.IntegerField(blank=True, null=True)
number = models.IntegerField(
db_column="number_val",
error_messages={"null": "NULL", "not42": "AAARGH", "not_equal": "%s != me"},
validators=[validate_answer_to_universe],
)
| CustomMessagesModel |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 397570,
"end": 398755
} | class ____(Response):
"""
Response of tasks.update_batch endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
"""
_service = "tasks"
_action = "update_batch"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"updat... | UpdateBatchResponse |
python | pypa__warehouse | tests/unit/integration/secrets/test_utils.py | {
"start": 3176,
"end": 27065
} | class ____:
def test_init(self, metrics, someorigin):
session = pretend.stub()
token = "api_token"
url = "http://foo"
cache = integrations.PublicKeysCache(cache_time=12)
generic_verifier = utils.GenericTokenScanningPayloadVerifier(
origin=someorigin,
... | TestGenericTokenScanningPayloadVerifier |
python | ray-project__ray | python/ray/serve/_private/deployment_state.py | {
"start": 69341,
"end": 124295
} | class ____:
"""Manages the target state and replicas for a single deployment."""
FORCE_STOP_UNHEALTHY_REPLICAS = RAY_SERVE_FORCE_STOP_UNHEALTHY_REPLICAS
MAX_CONSTRUCTOR_RETRY_COUNT_WARNING_LOGGED = False
def __init__(
self,
id: DeploymentID,
long_poll_host: LongPollHost,
... | DeploymentState |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 18844,
"end": 19251
} | class ____(Element):
proto: MarkdownProto = field(repr=False)
is_caption: bool
allow_html: bool
key: None
def __init__(self, proto: MarkdownProto, root: ElementTree) -> None:
self.proto = proto
self.key = None
self.root = root
self.type = "markdown"
@property
... | Markdown |
python | django-guardian__django-guardian | example_project_custom_group/articles/migrations/0001_initial.py | {
"start": 126,
"end": 2855
} | class ____(migrations.Migration):
initial = True
dependencies = [
("auth", "0012_alter_user_first_name_max_length"),
("contenttypes", "0002_remove_content_type_name"),
]
operations = [
migrations.CreateModel(
name="Article",
fields=[
("id... | Migration |
python | doocs__leetcode | solution/0200-0299/0215.Kth Largest Element in an Array/Solution.py | {
"start": 0,
"end": 770
} | class ____:
def findKthLargest(self, nums: List[int], k: int) -> int:
def quick_sort(l: int, r: int) -> int:
if l == r:
return nums[l]
i, j = l - 1, r + 1
x = nums[(l + r) >> 1]
while i < j:
while 1:
i += 1
... | Solution |
python | doocs__leetcode | solution/1000-1099/1052.Grumpy Bookstore Owner/Solution.py | {
"start": 0,
"end": 454
} | class ____:
def maxSatisfied(
self, customers: List[int], grumpy: List[int], minutes: int
) -> int:
mx = cnt = sum(c * g for c, g in zip(customers[:minutes], grumpy))
for i in range(minutes, len(customers)):
cnt += customers[i] * grumpy[i]
cnt -= customers[i - min... | Solution |
python | scikit-image__scikit-image | tests/skimage/morphology/test_max_tree.py | {
"start": 1685,
"end": 20613
} | class ____(TestCase):
def test_max_tree(self):
"Test for max tree"
img_type = np.uint8
img = np.array(
[[10, 8, 8, 9], [7, 7, 9, 9], [8, 7, 10, 10], [9, 9, 10, 10]],
dtype=img_type,
)
P_exp = np.array(
[[1, 4, 1, 1], [4, 4, 3, 3], [1, 4, 3... | TestMaxtree |
python | pytorch__pytorch | torch/_inductor/codegen/triton.py | {
"start": 25150,
"end": 33786
} | class ____(PythonPrinter):
def _print_TruncToInt(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
return (
f"libdevice.trunc({self._print(expr.args[0])}).to({V.kernel.index_dtype})"
)
def _print_Float(self, expr: sympy.Expr) -> str:
if expr.is_integer:
... | TritonPrinter |
python | gevent__gevent | src/gevent/tests/test__example_portforwarder.py | {
"start": 363,
"end": 2025
} | class ____(util.TestServer):
example = 'portforwarder.py'
# [listen on, forward to]
example_args = ['127.0.0.1:10011', '127.0.0.1:10012']
if greentest.WIN:
from subprocess import CREATE_NEW_PROCESS_GROUP
# Must be in a new process group to use CTRL_C_EVENT, otherwise
# we get ki... | Test |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 90451,
"end": 91310
} | class ____(Response):
"""
Response of datasets.create_version endpoint.
:param id: ID of the version
:type id: str
"""
_service = "datasets"
_action = "create_version"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"id": {"description"... | CreateVersionResponse |
python | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 29581,
"end": 30292
} | class ____(ActionBaseModel):
"""Data used to create block document reference."""
id: UUID = Field(
default_factory=uuid4, description="The block document reference ID"
)
parent_block_document_id: UUID = Field(
default=..., description="ID of the parent block document"
)
referenc... | BlockDocumentReferenceCreate |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/agent.py | {
"start": 6871,
"end": 11176
} | class ____(BaseModel):
"""Base Multi Action Agent class."""
@property
def return_values(self) -> list[str]:
"""Return values of the agent."""
return ["output"]
def get_allowed_tools(self) -> list[str] | None:
"""Get allowed tools.
Returns:
Allowed tools.
... | BaseMultiActionAgent |
python | ray-project__ray | python/ray/tune/integration/lightgbm.py | {
"start": 343,
"end": 2713
} | class ____(RayReportCallback):
"""Creates a callback that reports metrics and checkpoints model.
Args:
metrics: Metrics to report. If this is a list,
each item should be a metric key reported by LightGBM,
and it will be reported to Ray Train/Tune under the same name.
... | TuneReportCheckpointCallback |
python | modin-project__modin | modin/pandas/iterator.py | {
"start": 992,
"end": 2287
} | class ____(Iterator):
"""
Iterator on partitioned data.
Parameters
----------
df : modin.pandas.DataFrame
The dataframe to iterate over.
axis : {0, 1}
Axis to iterate over.
func : callable
The function to get inner iterables from each partition.
"""
df: Data... | PartitionIterator |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/dag_sources.py | {
"start": 918,
"end": 1168
} | class ____(BaseModel):
"""DAG Source serializer for responses."""
content: str | None
dag_id: str
version_number: int | None
dag_display_name: str = Field(validation_alias=AliasPath("dag_model", "dag_display_name"))
| DAGSourceResponse |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 90773,
"end": 91056
} | class ____(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING
AutoModelForAudioFrameClassification = auto_class_update(
AutoModelForAudioFrameClassification, head_doc="audio frame (token) classification"
)
| AutoModelForAudioFrameClassification |
python | getsentry__sentry | tests/sentry/rules/actions/test_base.py | {
"start": 248,
"end": 1361
} | class ____(TestCase):
def setUp(self) -> None:
self.rule = self.create_project_rule(project=self.project)
self.notification_uuid = str(uuid4())
self.event_id = 456
self.rule_fire_history = RuleFireHistory.objects.create(
project=self.project,
rule=self.rule,
... | TestInstantiateAction |
python | pytorch__pytorch | test/jit/test_peephole.py | {
"start": 311,
"end": 29697
} | class ____(JitTestCase):
def test_peephole_with_writes(self):
def test_write(x):
s = 0
s += x
s += x
return s
self.checkScript(test_write, (torch.ones(4, 4),))
def test_peephole_with_non_output_writes(self):
@torch.jit.ignore
def ... | TestPeephole |
python | pallets__werkzeug | src/werkzeug/_reloader.py | {
"start": 9837,
"end": 15100
} | class ____(ReloaderLoop):
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
from watchdog.events import EVENT_TYPE_CLOSED
from watchdog.events import EVENT_TYPE_CREATED
from watchdog.events import EVENT_TYPE_DELETED
from watchdog.events import EVENT_TYPE_MODIFIED
fro... | WatchdogReloaderLoop |
python | getsentry__sentry | tests/sentry/sentry_apps/token_exchange/test_refresher.py | {
"start": 1059,
"end": 9548
} | class ____(TestCase):
def setUp(self) -> None:
self.install = self.create_sentry_app_installation()
self.client_id = self.install.sentry_app.application.client_id
self.user = self.install.sentry_app.proxy_user
self.token = self.install.api_token
self.refresher = Refresher(
... | TestRefresher |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.