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 | pypa__pip | src/pip/_vendor/rich/columns.py | {
"start": 469,
"end": 7131
} | class ____(JupyterMixin):
"""Display renderables in neat columns.
Args:
renderables (Iterable[RenderableType]): Any number of Rich renderables (including str).
width (int, optional): The desired width of the columns, or None to auto detect. Defaults to None.
padding (PaddingDimensions, ... | Columns |
python | pandas-dev__pandas | pandas/tests/arithmetic/test_period.py | {
"start": 19409,
"end": 20836
} | class ____:
def test_ops_frame_period(self):
# GH#13043
df = pd.DataFrame(
{
"A": [Period("2015-01", freq="M"), Period("2015-02", freq="M")],
"B": [Period("2014-01", freq="M"), Period("2014-02", freq="M")],
}
)
assert df["A"].dt... | TestPeriodFrameArithmetic |
python | scipy__scipy | scipy/sparse/linalg/_eigen/tests/test_svds.py | {
"start": 35858,
"end": 35961
} | class ____(SVDSCommonTests):
def setup_method(self):
self.solver = 'lobpcg'
| Test_SVDS_LOBPCG |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 106434,
"end": 106564
} | class ____(BaseModel, extra="forbid"):
replicate_points: "ReplicatePoints" = Field(..., description="")
| ReplicatePointsOperation |
python | streamlit__streamlit | lib/tests/streamlit/form_test.py | {
"start": 7133,
"end": 10449
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall form protos."""
def test_marshall_form(self):
"""Creating a form should result in the expected protobuf data."""
# Test with clear_on_submit=True
with st.form(key="foo", clear_on_submit=True):
pass
ass... | FormMarshallingTest |
python | great-expectations__great_expectations | great_expectations/core/expectation_diagnostics/supporting_types.py | {
"start": 5406,
"end": 5801
} | class ____(SerializableDictDot):
"""A holder for ExpectationDiagnosticCheckMessages, grouping them by maturity level. Used within the ExpectationDiagnostic object.""" # noqa: E501 # FIXME CoP
experimental: List[ExpectationDiagnosticCheckMessage]
beta: List[ExpectationDiagnosticCheckMessage]
production... | ExpectationDiagnosticMaturityMessages |
python | neetcode-gh__leetcode | python/0374-guess-number-higher-or-lower.py | {
"start": 0,
"end": 405
} | class ____:
def guessNumber(self, n: int) -> int:
# return a num btw 1,..,n
low = 1
high = n
while True:
mid = low + (high - low) // 2
myGuess = guess(mid)
if myGuess == 1:
low = mid + 1
elif myGuess ==... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zoom/components.py | {
"start": 1065,
"end": 3500
} | class ____(NoAuth):
config: Config
account_id: Union[InterpolatedString, str]
client_id: Union[InterpolatedString, str]
client_secret: Union[InterpolatedString, str]
authorization_endpoint: Union[InterpolatedString, str]
_instance = None
_generate_token_time = 0
_access_token = None
... | ServerToServerOauthAuthenticator |
python | PyCQA__pylint | tests/functional/a/assigning/assigning_non_slot.py | {
"start": 2666,
"end": 3053
} | class ____:
__slots__ = ['_err']
data_descriptor = DataDescriptor('_err')
non_data_descriptor = NonDataDescriptor()
missing_descriptor = Unknown()
def dont_emit_for_descriptors():
inst = SlotsWithDescriptor()
# This should not emit, because attr is
# a data descriptor
inst.data_descrip... | SlotsWithDescriptor |
python | numpy__numpy | benchmarks/benchmarks/bench_function_base.py | {
"start": 8165,
"end": 10416
} | class ____(Benchmark):
def setup(self):
self.d = np.arange(20000)
self.d_o = self.d.astype(object)
self.e = self.d.copy()
self.e_o = self.d_o.copy()
self.cond = (self.d > 5000)
size = 1024 * 1024 // 8
rnd_array = np.random.rand(size)
self.rand_cond_01 ... | Where |
python | numpy__numpy | numpy/polynomial/tests/test_symbol.py | {
"start": 3437,
"end": 3735
} | class ____:
p = poly.Polynomial([1, 2, 3], symbol='x')
def test_eq(self):
other = poly.Polynomial([1, 2, 3], symbol='x')
assert_(self.p == other)
def test_neq(self):
other = poly.Polynomial([1, 2, 3], symbol='y')
assert_(not self.p == other)
| TestEquality |
python | davidhalter__jedi | jedi/plugins/stdlib.py | {
"start": 12865,
"end": 13508
} | class ____(TreeArgumentsWrapper):
def __init__(self, klass, arguments):
super().__init__(arguments)
self._class = klass
def unpack(self, func=None):
yield None, LazyKnownValue(self._class)
for values in self._wrapped_arguments.unpack(func):
yield values
@argument_c... | ClassMethodArguments |
python | google__jax | tests/sparse_test.py | {
"start": 46718,
"end": 48937
} | class ____(sptu.SparseTestCase):
@jtu.sample_product(
[
dict(n_batch=n_batch, n_dense=n_dense, expected_nse=expected_nse)
for n_batch, n_dense, expected_nse in [
(0, 0, 4),
(1, 0, 2),
(0, 1, 2),
(2, 0, 1),
(1, 1, 1),
... | SparseUtilTest |
python | google__pytype | pytype/tools/xref/indexer.py | {
"start": 8132,
"end": 8291
} | class ____:
"""A link between a function def and the defs of its params."""
def_id: str
param_id: str
position: int
@dataclasses.dataclass
| FunctionParam |
python | openai__openai-python | src/openai/lib/streaming/chat/_events.py | {
"start": 829,
"end": 937
} | class ____(BaseModel):
type: Literal["refusal.delta"]
delta: str
snapshot: str
| RefusalDeltaEvent |
python | ansible__ansible | lib/ansible/playbook/block.py | {
"start": 1286,
"end": 14383
} | class ____(Base, Conditional, CollectionSearch, Taggable, Notifiable, Delegatable):
# main block fields containing the task lists
block = NonInheritableFieldAttribute(isa='list', default=list)
rescue = NonInheritableFieldAttribute(isa='list', default=list)
always = NonInheritableFieldAttribute(isa='lis... | Block |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_data_forwarding_details.py | {
"start": 366,
"end": 982
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-forwarding-details"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def get_response(self, *args, **kwargs):
"""
Override get_response to always add the required feature flag.
"""
... | DataForwardingDetailsEndpointTest |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_range.py | {
"start": 1108,
"end": 26269
} | class ____(__TestCase):
def assert_iterators_equal(self, xs, ys, test_id, limit=None):
# check that an iterator xs matches the expected results ys,
# up to a given limit.
if limit is not None:
xs = itertools.islice(xs, limit)
ys = itertools.islice(ys, limit)
s... | RangeTest |
python | pennersr__django-allauth | allauth/usersessions/views.py | {
"start": 577,
"end": 1666
} | class ____(FormView):
template_name = (
"usersessions/usersession_list." + account_settings.TEMPLATE_EXTENSION
)
form_class = ManageUserSessionsForm
success_url = reverse_lazy("usersessions_list")
def get_context_data(self, **kwargs):
ret = super().get_context_data(**kwargs)
... | ListUserSessionsView |
python | astropy__astropy | astropy/io/votable/tree.py | {
"start": 10959,
"end": 11625
} | class ____:
_utype_in_v1_2 = False
@property
def utype(self):
"""The usage-specific or `unique type`_ of the element."""
return self._utype
@utype.setter
def utype(self, utype):
if (
self._utype_in_v1_2
and utype is not None
and not self.... | _UtypeProperty |
python | getsentry__sentry | tests/sentry/db/test_transactions.py | {
"start": 5165,
"end": 5921
} | class ____(CaseMixin):
@no_silo_test
@django_db_all
def test_in_test_assert_no_transaction(self) -> None:
super().test_in_test_assert_no_transaction()
@no_silo_test
@django_db_all
def test_transaction_on_commit(self) -> None:
super().test_transaction_on_commit()
@no_silo_te... | TestPytestDjangoDbAll |
python | pypa__setuptools | setuptools/_distutils/tests/test_modified.py | {
"start": 251,
"end": 4221
} | class ____(support.TempdirManager):
def test_newer(self):
tmpdir = self.mkdtemp()
new_file = os.path.join(tmpdir, 'new')
old_file = os.path.abspath(__file__)
# Raise DistutilsFileError if 'new_file' does not exist.
with pytest.raises(DistutilsFileError):
newer(ne... | TestDepUtil |
python | joke2k__faker | faker/providers/date_time/cs_CZ/__init__.py | {
"start": 46,
"end": 766
} | class ____(DateTimeProvider):
DAY_NAMES = {
"0": "nedΔle",
"1": "pondΔlΓ",
"2": "ΓΊterΓ½",
"3": "stΕeda",
"4": "Δtvrtek",
"5": "pΓ‘tek",
"6": "sobota",
}
MONTH_NAMES = {
"01": "leden",
"02": "ΓΊnor",
"03": "bΕezen",
"04": "... | Provider |
python | pdm-project__pdm | src/pdm/cli/commands/self_cmd.py | {
"start": 3976,
"end": 5079
} | class ____(BaseCommand):
"""Install packages to the PDM's environment"""
arguments = (verbose_option,)
name = "add"
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--pip-args",
help="Arguments that will be passed to pip install",
... | AddCommand |
python | numba__numba | numba/core/types/common.py | {
"start": 532,
"end": 783
} | class ____(IteratorType):
def __init__(self, name, yield_type):
self._yield_type = yield_type
super(SimpleIteratorType, self).__init__(name)
@property
def yield_type(self):
return self._yield_type
| SimpleIteratorType |
python | pytorch__pytorch | torch/_inductor/remote_cache.py | {
"start": 2725,
"end": 2971
} | class ____(RemoteCacheSerde[JsonDataTy, bytes]):
def encode(self, data: JsonDataTy) -> bytes:
return bytes(json.dumps(data), "ascii")
def decode(self, data: bytes) -> JsonDataTy:
return json.loads(data)
| RemoteCacheJsonSerde |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-openai/llama_index/voice_agents/openai/types.py | {
"start": 802,
"end": 884
} | class ____(BaseVoiceAgentEvent):
call_id: str
output: str
| FunctionResultItem |
python | google__jax | jax/experimental/sparse/util.py | {
"start": 1090,
"end": 1181
} | class ____(SparseEfficiencyWarning):
pass
Shape = tuple[int, ...]
| CuSparseEfficiencyWarning |
python | ray-project__ray | python/ray/tests/test_placement_group_4.py | {
"start": 765,
"end": 14396
} | class ____(RuntimeEnvPlugin):
name = MOCK_WORKER_STARTUP_SLOWLY_PLUGIN_NAME
def validate(runtime_env_dict: dict) -> str:
return "success"
@staticmethod
def create(uri: str, runtime_env_dict: dict, ctx: RuntimeEnvContext) -> float:
time.sleep(60)
return 0
def test_remove_plac... | MockWorkerStartupSlowlyPlugin |
python | ray-project__ray | python/ray/_private/parameter.py | {
"start": 310,
"end": 22122
} | class ____:
"""A class used to store the parameters used by Ray.
Attributes:
redis_address: The address of the Redis server to connect to. If
this address is not provided, then this command will start Redis, a
raylet, a plasma store, a plasma manager, and some workers.
... | RayParams |
python | PrefectHQ__prefect | src/prefect/events/actions.py | {
"start": 7298,
"end": 8458
} | class ____(Action):
"""Base class for Actions that operate on Automations and need to infer them from
events"""
source: Literal["selected", "inferred"] = Field(
"selected",
description=(
"Whether this Action applies to a specific selected "
"automation (given by `aut... | AutomationAction |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_connector/file_path_data_connector.py | {
"start": 1611,
"end": 24065
} | class ____(DataConnector):
"""The base class for Data Connectors designed to access filesystem-like data.
This can include traditional, disk-based filesystems or object stores such as S3, GCS, or ABS.
See the `DataConnector` base class for more information on the role of Data Connectors.
Note that `F... | FilePathDataConnector |
python | doocs__leetcode | solution/0300-0399/0309.Best Time to Buy and Sell Stock with Cooldown/Solution.py | {
"start": 0,
"end": 414
} | class ____:
def maxProfit(self, prices: List[int]) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= len(prices):
return 0
ans = dfs(i + 1, j)
if j:
ans = max(ans, prices[i] + dfs(i + 2, 0))
else:
an... | Solution |
python | marshmallow-code__marshmallow | tests/test_options.py | {
"start": 4356,
"end": 4752
} | class ____:
class ManySchema(Schema):
foo = fields.Str()
class Meta:
many = True
def test_many_by_default(self):
test = self.ManySchema()
assert test.load([{"foo": "bar"}]) == [{"foo": "bar"}]
def test_explicit_single(self):
test = self.ManySchema(many=... | TestManyOption |
python | django__django | tests/serializers/models/data.py | {
"start": 6081,
"end": 6159
} | class ____(models.Model):
data = models.UUIDField(primary_key=True)
| UUIDData |
python | django__django | tests/db_functions/text/test_upper.py | {
"start": 194,
"end": 1393
} | class ____(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.annotate(upper_name=Upper("name"))
self.assertQuerySetEqual(
authors.order_by("name"),
[
... | UpperTests |
python | pandas-dev__pandas | pandas/tests/arrays/sparse/test_indexing.py | {
"start": 3892,
"end": 4281
} | class ____:
def test_set_item(self, arr_data):
arr = SparseArray(arr_data).copy()
def setitem():
arr[5] = 3
def setslice():
arr[1:5] = 2
with pytest.raises(TypeError, match="assignment via setitem"):
setitem()
with pytest.raises(TypeErr... | TestSetitem |
python | huggingface__transformers | examples/modular-transformers/modular_multimodal2.py | {
"start": 757,
"end": 817
} | class ____(CLIPAttention):
pass
| Multimodal2VisionAttention |
python | openai__openai-python | src/openai/resources/beta/realtime/transcription_sessions.py | {
"start": 13811,
"end": 14124
} | class ____:
def __init__(self, transcription_sessions: AsyncTranscriptionSessions) -> None:
self._transcription_sessions = transcription_sessions
self.create = async_to_streamed_response_wrapper(
transcription_sessions.create,
)
| AsyncTranscriptionSessionsWithStreamingResponse |
python | getlogbook__logbook | src/logbook/base.py | {
"start": 8108,
"end": 9692
} | class ____(StackedObject):
"""A nested setup can be used to configure multiple handlers
and processors at once.
"""
def __init__(self, objects=None):
self.objects = list(objects or ())
def push_application(self):
for obj in self.objects:
obj.push_application()
def ... | NestedSetup |
python | apache__airflow | providers/teradata/src/airflow/providers/teradata/hooks/tpt.py | {
"start": 1608,
"end": 11646
} | class ____(TtuHook):
"""
Hook for executing Teradata Parallel Transporter (TPT) operations.
This hook provides methods to execute TPT operations both locally and remotely via SSH.
It supports DDL operations using tbuild utility. It extends the `TtuHook` and integrates
with Airflow's SSHHook for rem... | TptHook |
python | getsentry__sentry | src/sentry/rules/actions/integrations/base.py | {
"start": 746,
"end": 5768
} | class ____(EventAction, abc.ABC):
"""Intermediate abstract class to help DRY some event actions code."""
@property
@abc.abstractmethod
def prompt(self) -> str:
pass
@property
@abc.abstractmethod
def provider(self) -> str:
pass
@property
@abc.abstractmethod
def ... | IntegrationEventAction |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 24853,
"end": 25350
} | class ____(StructModel):
def __init__(self, dmm, fe_type):
payload_type = types.ListPayload(fe_type.container)
members = [
# The meminfo data points to a ListPayload (shared with the
# original list object)
('meminfo', types.MemInfoPointer(payload_type)),
... | ListIterModel |
python | celery__celery | t/unit/app/test_amqp.py | {
"start": 4331,
"end": 5516
} | class ____:
@pytest.mark.parametrize('default_queue_type', ['classic', 'quorum'])
@pytest.mark.parametrize('name,exchange,rkey', [
('default', None, None),
('default', 'exchange', None),
('default', 'exchange', 'routing_key'),
('default', None, 'routing_key'),
])
def tes... | test_default_queues |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/custom_job.py | {
"start": 2229,
"end": 9856
} | class ____(GoogleCloudBaseOperator):
"""The base class for operators that launch Custom jobs on VertexAI."""
def __init__(
self,
*,
project_id: str,
region: str,
display_name: str,
container_uri: str,
model_serving_container_image_uri: str | None = None,
... | CustomTrainingJobBaseOperator |
python | apache__airflow | airflow-e2e-tests/tests/airflow_e2e_tests/e2e_test_utils/clients.py | {
"start": 1146,
"end": 4723
} | class ____:
"""Client for interacting with the Airflow REST API."""
def __init__(self):
self.session = requests.Session()
@cached_property
def token(self):
Retry.DEFAULT_BACKOFF_MAX = 32
retry = Retry(total=10, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
... | AirflowClient |
python | plotly__plotly.py | plotly/graph_objs/parcoords/_stream.py | {
"start": 233,
"end": 3521
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "parcoords"
_path_str = "parcoords.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set t... | Stream |
python | fluentpython__example-code | 21-class-metaprog/bulkfood/model_v6.py | {
"start": 802,
"end": 1004
} | class ____(Validated):
"""a number greater than zero"""
def validate(self, instance, value):
if value <= 0:
raise ValueError('value must be > 0')
return value
| Quantity |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/model_call_limit.py | {
"start": 1693,
"end": 2715
} | class ____(Exception):
"""Exception raised when model call limits are exceeded.
This exception is raised when the configured exit behavior is `'error'` and either
the thread or run model call limit has been exceeded.
"""
def __init__(
self,
thread_count: int,
run_count: int... | ModelCallLimitExceededError |
python | tensorflow__tensorflow | tensorflow/compiler/tests/reduce_ops_test.py | {
"start": 7471,
"end": 9591
} | class ____(xla_test.XLATestCase):
def _testReduceSum(self,
expected_result,
dtype,
test_inputs,
rtol=1e-3,
atol=1e-4):
"""Tests reduce sum on a list of input arrays.
For each array in test_inputs, check ... | ReduceOpPrecisionTest |
python | realpython__materials | django-todo-list/source_code_final/todo_app/models.py | {
"start": 207,
"end": 427
} | class ____(models.Model):
title = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse("list", args=[self.id])
def __str__(self):
return self.title
| ToDoList |
python | mlflow__mlflow | mlflow/llama_index/pyfunc_wrapper.py | {
"start": 3379,
"end": 5259
} | class ____(_LlamaIndexModelWrapperBase):
@property
def engine_type(self):
return CHAT_ENGINE_NAME
def _predict_single(self, *args, **kwargs) -> str:
return self._llama_model.chat(*args, **kwargs).response
@staticmethod
def _convert_chat_message_history_to_chat_message_objects(
... | ChatEngineWrapper |
python | numba__numba | numba/core/types/scalars.py | {
"start": 2987,
"end": 3505
} | class ____(Number):
def __init__(self, *args, **kws):
super(Float, self).__init__(*args, **kws)
# Determine bitwidth
assert self.name.startswith('float')
bitwidth = int(self.name[5:])
self.bitwidth = bitwidth
def cast_python_value(self, value):
return getattr(np,... | Float |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 86876,
"end": 87182
} | class ____(sgqlc.types.Enum):
"""Properties by which repository invitation connections can be
ordered.
Enumeration Choices:
* `CREATED_AT`: Order repository invitations by creation time
"""
__schema__ = github_schema
__choices__ = ("CREATED_AT",)
| RepositoryInvitationOrderField |
python | pandas-dev__pandas | pandas/tests/scalar/period/test_asfreq.py | {
"start": 266,
"end": 38135
} | class ____:
"""Test frequency conversion of date objects"""
@pytest.mark.filterwarnings("ignore:Period with BDay:FutureWarning")
@pytest.mark.parametrize("freq", ["Y", "Q", "M", "W", "B", "D"])
def test_asfreq_near_zero(self, freq):
# GH#19643, GH#19650
per = Period("0001-01-01", freq=f... | TestFreqConversion |
python | jazzband__django-formtools | tests/wizard/namedwizardtests/forms.py | {
"start": 816,
"end": 935
} | class ____(forms.Form):
random_crap = forms.CharField(max_length=100)
Page4 = formset_factory(Page3, extra=2)
| Page3 |
python | dask__dask | dask/tests/test_context.py | {
"start": 677,
"end": 1176
} | class ____:
@globalmethod(key="f")
def f(): # type: ignore[misc]
return 1
g = globalmethod(foo, key="g", falsey=bar)
def test_globalmethod():
x = Foo()
assert x.f() == 1
with dask.config.set(f=lambda: 2):
assert x.f() == 2
with dask.config.set(f=foo):
assert x.... | Foo |
python | readthedocs__readthedocs.org | readthedocs/api/v3/mixins.py | {
"start": 1565,
"end": 4506
} | class ____:
# Lookup names defined on ``readthedocs/api/v3/urls.py`` when defining the
# mapping between URLs and views through the router.
PROJECT_LOOKUP_NAMES = [
"project__slug",
"projects__slug",
"parent__slug",
"superprojects__parent__slug",
"main_language_projec... | NestedParentObjectMixin |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-faiss/tests/test_vector_stores_faiss.py | {
"start": 2230,
"end": 10450
} | class ____:
def test_add_documents(self, node_embeddings: List[TextNode]) -> None:
"""Test adding documents to faiss map vector store."""
vector_store = FaissMapVectorStore(faiss_index=get_map_index())
# Add nodes to the faiss map vector
vector_store.add(node_embeddings)
qu... | TestFaissMapVectorStore |
python | explosion__spaCy | spacy/lang/is/__init__.py | {
"start": 153,
"end": 255
} | class ____(Language):
lang = "is"
Defaults = IcelandicDefaults
__all__ = ["Icelandic"]
| Icelandic |
python | getsentry__sentry | src/sentry/api/endpoints/organization_on_demand_metrics_estimation_stats.py | {
"start": 1828,
"end": 9950
} | class ____(OrganizationEventsV2EndpointBase):
"""Gets the estimated volume of an organization's metric events."""
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.TELEMETRY_EXPERIENCE
def get(self, request: Request, organization: Organization) -> Response:
mea... | OrganizationOnDemandMetricsEstimationStatsEndpoint |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 792,
"end": 883
} | class ____(A1):
def m0(self, x):
self.m1(x)
def m1(self, x):
pass
| B1 |
python | huggingface__transformers | src/transformers/models/rt_detr/modeling_rt_detr_resnet.py | {
"start": 2334,
"end": 4060
} | class ____(nn.Module):
"""
ResNet Embeddings (stem) composed of a deep aggressive convolution.
"""
def __init__(self, config: RTDetrResNetConfig):
super().__init__()
self.embedder = nn.Sequential(
*[
RTDetrResNetConvLayer(
config.num_chann... | RTDetrResNetEmbeddings |
python | getsentry__sentry | src/sentry/integrations/discord/message_builder/base/component/base.py | {
"start": 129,
"end": 602
} | class ____:
"""
Represents an abstract Discord message component.
Child classes should override the constructor with necessary fields for
the component type.
https://discord.com/developers/docs/interactions/message-components#component-object
"""
def __init__(self, type: int) -> None:
... | DiscordMessageComponent |
python | realpython__materials | queue/src/thread_safe_queues.py | {
"start": 2266,
"end": 2478
} | class ____(Worker):
def run(self):
while True:
self.product = self.buffer.get()
self.simulate_work()
self.buffer.task_done()
self.simulate_idle()
| Consumer |
python | sqlalchemy__sqlalchemy | test/engine/test_pool.py | {
"start": 67885,
"end": 68314
} | class ____(PoolTestBase):
def test_reconnect(self):
dbapi = MockDBAPI()
p = pool.NullPool(creator=lambda: dbapi.connect("foo.db"))
c1 = p.connect()
c1.close()
c1 = None
c1 = p.connect()
c1.invalidate()
c1 = None
c1 = p.connect()
dbap... | NullPoolTest |
python | keras-team__keras | keras/src/layers/rnn/gru_test.py | {
"start": 169,
"end": 11929
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_basics(self):
self.run_layer_test(
layers.GRU,
init_kwargs={"units": 3, "dropout": 0.5},
input_shape=(3, 2, 4),
call_kwargs={"training": True},
expected_output_shape... | GRUTest |
python | doocs__leetcode | solution/3500-3599/3579.Minimum Steps to Convert String with Operations/Solution.py | {
"start": 0,
"end": 803
} | class ____:
def minOperations(self, word1: str, word2: str) -> int:
def calc(l: int, r: int, rev: bool) -> int:
cnt = Counter()
res = 0
for i in range(l, r + 1):
j = r - (i - l) if rev else i
a, b = word1[j], word2[i]
if a !... | Solution |
python | protocolbuffers__protobuf | python/google/protobuf/internal/generator_test.py | {
"start": 15026,
"end": 16606
} | class ____(unittest.TestCase):
"""Checks that messages, enums and files are correctly registered."""
def testGetSymbol(self):
self.assertEqual(
unittest_pb2.TestAllTypes, symbol_database.Default().GetSymbol(
'proto2_unittest.TestAllTypes'))
self.assertEqual(
unittest_pb2.TestAll... | SymbolDatabaseRegistrationTest |
python | wandb__wandb | wandb/automations/_generated/integrations_by_entity.py | {
"start": 461,
"end": 575
} | class ____(GQLResult):
integrations: Optional[IntegrationsByEntityEntityIntegrations]
| IntegrationsByEntityEntity |
python | pandas-dev__pandas | asv_bench/benchmarks/index_object.py | {
"start": 5818,
"end": 6756
} | class ____:
# GH 24813
params = [10**3, 10**5]
def setup(self, N):
left = np.append(np.arange(N), np.array(0))
right = np.append(np.arange(1, N + 1), np.array(1))
self.intv = IntervalIndex.from_arrays(left, right)
self.intv._engine
self.intv2 = IntervalIndex.from_ar... | IntervalIndexMethod |
python | openai__openai-python | src/openai/types/realtime/realtime_mcp_protocol_error.py | {
"start": 201,
"end": 313
} | class ____(BaseModel):
code: int
message: str
type: Literal["protocol_error"]
| RealtimeMcpProtocolError |
python | pytorch__pytorch | torch/_dynamo/metrics_context.py | {
"start": 7390,
"end": 8889
} | class ____:
def __init__(self, on_exit: OnExitType):
"""
Similar to MetricsContext, but used to gather the runtime metrics that are
decoupled from compilation, where there's not a natural place to insert a
context manager.
"""
self._on_exit = on_exit
self._met... | RuntimeMetricsContext |
python | tensorflow__tensorflow | third_party/xla/xla/python/xla_client.py | {
"start": 9747,
"end": 14136
} | class ____:
"""Python representation of a xla.ConvolutionDimensionNumbers protobuf."""
__slots__ = (
'input_batch_dimension',
'input_feature_dimension',
'input_spatial_dimensions',
'kernel_input_feature_dimension',
'kernel_output_feature_dimension',
'kernel_spatial_dimensions',
... | ConvolutionDimensionNumbers |
python | doocs__leetcode | solution/2300-2399/2316.Count Unreachable Pairs of Nodes in an Undirected Graph/Solution.py | {
"start": 0,
"end": 512
} | class ____:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
def dfs(i: int) -> int:
if vis[i]:
return 0
vis[i] = True
return 1 + sum(dfs(j) for j in g[i])
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b... | Solution |
python | pypa__pip | src/pip/_vendor/tomli/_parser.py | {
"start": 2556,
"end": 7135
} | class ____(ValueError):
"""An error raised if a document is not valid TOML.
Adds the following attributes to ValueError:
msg: The unformatted error message
doc: The TOML document being parsed
pos: The index of doc where parsing failed
lineno: The line corresponding to pos
colno: The column ... | TOMLDecodeError |
python | django-compressor__django-compressor | compressor/exceptions.py | {
"start": 232,
"end": 339
} | class ____(Exception):
"""
This exception is raised when a filter fails
"""
pass
| FilterError |
python | wandb__wandb | wandb/sdk/launch/inputs/internal.py | {
"start": 1586,
"end": 2089
} | class ____:
"""Arguments for the publish_job_input of Interface."""
def __init__(
self,
include: Optional[List[str]] = None,
exclude: Optional[List[str]] = None,
schema: Optional[dict] = None,
file_path: Optional[str] = None,
run_config: Optional[bool] = None,
... | JobInputArguments |
python | facebookresearch__faiss | benchs/distributed_ondisk/combined_index.py | {
"start": 4914,
"end": 6376
} | class ____(CombinedIndex):
""" loads a CombinedIndex with the data from the big photodna index """
def __init__(self):
# set some paths
workdir = "/checkpoint/matthijs/ondisk_distributed/"
# empty index with the proper quantizer
indexfname = workdir + 'trained.faissindex'
... | CombinedIndexDeep1B |
python | Textualize__textual | examples/five_by_five.py | {
"start": 3320,
"end": 4028
} | class ____(Button):
"""Individual playable cell in the game."""
@staticmethod
def at(row: int, col: int) -> str:
"""Get the ID of the cell at the given location.
Args:
row (int): The row of the cell.
col (int): The column of the cell.
Returns:
s... | GameCell |
python | jazzband__django-oauth-toolkit | tests/test_oidc_views.py | {
"start": 7160,
"end": 31173
} | class ____(TestCase):
def test_get_jwks_info(self):
self.oauth2_settings.OIDC_RSA_PRIVATE_KEYS_INACTIVE = []
expected_response = {
"keys": [
{
"alg": "RS256",
"use": "sig",
"kid": "s4a1o8mFEd1tATAIH96caMlu4hOxzBU... | TestJwksInfoView |
python | pyca__cryptography | src/cryptography/hazmat/_oid.py | {
"start": 7938,
"end": 8758
} | class ____:
SHA1 = ObjectIdentifier("1.3.14.3.2.26")
SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.2.4")
SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.2.1")
SHA384 = ObjectIdentifier("2.16.840.1.101.3.4.2.2")
SHA512 = ObjectIdentifier("2.16.840.1.101.3.4.2.3")
SHA3_224 = ObjectIdentifier("1.3.6.... | HashAlgorithmOID |
python | bokeh__bokeh | src/bokeh/util/dataclasses.py | {
"start": 1569,
"end": 2552
} | class ____:
def __repr__(self) -> str:
return "Unspecified"
Unspecified = _UnspecifiedType()
_T = TypeVar("_T")
NotRequired: TypeAlias = _UnspecifiedType | _T
def entries(obj: Any) -> Iterable[tuple[str, Any]]:
""" Iterate over a dataclass' fields and their values. """
if is_dataclass(obj):
... | _UnspecifiedType |
python | davidhalter__jedi | test/completion/docstring.py | {
"start": 2669,
"end": 3005
} | class ____(object):
def __init__(self):
self.teststr = ""
"""
# jedi issue #210
"""
def test(self):
#? ['teststr']
self.teststr
# -----------------
# statement docstrings
# -----------------
d = ''
""" bsdf """
#? str()
d.upper()
# -----------------
# class docstrings
# ---... | Test |
python | astropy__astropy | astropy/io/votable/converters.py | {
"start": 21441,
"end": 24852
} | class ____(Numeric):
"""
The base class for floating-point datatypes.
"""
default = np.nan
def __init__(self, field, config=None, pos=None):
if config is None:
config = {}
Numeric.__init__(self, field, config, pos)
precision = field.precision
width = f... | FloatingPoint |
python | google__jax | tests/lax_numpy_operators_test.py | {
"start": 22182,
"end": 23575
} | class ____:
pass
for rec in JAX_OPERATOR_OVERLOADS + JAX_RIGHT_OPERATOR_OVERLOADS:
if rec.nargs == 2:
setattr(_OverrideNothing, rec.name, lambda self, other: NotImplemented)
def _dtypes_are_compatible_for_bitwise_ops(args):
if len(args) <= 1:
return True
is_signed = lambda dtype: jnp.issubdtype(dtype... | _OverrideNothing |
python | spyder-ide__spyder | spyder/utils/qthelpers.py | {
"start": 18066,
"end": 19427
} | class ____(QObject):
"""
Object that keep references to non-modal dialog boxes for another QObject,
typically a QMainWindow or any kind of QWidget
"""
def __init__(self):
QObject.__init__(self)
self.dialogs = {}
def show(self, dialog):
"""Generic method to show a non-mo... | DialogManager |
python | pandas-dev__pandas | scripts/check_for_inconsistent_pandas_namespace.py | {
"start": 1175,
"end": 4349
} | class ____(ast.NodeVisitor):
def __init__(self) -> None:
self.pandas_namespace: MutableMapping[OffsetWithNamespace, str] = {}
self.imported_from_pandas: set[str] = set()
def visit_Attribute(self, node: ast.Attribute) -> None:
if isinstance(node.value, ast.Name) and node.value.id in {"pa... | Visitor |
python | imageio__imageio | tests/test_core.py | {
"start": 658,
"end": 849
} | class ____:
"""A dummy plugin to test plugin resultion and dynamic loading"""
def __init__(self, request):
raise InitializationError("Can not read anything")
| UselessDummyPlugin |
python | coleifer__peewee | tests/sql.py | {
"start": 54580,
"end": 72000
} | class ____(BaseTestCase):
def test_partition_unordered(self):
partition = [Register.category]
query = (Register
.select(
Register.category,
Register.value,
fn.AVG(Register.value).over(partition_by=partition))
... | TestWindowFunctions |
python | getsentry__sentry | src/sentry/audit_log/events.py | {
"start": 3398,
"end": 3831
} | class ____(AuditLogEvent):
def __init__(self) -> None:
super().__init__(event_id=8, name="MEMBER_PENDING", api_name="member.pending")
def render(self, audit_log_entry: AuditLogEntry) -> str:
user_display_name = _get_member_display(
audit_log_entry.data.get("email"), audit_log_entry.... | MemberPendingAuditLogEvent |
python | kamyu104__LeetCode-Solutions | Python/find-the-closest-marked-node.py | {
"start": 227,
"end": 1193
} | class ____(object):
def minimumDistance(self, n, edges, s, marked):
"""
:type n: int
:type edges: List[List[int]]
:type s: int
:type marked: List[int]
:rtype: int
"""
def dijkstra(start):
best = [float("inf")]*len(adj)
best[star... | Solution |
python | PrefectHQ__prefect | src/prefect/cli/transfer/_migratable_resources/concurrency_limits.py | {
"start": 538,
"end": 3032
} | class ____(
MigratableResource[GlobalConcurrencyLimitResponse]
):
_instances: dict[uuid.UUID, Self] = {}
def __init__(self, global_concurrency_limit: GlobalConcurrencyLimitResponse):
self.source_global_concurrency_limit = global_concurrency_limit
self.destination_global_concurrency_limit: (... | MigratableGlobalConcurrencyLimit |
python | run-llama__llama_index | llama-dev/llama_dev/utils.py | {
"start": 232,
"end": 7278
} | class ____(str, Enum):
MAJOR = "major"
MINOR = "minor"
PATCH = "patch"
def bump_version(current_version: str, bump_type: BumpType) -> str:
"""Bump a version string according to semver rules."""
v = Version(current_version)
# Parse the version components
release = v.release
major = rel... | BumpType |
python | pypa__setuptools | setuptools/_vendor/zipp/__init__.py | {
"start": 6768,
"end": 13380
} | class ____:
"""
A :class:`importlib.resources.abc.Traversable` interface for zip files.
Implements many of the features users enjoy from
:class:`pathlib.Path`.
Consider a zip file with this structure::
.
βββ a.txt
βββ b
βββ c.txt
βββ d
... | Path |
python | kamyu104__LeetCode-Solutions | Python/transform-array-to-all-equal-elements.py | {
"start": 38,
"end": 637
} | class ____(object):
def canMakeEqual(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
def check(target):
cnt = 0
sign = 1
for i in xrange(len(nums)):
if nums[i]*sign == target:
... | Solution |
python | python__mypy | mypy/build.py | {
"start": 19280,
"end": 72405
} | class ____:
"""This class holds shared state for building a mypy program.
It is used to coordinate parsing, import processing, semantic
analysis and type checking. The actual build steps are carried
out by dispatch().
Attributes:
data_dir: Mypy data directory (contains stubs)
s... | BuildManager |
python | Textualize__textual | docs/examples/widgets/tree.py | {
"start": 78,
"end": 460
} | class ____(App):
def compose(self) -> ComposeResult:
tree: Tree[str] = Tree("Dune")
tree.root.expand()
characters = tree.root.add("Characters", expand=True)
characters.add_leaf("Paul")
characters.add_leaf("Jessica")
characters.add_leaf("Chani")
yield tree
if... | TreeApp |
python | huggingface__transformers | src/transformers/models/glm4v/image_processing_glm4v.py | {
"start": 3249,
"end": 24322
} | class ____(BaseImageProcessor):
r"""
Constructs a GLM-4V image processor that dynamically resizes images based on the original images.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions.
size (`Dict[str, int]` *opti... | Glm4vImageProcessor |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 34081,
"end": 34248
} | class ____(BoringModel):
def training_step(self, batch, batch_idx):
if batch_idx == 1:
raise RuntimeError("Trouble!")
| TroubledModelInTrainingStep |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.