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 | getsentry__sentry | src/sentry/sentry_metrics/querying/visitors/query_condition.py | {
"start": 1737,
"end": 3230
} | class ____(QueryConditionVisitor[QueryCondition]):
"""
Visitor that recursively transforms all conditions to work on tags in the form `tags[x]`.
"""
def __init__(self, check_sentry_tags: bool):
self._check_sentry_tags = check_sentry_tags
def _visit_condition(self, condition: Condition) -> ... | TagsTransformationVisitor |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/trajectory.py | {
"start": 1078,
"end": 2214
} | class ____:
@staticmethod
def get_name_at(index: int) -> AgentBufferKey:
"""
returns the name of the observation given the index of the observation
"""
return ObservationKeyPrefix.OBSERVATION, index
@staticmethod
def get_name_at_next(index: int) -> AgentBufferKey:
... | ObsUtil |
python | pydantic__pydantic | tests/test_pickle.py | {
"start": 5266,
"end": 7205
} | class ____(ImportableDataclass):
pass
def child_dataclass_factory() -> type:
class NonImportableChildDataclass(ImportableDataclass):
pass
return NonImportableChildDataclass
@pytest.mark.parametrize(
'dataclass_type,use_cloudpickle',
[
# Importable Pydantic dataclass can be pickl... | ImportableChildDataclass |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_select.py | {
"start": 25476,
"end": 29439
} | class ____(fixtures.TablesTest):
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer),
Column("y", Integer),
)
... | CompoundSelectTest |
python | marshmallow-code__marshmallow | tests/test_context.py | {
"start": 605,
"end": 8390
} | class ____:
def test_context_load_dump(self):
class ContextField(fields.Integer):
def _serialize(self, value, attr, obj, **kwargs):
if (context := Context[dict].get(None)) is not None:
value *= context.get("factor", 1)
return super()._serialize... | TestContext |
python | pennersr__django-allauth | allauth/socialaccount/providers/twitter/provider.py | {
"start": 230,
"end": 1106
} | class ____(ProviderAccount):
def get_screen_name(self):
"""The screen name is the username of the Twitter account."""
return self.account.extra_data.get("screen_name")
def get_profile_url(self):
ret = None
screen_name = self.get_screen_name()
if screen_name:
... | TwitterAccount |
python | openai__openai-python | src/openai/cli/_models.py | {
"start": 151,
"end": 491
} | class ____(_models.BaseModel):
if PYDANTIC_V1:
class Config(pydantic.BaseConfig): # type: ignore
extra: Any = pydantic.Extra.ignore # type: ignore
arbitrary_types_allowed: bool = True
else:
model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore", arbitrary_types... | BaseModel |
python | gevent__gevent | src/greentest/3.9/test_httplib.py | {
"start": 70163,
"end": 74415
} | class ____(TestCase):
"""Test cases where a request includes a message body."""
def setUp(self):
self.conn = client.HTTPConnection('example.com')
self.conn.sock = self.sock = FakeSocket("")
self.conn.sock = self.sock
def get_headers_and_fp(self):
f = io.BytesIO(self.sock.da... | RequestBodyTest |
python | pytorch__pytorch | torch/utils/tensorboard/writer.py | {
"start": 6443,
"end": 47533
} | class ____:
"""Writes entries directly to event files in the log_dir to be consumed by TensorBoard.
The `SummaryWriter` class provides a high-level API to create an event file
in a given directory and add summaries and events to it. The class updates the
file contents asynchronously. This allows a trai... | SummaryWriter |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/operators.py | {
"start": 3641,
"end": 5182
} | class ____(Hashable, Protocol):
"""describe an op() function."""
__slots__ = ()
__name__: str
@overload
def __call__(
self,
left: ColumnExpressionArgument[Any],
right: Optional[Any] = None,
*other: Any,
**kwargs: Any,
) -> ColumnElement[Any]: ...
@... | OperatorType |
python | pola-rs__polars | py-polars/src/polars/exceptions.py | {
"start": 4920,
"end": 5039
} | class ____(PolarsError):
"""Exception raised when unsuitable SQL is given to a database method."""
| UnsuitableSQLError |
python | huggingface__transformers | tests/models/regnet/test_modeling_regnet.py | {
"start": 3973,
"end": 7761
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as RegNet does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (RegNetModel, RegNetForImageClassification) if is_to... | RegNetModelTest |
python | python-pillow__Pillow | src/PIL/ExifTags.py | {
"start": 9461,
"end": 9931
} | class ____(IntEnum):
Unknown = 0x00
Daylight = 0x01
Fluorescent = 0x02
Tungsten = 0x03
Flash = 0x04
Fine = 0x09
Cloudy = 0x0A
Shade = 0x0B
DaylightFluorescent = 0x0C
DayWhiteFluorescent = 0x0D
CoolWhiteFluorescent = 0x0E
WhiteFluorescent = 0x0F
StandardLightA = 0x11
... | LightSource |
python | spack__spack | lib/spack/spack/vendor/jinja2/nativetypes.py | {
"start": 2543,
"end": 2703
} | class ____(Environment):
"""An environment that renders templates to native Python types."""
code_generator_class = NativeCodeGenerator
| NativeEnvironment |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/type_api.py | {
"start": 86057,
"end": 87744
} | class ____(TypeDecorator[_T]):
"""deprecated. symbol is present for backwards-compatibility with
workaround recipes, however this actual type should not be used.
"""
def __init__(self, *arg: Any, **kw: Any):
raise NotImplementedError(
"Variant is no longer used in SQLAlchemy; this... | Variant |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/integration_test/public_symbol_test.py | {
"start": 828,
"end": 1058
} | class ____(tf.test.TestCase):
def testSimple(self):
a = 0.1
b = 0.2
self.assertAllClose(onp.add(a, b), np.add(a, b))
if __name__ == "__main__":
tf.compat.v1.enable_eager_execution()
tf.test.main()
| PublicSymbolTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_selection.py | {
"start": 42746,
"end": 43391
} | class ____(AssetSelection):
"""Used to represent a UI asset selection by table name. This should not be resolved against
an in-process asset graph.
"""
selected_table_name: Optional[str]
def resolve_inner(
self, asset_graph: BaseAssetGraph, allow_missing: bool
) -> AbstractSet[AssetKey... | TableNameAssetSelection |
python | django__django | tests/i18n/tests.py | {
"start": 77880,
"end": 78116
} | class ____(ResolutionOrderI18NTests):
def test_django_fallback(self):
self.assertEqual(gettext("Date/time"), "Datum/Zeit")
@override_settings(INSTALLED_APPS=["i18n.territorial_fallback"])
| DjangoFallbackResolutionOrderI18NTests |
python | networkx__networkx | networkx/algorithms/bipartite/tests/test_basic.py | {
"start": 81,
"end": 4291
} | class ____:
def test_is_bipartite(self):
assert bipartite.is_bipartite(nx.path_graph(4))
assert bipartite.is_bipartite(nx.DiGraph([(1, 0)]))
assert not bipartite.is_bipartite(nx.complete_graph(3))
def test_bipartite_color(self):
G = nx.path_graph(4)
c = bipartite.color(G... | TestBipartiteBasic |
python | google__jax | tests/pallas/fusion_test.py | {
"start": 8952,
"end": 9431
} | class ____(jtu.JaxTestCase):
def test_basic_fusion(self):
@jax.jit
@fuser.fuse
@fuser.fusible
def f(x_fn, y_fn):
x = x_fn()
if y_fn is None:
y_fn = lambda x: x
return y_fn(x)
xt = ArrayTuple(x0=jnp.ones((8, 8)), x1=jnp.zeros(4))
ot = f(xt)
np.testing.assert_arr... | FusionHijaxTest |
python | tensorflow__tensorflow | tensorflow/python/ops/special_math_ops_test.py | {
"start": 26816,
"end": 39839
} | class ____(test.TestCase):
def _check(self, s, *input_shapes, **kwargs):
dtype = kwargs.pop('dtype', np.float32)
r = np.random.RandomState(0)
inputs = []
for shape in input_shapes:
arr = np.array(r.randn(*shape)).astype(dtype)
if dtype == np.complex64 or dtype == np.complex128:
ar... | EinsumTest |
python | pandas-dev__pandas | pandas/tests/indexing/test_coercion.py | {
"start": 482,
"end": 815
} | class ____:
klasses = ["index", "series"]
dtypes = [
"object",
"int64",
"float64",
"complex128",
"bool",
"datetime64",
"datetime64tz",
"timedelta64",
"period",
]
@property
def method(self):
raise NotImplementedError(sel... | CoercionBase |
python | walkccc__LeetCode | solutions/313. Super Ugly Number/313.py | {
"start": 0,
"end": 409
} | class ____:
def nthSuperUglyNumber(self, n: int, primes: list[int]) -> int:
k = len(primes)
nums = [1]
indices = [0] * k
while len(nums) < n:
nexts = [0] * k
for i in range(k):
nexts[i] = nums[indices[i]] * primes[i]
next = min(nexts)
for i in range(k):
if next... | Solution |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/vgg_block_test.py | {
"start": 1176,
"end": 2520
} | class ____(trt_test.TfTrtIntegrationTestBase):
"""Single vgg layer test in TF-TRT conversion."""
def GraphFn(self, x):
dtype = x.dtype
x, _, _ = nn_impl.fused_batch_norm(
x, [1.0, 1.0], [0.0, 0.0],
mean=[0.5, 0.5],
variance=[1.0, 1.0],
is_training=False)
e = constant_op.... | VGGBlockTest |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 817543,
"end": 818979
} | class ____(VegaLiteSchema):
"""
OrderValueDef schema wrapper.
Parameters
----------
value : dict, float, :class:`ExprRef`
A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient
definition <https://vega.github.io/vega-lite/docs/types.html#gradient>`__ for colo... | OrderValueDef |
python | django__django | tests/migrations/test_migrations_no_changes/0002_second.py | {
"start": 43,
"end": 666
} | class ____(migrations.Migration):
dependencies = [
("migrations", "0001_initial"),
]
operations = [
migrations.DeleteModel("Tribble"),
migrations.RemoveField("Author", "silly_field"),
migrations.AddField("Author", "rating", models.IntegerField(default=0)),
migrations... | Migration |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/build_systems/python.py | {
"start": 416,
"end": 705
} | class ____(PythonExtension):
build_system_class = "PythonPackage"
default_buildsystem = "python_pip"
install_time_test_callbacks = ["test_imports"]
build_system("python_pip")
extends("python", when="build_system=python_pip")
@register_builder("python_pip")
| PythonPackage |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict5.py | {
"start": 393,
"end": 1297
} | class ____(TypedDict, total=True):
name: str
year: float
movie1: Movie1 = Movie2(name="hello", year=1971)
# This should generate an error because
# items are required in Movie3 but not Movie2.
movie2: Movie2 = Movie3(name="hello", year=1971)
# This should generate an error because
# items are required in Mo... | Movie5 |
python | django__django | tests/model_options/test_tablespaces.py | {
"start": 816,
"end": 5441
} | class ____(TransactionTestCase):
available_apps = ["model_options"]
def setUp(self):
# The unmanaged models need to be removed after the test in order to
# prevent bad interactions with the flush operation in other tests.
self._old_models = apps.app_configs["model_options"].models.copy(... | TablespacesTests |
python | Lightning-AI__lightning | examples/pytorch/bug_report/bug_report_model.py | {
"start": 131,
"end": 388
} | class ____(Dataset):
def __init__(self, size, length):
self.len = length
self.data = torch.randn(length, size)
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return self.len
| RandomDataset |
python | django__django | tests/template_tests/filter_tests/test_unordered_list.py | {
"start": 2075,
"end": 6180
} | class ____(SimpleTestCase):
def test_list(self):
self.assertEqual(
unordered_list(["item 1", "item 2"]), "\t<li>item 1</li>\n\t<li>item 2</li>"
)
def test_list_gettext(self):
self.assertEqual(
unordered_list(["item 1", gettext_lazy("item 2")]),
"\t<li... | FunctionTests |
python | getsentry__sentry | src/sentry/integrations/github_enterprise/webhook.py | {
"start": 3596,
"end": 3690
} | class ____(GitHubEnterpriseWebhook, PushEventWebhook):
pass
| GitHubEnterprisePushEventWebhook |
python | streamlit__streamlit | lib/tests/streamlit/commands/experimental_query_params_test.py | {
"start": 970,
"end": 3971
} | class ____(DeltaGeneratorTestCase):
"""Test Query params commands APIs."""
def test_set_query_params_sends_protobuf_message(self):
"""Test valid st.set_query_params sends protobuf message."""
st.experimental_set_query_params(x="a")
message = self.get_message_from_queue(0)
assert... | QueryParamsAPITest |
python | TheAlgorithms__Python | data_structures/binary_tree/is_sorted.py | {
"start": 736,
"end": 3044
} | class ____:
data: float
left: Node | None = None
right: Node | None = None
def __iter__(self) -> Iterator[float]:
"""
>>> root = Node(data=2.1)
>>> list(root)
[2.1]
>>> root.left=Node(data=2.0)
>>> list(root)
[2.0, 2.1]
>>> root.right=Node... | Node |
python | huggingface__transformers | src/transformers/models/edgetam/configuration_edgetam.py | {
"start": 5641,
"end": 7737
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`EdgeTamPromptEncoder`]. The [`EdgeTamPromptEncoder`]
module is used to encode the input 2D points and bounding boxes.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control t... | EdgeTamPromptEncoderConfig |
python | scipy__scipy | scipy/sparse/tests/test_base.py | {
"start": 223038,
"end": 223107
} | class ____(COONonCanonicalMixin, TestCOO):
pass
| TestCOONonCanonical |
python | pytorch__pytorch | test/distributed/_shard/sharded_tensor/test_sharded_tensor_reshard.py | {
"start": 831,
"end": 3572
} | class ____(ShardedTensorTestBase):
def _run_sharded_tensor_reshard(self, sharding_spec, reshard_spec, input_size):
torch.manual_seed(0)
local_tensor = torch.rand(*input_size).cuda(self.rank)
st = _shard_tensor(local_tensor, sharding_spec)
st_compare = _shard_tensor(local_tensor, resh... | TestReshard |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 97857,
"end": 98112
} | class ____:
xlDisplayPropertyInPivotTable = 1 # from enum XlPropertyDisplayedIn
xlDisplayPropertyInPivotTableAndTooltip = 3 # from enum XlPropertyDisplayedIn
xlDisplayPropertyInTooltip = 2 # from enum XlPropertyDisplayedIn
| PropertyDisplayedIn |
python | dagster-io__dagster | python_modules/libraries/dagster-celery/dagster_celery/launcher.py | {
"start": 1156,
"end": 8754
} | class ____(RunLauncher, ConfigurableClass):
"""Dagster [Run Launcher](https://docs.dagster.io/guides/deploy/execution/run-launchers) which
starts runs as Celery tasks.
"""
_instance: DagsterInstance # pyright: ignore[reportIncompatibleMethodOverride]
celery: Celery
def __init__(
self,... | CeleryRunLauncher |
python | google__jax | tests/array_extensibility_test.py | {
"start": 2053,
"end": 2663
} | class ____(NamedTuple):
fun: Callable[..., Any]
args: list[jax.ShapeDtypeStruct]
kwargs: dict[str, Any]
skip_on_devices: list[str] | None
def name(self):
return self.fun.__name__
def make_args(self, rng):
rng = jtu.rand_default(rng)
return jax.tree.map(lambda arg: rng(arg.shape, arg.dtype), se... | NumPyAPI |
python | kamyu104__LeetCode-Solutions | Python/pairs-of-songs-with-total-durations-divisible-by-60.py | {
"start": 50,
"end": 357
} | class ____(object):
def numPairsDivisibleBy60(self, time):
"""
:type time: List[int]
:rtype: int
"""
result = 0
count = collections.Counter()
for t in time:
result += count[-t%60]
count[t%60] += 1
return result
| Solution |
python | openai__openai-python | src/openai/resources/models.py | {
"start": 10440,
"end": 10823
} | class ____:
def __init__(self, models: Models) -> None:
self._models = models
self.retrieve = to_streamed_response_wrapper(
models.retrieve,
)
self.list = to_streamed_response_wrapper(
models.list,
)
self.delete = to_streamed_response_wrapper(... | ModelsWithStreamingResponse |
python | viewflow__viewflow | viewflow/workflow/flow/views/actions.py | {
"start": 1087,
"end": 1701
} | class ____(
mixins.SuccessMessageMixin,
mixins.TaskSuccessUrlMixin,
mixins.TaskViewTemplateNames,
generic.FormView,
):
"""
Default unassign view for flow task.
Get confirmation from user, and unassign task
"""
form_class = forms.Form
template_filename = "task_unassign.html"
... | UnassignTaskView |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/conv.py | {
"start": 12078,
"end": 16624
} | class ____(_ConvNd):
r"""Applies a 1D convolution over a quantized input signal composed of
several quantized input planes.
For details on input arguments, parameters, and implementation see
:class:`~torch.nn.Conv1d`.
.. note::
Only `zeros` is supported for the :attr:`padding_mode` argumen... | Conv1d |
python | realpython__materials | django-markdown/dmd_app/admin.py | {
"start": 72,
"end": 225
} | class ____(admin.ModelAdmin):
prepopulated_fields = {"slug": ["title"]}
admin.site.register(MarkdownContent, MarkdownContentAdmin)
| MarkdownContentAdmin |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 71479,
"end": 73953
} | class ____(NonStrictDataModel):
"""
:param model_urls:
:type model_urls: Sequence[str]
:param event_urls:
:type event_urls: Sequence[str]
:param artifact_urls:
:type artifact_urls: Sequence[str]
"""
_schema = {
"properties": {
"artifact_urls": {"items": {"type": ... | TaskUrls |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_mcp_toolset_param.py | {
"start": 474,
"end": 1040
} | class ____(TypedDict, total=False):
mcp_server_name: Required[str]
"""Name of the MCP server to configure tools for"""
type: Required[Literal["mcp_toolset"]]
cache_control: Optional[BetaCacheControlEphemeralParam]
"""Create a cache control breakpoint at this content block."""
configs: Optiona... | BetaMCPToolsetParam |
python | facebook__pyre-check | tools/generate_taint_models/get_constructor_initialized_attribute_sources.py | {
"start": 661,
"end": 3828
} | class ____(ModelGenerator[AssignmentModel]):
"""
This Generator will taint the attributes initialized by the constructors of
'classes_to_taint' and their descendants. Only descendants that have had
their modules loaded at preprocessing time will be tainted. Models are
generated on a best effort basi... | ConstructorInitializedAttributeSourceGenerator |
python | lxml__lxml | src/lxml/html/formfill.py | {
"start": 427,
"end": 5721
} | class ____(LookupError):
"""
Raised when no form can be found
"""
_form_name_xpath = XPath('descendant-or-self::form[name=$name]|descendant-or-self::x:form[name=$name]', namespaces={'x':XHTML_NAMESPACE})
_input_xpath = XPath('|'.join(['descendant-or-self::'+_tag for _tag in ('input','select','textarea','x:... | FormNotFound |
python | pytorch__pytorch | torch/fx/graph.py | {
"start": 35503,
"end": 36889
} | class ____(CodeGen):
"""
CodeGen subclass that generates code using the "boxed" calling convention.
The boxed calling convention takes a single list argument and clears it
after extracting the arguments, which allows for early deallocation of
input tensors.
"""
def gen_fn_def(
self... | _BoxedCodeGen |
python | apache__airflow | providers/databricks/tests/unit/databricks/operators/test_databricks_repos.py | {
"start": 5897,
"end": 9037
} | class ____:
@mock.patch("airflow.providers.databricks.operators.databricks_repos.DatabricksHook")
def test_create_plus_checkout(self, db_mock_class):
"""
Test the execute function creating new Repo.
"""
git_url = "https://github.com/test/test"
repo_path = "/Repos/Project1... | TestDatabricksReposCreateOperator |
python | celery__celery | celery/app/trace.py | {
"start": 4683,
"end": 30264
} | class ____:
"""Information about task execution."""
__slots__ = ('state', 'retval')
def __init__(self, state, retval=None):
self.state = state
self.retval = retval
def handle_error_state(self, task, req,
eager=False, call_errbacks=True):
if task.igno... | TraceInfo |
python | pytorch__pytorch | test/inductor/test_split_cat_fx_aten_passes.py | {
"start": 1991,
"end": 4358
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
def forward(
self, x1: torch.Tensor, x2: torch.Tensor, y: torch.Tensor, z: torch.Tensor
):
split_with_sizes_1 = torch.ops.aten.split_with_sizes.default(
x1,
[
96,
... | TestSplitCatPartial |
python | PyCQA__pylint | doc/data/messages/p/protected-access/bad.py | {
"start": 0,
"end": 103
} | class ____:
def __swallow(self):
pass
jim = Worm()
jim.__swallow() # [protected-access]
| Worm |
python | ray-project__ray | rllib/models/tf/tf_action_dist.py | {
"start": 20550,
"end": 21402
} | class ____(TFActionDistribution):
"""Action distribution that returns the input values directly.
This is similar to DiagGaussian with standard deviation zero (thus only
requiring the "mean" values as NN output).
"""
@override(ActionDistribution)
def deterministic_sample(self) -> TensorType:
... | Deterministic |
python | pytorch__pytorch | test/distributed/elastic/multiprocessing/api_test.py | {
"start": 5824,
"end": 39233
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.test_dir = tempfile.mkdtemp(prefix=f"{self.__class__.__name__}_")
self._start_methods = ["spawn"]
def tearDown(self):
super().tearDown()
shutil.rmtree(self.test_dir)
def log_dir(self):
return tempfi... | _StartProcessesTest |
python | pypa__pipenv | benchmarks/benchmark.py | {
"start": 243,
"end": 12847
} | class ____:
def __init__(self, benchmark_dir: Path):
self.benchmark_dir = benchmark_dir
self.timings_dir = benchmark_dir / "timings"
self.timings_dir.mkdir(exist_ok=True)
self.requirements_url = "https://raw.githubusercontent.com/getsentry/sentry/51281a6abd8ff4a93d2cebc04e1d5fc7aa9c4... | PipenvBenchmark |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/asb.py | {
"start": 28858,
"end": 30498
} | class ____(BaseOperator):
"""
Delete the topic in the Azure Service Bus namespace.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:AzureServiceBusTopicDeleteOperator`
:param topic_name: Name of the topic to be deleted.
:... | AzureServiceBusTopicDeleteOperator |
python | aio-libs__aiohttp | aiohttp/client_exceptions.py | {
"start": 5757,
"end": 5847
} | class ____(ClientConnectionError):
"""Server connection errors."""
| ServerConnectionError |
python | kamyu104__LeetCode-Solutions | Python/naming-a-company.py | {
"start": 61,
"end": 567
} | class ____(object):
def distinctNames(self, ideas):
"""
:type ideas: List[str]
:rtype: int
"""
lookup = [set() for _ in xrange(26)]
for x in ideas:
lookup[ord(x[0])-ord('a')].add(x[1:])
result = 0
for i in xrange(len(lookup)):
f... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/non_slot_assignment.py | {
"start": 1639,
"end": 1886
} | class ____:
names = ("surname",)
__slots__ = (*names, "a")
def __init__(self, name, surname):
self.name = name
self.surname = surname # [assigning-non-slot]
self.setup()
def setup(self):
pass
| StudentG |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 148001,
"end": 148657
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"issue_id",
"repository_id",
"create_labels_if_missing",
"client_mutation_id",
)
issue_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graph... | TransferIssueInput |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/associationproxy.py | {
"start": 47245,
"end": 49196
} | class ____(Generic[_IT]):
getter: _GetterProtocol[_IT]
"""A function. Given an associated object, return the 'value'."""
creator: _CreatorProtocol
"""
A function that creates new target entities. Given one parameter:
value. This assertion is assumed::
obj = creator(somevalue)
assert... | _AssociationCollection |
python | pypa__warehouse | warehouse/accounts/services.py | {
"start": 36900,
"end": 38488
} | class ____:
def __init__(
self,
*,
session,
api_base="https://haveibeenpwned.com/api/v3/breachedaccount/",
api_key=None,
):
self._http = session
self._api_base = api_base
self.api_key = api_key
@classmethod
def create_service(cls, context,... | HaveIBeenPwnedEmailBreachedService |
python | django-haystack__django-haystack | haystack/exceptions.py | {
"start": 203,
"end": 305
} | class ____(HaystackError):
"""Raised when a field encounters an error."""
pass
| SearchFieldError |
python | tensorflow__tensorflow | tensorflow/python/ops/math_ops_test.py | {
"start": 51418,
"end": 52361
} | class ____(test_util.TensorFlowTestCase):
def testConvertToTensorRange(self):
values = range(5)
tensor = ops.convert_to_tensor(values)
self.assertAllEqual((5,), tensor.get_shape().as_list())
self.assertAllEqual(values, self.evaluate(tensor))
def testInputsNearInt64Max(self):
int64_t_max = 2**6... | RangeTest |
python | vyperlang__vyper | vyper/builtins/functions.py | {
"start": 46496,
"end": 48523
} | class ____(BuiltinFunctionT):
_id = "shift"
_inputs = [("x", (UINT256_T, INT256_T)), ("_shift_bits", IntegerT.any())]
_return_type = UINT256_T
def _try_fold(self, node):
vyper_warn("`shift()` is deprecated! Please use the << or >> operator instead.", node)
validate_call_args(node, 2)
... | Shift |
python | spyder-ide__spyder | spyder/plugins/switcher/api.py | {
"start": 184,
"end": 289
} | class ____:
FileSwitcherAction = 'file switcher'
SymbolFinderAction = 'symbol finder'
| SwitcherActions |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 113148,
"end": 118129
} | class ____(ASTBase):
def __init__(self, declSpecs: ASTDeclSpecs, decl: ASTDeclarator) -> None:
assert declSpecs
assert decl
self.declSpecs = declSpecs
self.decl = decl
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTType):
return NotImple... | ASTType |
python | Netflix__metaflow | test/unit/inheritance/test_inheritance.py | {
"start": 386,
"end": 2101
} | class ____:
"""Test comprehensive linear inheritance: FlowSpec -> BaseA -> BaseB -> BaseC -> Flow"""
def test_flow_completes(self, comprehensive_linear_run):
"""Test that the flow completes successfully"""
assert comprehensive_linear_run.successful
assert comprehensive_linear_run.finish... | TestComprehensiveLinear |
python | apache__airflow | airflow-ctl/src/airflowctl/api/operations.py | {
"start": 14202,
"end": 17079
} | class ____(BaseOperations):
"""Connection operations."""
def get(self, conn_id: str) -> ConnectionResponse | ServerResponseError:
"""Get a connection from the API server."""
try:
self.response = self.client.get(f"connections/{conn_id}")
return ConnectionResponse.model_va... | ConnectionsOperations |
python | plotly__plotly.py | plotly/graph_objs/scatter/marker/colorbar/_title.py | {
"start": 233,
"end": 4021
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter.marker.colorbar"
_path_str = "scatter.marker.colorbar.title"
_valid_props = {"font", "side", "text"}
@property
def font(self):
"""
Sets this color bar's title font.
The 'font' property is an instance of Font
... | Title |
python | google__pytype | pytype/tests/test_attr2.py | {
"start": 27838,
"end": 32364
} | class ____(test_base.BaseTest):
"""Tests for @attr.s in pyi files."""
def test_basic(self):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
"""
import attr
@attr.s
class A:
x: int
y: str
""",
)
self.Check(
... | TestPyiAttrs |
python | huggingface__transformers | src/transformers/models/qwen3_moe/configuration_qwen3_moe.py | {
"start": 897,
"end": 10213
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Qwen3MoeModel`]. It is used to instantiate a
Qwen3MoE model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar con... | Qwen3MoeConfig |
python | numpy__numpy | numpy/lib/tests/test_recfunctions.py | {
"start": 43278,
"end": 43973
} | class ____:
"""
Test append_fields with arrays containing objects
"""
# https://github.com/numpy/numpy/issues/2346
def test_append_to_objects(self):
"Test append_fields when the base array contains objects"
from datetime import date
obj = date(2000, 1, 1)
x = np.arra... | TestAppendFieldsObj |
python | python-openxml__python-docx | tests/oxml/test_xmlchemy.py | {
"start": 27031,
"end": 27142
} | class ____(BaseBuilder):
__tag__ = "w:oomChild"
__nspfxs__ = ("w",)
__attrs__ = ()
| CT_OomChildBuilder |
python | sqlalchemy__sqlalchemy | test/engine/test_pool.py | {
"start": 26027,
"end": 28960
} | class ____(PoolTestBase):
"""test for :ticket:`2964`, where the pool would not mutex the
initialization of the dialect.
Unfortunately, as discussed in :ticket:`6337`, this test suite did not
ensure that the ``Engine`` itself actually uses the "first_connect" event,
so when :ticket:`5497` came along... | PoolFirstConnectSyncTest |
python | wandb__wandb | tests/unit_tests/conftest.py | {
"start": 382,
"end": 2037
} | class ____:
def __init__(self, queue: "Queue") -> None:
self.records = []
while not queue.empty():
self.records.append(queue.get())
def __len__(self) -> int:
return len(self.records)
def __getitem__(self, name: str) -> Generator:
for record in self.records:
... | RecordsUtil |
python | streamlit__streamlit | lib/tests/streamlit/temporary_directory_test.py | {
"start": 777,
"end": 1147
} | class ____(unittest.TestCase):
"""Test temp directory context manager."""
@tempdir()
def test_temp_directory(self, dir):
"""Test that the directory only exists inside the context."""
with TemporaryDirectory(dir=dir.path) as temp_fname:
assert os.path.exists(temp_fname)
a... | TemporaryFileTest |
python | openai__openai-python | src/openai/_exceptions.py | {
"start": 4616,
"end": 4836
} | class ____(OpenAIError):
def __init__(self) -> None:
super().__init__(
f"Could not parse response content as the request was rejected by the content filter",
)
| ContentFilterFinishReasonError |
python | coleifer__peewee | tests/models.py | {
"start": 177168,
"end": 177256
} | class ____(TestModel):
name = CharField()
price = IntegerField(default=0)
| C_Product |
python | walkccc__LeetCode | solutions/3489. Zero Array Transformation IV/3489.py | {
"start": 0,
"end": 483
} | class ____:
def minZeroArray(self, nums: list[int], queries: list[list[int]]) -> int:
if all(num == 0 for num in nums):
return 0
n = len(nums)
subsetSums = [{0} for _ in range(n)]
for k, (l, r, val) in enumerate(queries):
for i in range(l, r + 1):
newSums = {subsetSum + val for s... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 493462,
"end": 494196
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for CheckSuite."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("CheckSuiteEdge"), graphql_name="edges")
"""A list of edges."""
nodes = ... | CheckSuiteConnection |
python | pypa__warehouse | tests/unit/cache/test_http.py | {
"start": 849,
"end": 3376
} | class ____:
def test_cache_public(self):
response_obj = pretend.stub(
cache_control=pretend.stub(public=None, max_age=None)
)
request_obj = pretend.stub(registry=pretend.stub(settings={}))
context_obj = pretend.stub()
@cache_control(12)
def view(context, ... | TestCacheControl |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadCall4.py | {
"start": 595,
"end": 3424
} | class ____(Enum):
x00 = 0
x01 = 0
x02 = 0
x03 = 0
x04 = 0
x05 = 0
x06 = 0
x07 = 0
x08 = 0
x09 = 0
x10 = 0
x11 = 0
x12 = 0
x13 = 0
x14 = 0
x15 = 0
x16 = 0
x17 = 0
x18 = 0
x19 = 0
x20 = 0
x21 = 0
x22 = 0
x23 = 0
x24 = 0
... | LargeEnum |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 12048,
"end": 12198
} | class ____(SubclassSelectorAbstractModel):
concrete_field = models.CharField(max_length=30, default="test_cf")
| SubclassSelectorAbstractConcreteModel |
python | scikit-learn__scikit-learn | sklearn/linear_model/_omp.py | {
"start": 21893,
"end": 30243
} | class ____(MultiOutputMixin, RegressorMixin, LinearModel):
"""Orthogonal Matching Pursuit model (OMP).
Read more in the :ref:`User Guide <omp>`.
Parameters
----------
n_nonzero_coefs : int, default=None
Desired number of non-zero entries in the solution. Ignored if `tol` is set.
Wh... | OrthogonalMatchingPursuit |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/metadata/pipeline.py | {
"start": 1951,
"end": 3820
} | class ____(SimpleDockerStep):
# When the metadata service exits with this code, it means the metadata is valid but the upload was skipped because the metadata is already uploaded
skipped_exit_code = 5
def __init__(
self,
context: ConnectorContext,
metadata_bucket_name: str,
... | MetadataUpload |
python | modin-project__modin | modin/core/execution/unidist/implementations/pandas_on_unidist/partitioning/virtual_partition.py | {
"start": 8937,
"end": 9104
} | class ____(PandasOnUnidistDataframeVirtualPartition):
axis = 0
@_inherit_docstrings(PandasOnUnidistDataframeVirtualPartition)
| PandasOnUnidistDataframeColumnPartition |
python | ray-project__ray | python/ray/data/collate_fn.py | {
"start": 4684,
"end": 5354
} | class ____(CollateFn["pyarrow.Table"]):
"""Collate function that takes pyarrow.Table as the input batch type.
Arrow tables with chunked arrays can be efficiently transferred to GPUs without
combining the chunks with the `arrow_batch_to_tensors` utility function.
See `DefaultCollateFn` for example.
"... | ArrowBatchCollateFn |
python | django__django | tests/prefetch_related/models.py | {
"start": 2947,
"end": 3088
} | class ____(models.Manager):
def get_queryset(self):
return super().get_queryset().prefetch_related("qualifications")
| TeacherManager |
python | ipython__ipython | docs/sphinxext/apigen.py | {
"start": 974,
"end": 2622
} | class ____(ast.NodeVisitor):
"""Scan a module for top-level functions and classes.
Skips objects with an @undoc decorator, or a name starting with '_'.
"""
def __init__(self):
ast.NodeVisitor.__init__(self)
self.classes = []
self.classes_seen = set()
self.functions =... | FuncClsScanner |
python | huggingface__transformers | src/transformers/models/swin/modeling_swin.py | {
"start": 36111,
"end": 39852
} | class ____(SwinPreTrainedModel):
def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
r"""
add_pooling_layer (`bool`, *optional*, defaults to `True`):
Whether or not to apply pooling layer.
use_mask_token (`bool`, *optional*, defaults to `False`):
... | SwinModel |
python | huggingface__transformers | tests/models/git/test_modeling_git.py | {
"start": 4403,
"end": 7090
} | class ____(ModelTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as GIT does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (GitVisionModel,) if is_torch_available() else ()
test_resize_embedding... | GitVisionModelTest |
python | doocs__leetcode | solution/2200-2299/2217.Find Palindrome With Fixed Length/Solution.py | {
"start": 0,
"end": 441
} | class ____:
def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:
l = (intLength + 1) >> 1
start, end = 10 ** (l - 1), 10**l - 1
ans = []
for q in queries:
v = start + q - 1
if v > end:
ans.append(-1)
continu... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride2.py | {
"start": 788,
"end": 1919
} | class ____(Base1):
def f1(self, arg0: int = 0, *, kwarg0: int, kwarg1: int = 0) -> None: ...
# This should generate an error because of a positional parameter mismatch.
def f2(self, arg0: int, *, kwarg0: int, kwarg1: int = 0) -> None: ...
# This should generate an error because of a missing kwarg1.
... | Derived1 |
python | allegroai__clearml | clearml/backend_interface/task/development/worker.py | {
"start": 380,
"end": 6483
} | class ____(object):
property_abort_callback_completed = "_abort_callback_completed"
property_abort_callback_timeout = "_abort_callback_timeout"
property_abort_poll_freq = "_abort_poll_freq"
prefix = attr.ib(type=str, default="MANUAL:")
report_stdout = deferred_config("development.worker.log_stdout... | DevWorker |
python | pypa__warehouse | tests/unit/utils/test_sns.py | {
"start": 2342,
"end": 13207
} | class ____:
@pytest.mark.parametrize(
("topics", "data", "error"),
[
([], {}, "Unknown SignatureVersion"),
([], {"SignatureVersion": "1"}, "Unknown SignatureVersion"),
([], {"SignatureVersion": "3"}, "Unknown SignatureVersion"),
(
[],
... | TestMessageVerifier |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType7.py | {
"start": 714,
"end": 1001
} | class ____(Generic[_T2, _T2A]):
def __init__(self, a: _T2, b: _T2A):
self._a1: dict[str, _T2A] = {"a": b}
self._a2: dict[str, _T2] = {"a": a}
self._b: tuple[_T2, ...] = (a, a, a)
self._c: tuple[_T2, _T2] = (a, a)
self._d: list[_T2] = [a]
| Class2A |
python | milvus-io__pymilvus | pymilvus/client/types.py | {
"start": 9865,
"end": 11069
} | class ____:
"""
This class represents replica info in orm format api, which is deprecated in milvus client api.
use `ReplicaInfo` instead.
"""
def __init__(
self,
group_id: int,
shards: List[str],
group_nodes: List[tuple],
resource_group: str,
num_out... | Group |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.