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 | django__django | django/contrib/redirects/migrations/0002_alter_redirect_new_path_help_text.py | {
"start": 43,
"end": 631
} | class ____(migrations.Migration):
dependencies = [
("redirects", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="redirect",
name="new_path",
field=models.CharField(
blank=True,
help_text=(
... | Migration |
python | catalyst-team__catalyst | examples/recsys/macridvae.py | {
"start": 3862,
"end": 6748
} | class ____(dl.Runner):
def on_loader_start(self, runner):
super().on_loader_start(runner)
self.meters = {
key: metrics.AdditiveMetric(compute_on_call=False)
for key in ["loss_ae", "loss_kld", "loss"]
}
def handle_batch(self, batch):
x = batch["inputs"]
... | RecSysRunner |
python | django__django | tests/template_tests/test_callables.py | {
"start": 123,
"end": 6218
} | class ____(TestCase):
@classmethod
def setUpClass(cls):
cls.engine = Engine()
super().setUpClass()
def test_callable(self):
class Doodad:
def __init__(self, value):
self.num_calls = 0
self.value = value
def __call__(self):
... | CallableVariablesTests |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/location.py | {
"start": 47,
"end": 746
} | class ____(object):
__slots__ = 'line', 'column'
def __init__(self, line, column):
self.line = line
self.column = column
def __repr__(self):
return '<SourceLocation line={} column={}>'.format(self.line, self.column)
def __eq__(self, other):
return (
isinsta... | SourceLocation |
python | huggingface__transformers | src/transformers/models/hubert/modeling_hubert.py | {
"start": 4547,
"end": 5294
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_id=0):
super().__init__()
self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
self.out_conv_dim = config.conv_dim[layer_id]
self.conv = nn.Conv1d(
self.in_conv_dim,
s... | HubertNoLayerNormConvLayer |
python | getsentry__sentry | src/sentry/releases/endpoints/organization_release_file_details.py | {
"start": 553,
"end": 694
} | class ____(serializers.Serializer):
name = serializers.CharField(max_length=200, required=True)
@region_silo_endpoint
| ReleaseFileSerializer |
python | getsentry__sentry | src/social_auth/backends/asana.py | {
"start": 950,
"end": 2448
} | class ____(BaseOAuth2):
"""Asana OAuth authentication mechanism"""
AUTHORIZATION_URL = ASANA_AUTHORIZATION_URL
ACCESS_TOKEN_URL = ASANA_TOKEN_EXCHANGE_URL
AUTH_BACKEND = AsanaBackend
SETTINGS_KEY_NAME = "ASANA_CLIENT_ID"
SETTINGS_SECRET_NAME = "ASANA_CLIENT_SECRET"
REDIRECT_STATE = False
... | AsanaAuth |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/embedding_ops_test.py | {
"start": 53879,
"end": 55264
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testCint32Cpu(self):
with self.session(use_gpu=False):
indices = [
ops.convert_to_tensor([0, 1, 4, 6]),
ops.convert_to_tensor([2, 3, 5])
]
values = [
ops.convert_to_tensor([12, 23, 34, 45]),
op... | ParallelDynamicStitchOpTest |
python | allegroai__clearml | clearml/automation/trigger.py | {
"start": 477,
"end": 3379
} | class ____(BaseScheduleJob):
_only_fields = {"id", "name", "last_update", "last_change"}
_update_field = None
_change_field = None
project = attrib(default=None, type=str)
match_name = attrib(default=None, type=str)
tags = attrib(default=None, type=list)
required_tags = attrib(default=None,... | BaseTrigger |
python | google__flatbuffers | python/flatbuffers/flexbuffers.py | {
"start": 14731,
"end": 15727
} | class ____(Vector):
"""Data accessor for the encoded map bytes."""
@staticmethod
def CompareKeys(a, b):
if isinstance(a, Ref):
a = a.AsKeyBytes
if isinstance(b, Ref):
b = b.AsKeyBytes
return a < b
def __getitem__(self, key):
if isinstance(key, int):
return super().__getitem__... | Map |
python | dagster-io__dagster | python_modules/dagster/dagster/components/core/component_tree.py | {
"start": 1619,
"end": 1727
} | class ____(Exception):
pass
@record(
checked=False, # cant handle ModuleType
)
| ComponentTreeException |
python | pytorch__pytorch | torch/_inductor/fuzzer.py | {
"start": 19862,
"end": 37524
} | class ____:
"""
This tool makes it easy to search through config state-space with a minimal reproduction or test, either for
debugging or just bug hunting.
It has two entry points:
- bisect, which randomly flips configs and tries to find the minimal reproduction upon failure.
- fuzz_n_tuple,... | ConfigFuzzer |
python | getsentry__sentry | tests/sentry/core/endpoints/scim/test_scim_user_details.py | {
"start": 1162,
"end": 1927
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def test_cant_use_scim(self) -> None:
url = reverse("sentry-api-0-organization-scim-member-index", args=[self.organization.slug])
response = self.client.get(url)
assert respon... | SCIMMemberTestsPermissions |
python | pyinstaller__pyinstaller | PyInstaller/exceptions.py | {
"start": 1140,
"end": 1448
} | class ____(SystemExit):
def __init__(self, message):
super().__init__(
f"ERROR: Bytecode encryption was removed in PyInstaller v6.0. {message}"
" For the rationale and alternatives see https://github.com/pyinstaller/pyinstaller/pull/6999"
)
| RemovedCipherFeatureError |
python | gevent__gevent | src/greentest/3.11/test_signal.py | {
"start": 24306,
"end": 27750
} | class ____(unittest.TestCase):
def readpipe_interrupted(self, interrupt):
"""Perform a read during which a signal will arrive. Return True if the
read is interrupted by the signal and raises an exception. Return False
if it returns normally.
"""
# use a subprocess to have ... | SiginterruptTest |
python | pytorch__pytorch | torch/_inductor/codegen/cpp.py | {
"start": 229420,
"end": 234693
} | class ____:
"""
A loop-nest-like structure. It is built with the `build` method
as a loop nest and then will perform loop-tiling at some depth.
A typical case is for vectorization, where we typically do loop-tiling
at the innermost loop level. A more complicated case is when we do
2D tiling at ... | LoopNest |
python | allegroai__clearml | clearml/utilities/gpu/gpustat.py | {
"start": 4755,
"end": 24836
} | class ____(object):
global_processes = {}
_initialized = False
_device_count = None
_gpu_device_info = {}
_mig_device_info = {}
def __init__(
self,
gpu_list: List[GPUStat],
driver_version: Optional[str] = None,
driver_cuda_version: Optional[str] = None,
) -> ... | GPUStatCollection |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/foundry.py | {
"start": 2607,
"end": 2977
} | class ____(AsyncBeta):
@cached_property
@override
def messages(self) -> AsyncBetaMessages: # type: ignore[override]
"""Return beta messages resource instance with excluded unsupported endpoints."""
return AsyncBetaFoundryMessages(self._client)
# ===========================================... | AsyncBetaFoundry |
python | Textualize__textual | src/textual/demo/widgets.py | {
"start": 4076,
"end": 4954
} | class ____(containers.VerticalGroup):
"""Demonstrates DataTables."""
DEFAULT_CLASSES = "column"
DATATABLES_MD = """\
## Datatables
A fully-featured DataTable, with cell, row, and columns cursors.
Cells may be individually styled, and may include Rich renderables.
**Tip:** Focus the table and press `ctrl+... | Datatables |
python | PrefectHQ__prefect | tests/test_task_worker.py | {
"start": 4406,
"end": 6540
} | class ____:
async def test_serve_basic_sync_task(self, foo_task, mock_task_worker_start):
await serve(foo_task)
mock_task_worker_start.assert_called_once()
task_run_future = foo_task.apply_async((42,))
assert isinstance(task_run_future, PrefectDistributedFuture)
assert tas... | TestServe |
python | pdm-project__pdm | src/pdm/cli/commands/fix/__init__.py | {
"start": 310,
"end": 3197
} | class ____(BaseCommand):
"""Fix the project problems according to the latest version of PDM"""
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
parser.add_argument("problem", nargs="?", help="Fix the specific problem, or all if not given")
parser.add_argument("--dry-run", actio... | Command |
python | apache__thrift | lib/py/test/test_sslsocket.py | {
"start": 3984,
"end": 15110
} | class ____(unittest.TestCase):
def _server_socket(self, **kwargs):
return TSSLServerSocket(port=0, **kwargs)
@contextmanager
def _connectable_client(self, server, expect_failure=False, path=None, **client_kwargs):
acc = ServerAcceptor(server, expect_failure)
try:
acc.sta... | TSSLSocketTest |
python | walkccc__LeetCode | solutions/2965. Find Missing and Repeated Values/2965.py | {
"start": 0,
"end": 269
} | class ____:
def findMissingAndRepeatedValues(self, grid: list[list[int]]) -> list[int]:
count = [1] + [0] * len(grid)**2 # padding for 1-indexed
for row in grid:
for num in row:
count[num] += 1
return [count.index(2), count.index(0)]
| Solution |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-buckets-required-to-collect-rainwater-from-houses.py | {
"start": 29,
"end": 619
} | class ____(object):
def minimumBuckets(self, street):
"""
:type street: str
:rtype: int
"""
result = 0
street = list(street)
for i, c in enumerate(street):
if c != 'H' or (i and street[i-1] == 'B'):
continue
if i+1 < len... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingTypeIs1.py | {
"start": 1042,
"end": 1186
} | class ____:
pass
E = C[T] | D
def func5(x: E[T]) -> None:
if type(x) is C:
reveal_type(x, expected_text="C[T@func5]")
@final
| D |
python | PyCQA__pylint | tests/functional/ext/no_self_use/no_self_use.py | {
"start": 2569,
"end": 2804
} | class ____(ABC):
"""Don't emit no-self-use for abstract methods."""
@abstractmethod
def a(self):
pass
def b(self):
raise NotImplementedError
def c(self):
pass # pass counts as abstract
| Foo1 |
python | pennersr__django-allauth | tests/apps/account/test_signup.py | {
"start": 832,
"end": 2712
} | class ____(TestCase):
@override_settings(
ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE=True,
ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE=True,
)
def test_custom_form_field_order(self):
expected_field_order = [
"email",
"email2",
"password1",
"password2",
... | CustomSignupFormTests |
python | tiangolo__fastapi | docs_src/pydantic_v1_in_v2/tutorial004_an_py310.py | {
"start": 143,
"end": 360
} | class ____(BaseModel):
name: str
description: str | None = None
size: float
app = FastAPI()
@app.post("/items/")
async def create_item(item: Annotated[Item, Body(embed=True)]) -> Item:
return item
| Item |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/string_conversion.py | {
"start": 403,
"end": 968
} | class ____:
def __repr__(self):
return request.GET["tainted"]
def str_is_tainted():
s = StrIsTainted()
eval(str(s))
def repr_is_tainted():
r = ReprIsTainted()
eval(repr(r))
def str_falls_back_to_repr():
r = ReprIsTainted()
eval(str(r))
def implicit_str():
s = StrIsTainted... | ReprIsTainted |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/mapping/multi/base.py | {
"start": 1164,
"end": 12531
} | class ____(ABC):
@abstractmethod
def get_dimension_dependencies(
self,
upstream_partitions_def: PartitionsDefinition,
downstream_partitions_def: PartitionsDefinition,
) -> Sequence[DimensionDependency]: ...
def get_partitions_def(
self, partitions_def: PartitionsDefiniti... | BaseMultiPartitionMapping |
python | pypa__warehouse | warehouse/organizations/models.py | {
"start": 6145,
"end": 6281
} | class ____(enum.StrEnum):
GitHub = "github"
GitLab = "gitlab"
Google = "google"
ActiveState = "activestate"
| OIDCIssuerType |
python | redis__redis-py | redis/lock.py | {
"start": 282,
"end": 12760
} | class ____:
"""
A shared, distributed Lock. Using Redis for locking allows the Lock
to be shared across processes and/or machines.
It's left to the user to resolve deadlock issues and make sure
multiple clients play nicely together.
"""
lua_release = None
lua_extend = None
lua_reac... | Lock |
python | bottlepy__bottle | test/test_plugins.py | {
"start": 5538,
"end": 7526
} | class ____(tools.ServerTestBase):
def setUp(self):
super(TestPluginAPI, self).setUp()
@self.app.route('/', test='plugin.cfg')
def test(**args):
return ', '.join('%s:%s' % (k,v) for k,v in args.items())
def test_callable(self):
def plugin(func):
def wrapp... | TestPluginAPI |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 34555,
"end": 34775
} | class ____(PrimitiveModel):
def __init__(self, dmm, fe_type):
be_type = ir.IntType(64)
super(NPDatetimeModel, self).__init__(dmm, fe_type, be_type)
@register_default(types.ArrayIterator)
| NPDatetimeModel |
python | networkx__networkx | networkx/classes/tests/test_coreviews.py | {
"start": 7833,
"end": 9171
} | class ____(TestUnionAdjacency):
# nbr->key->data
def setup_method(self):
dd = {"color": "blue", "weight": 1.2}
self.kd = {7: {}, "ekey": {}, 9: {"color": 1}}
self.s = {3: self.kd, 0: {7: dd}, 1: {}, 2: {"key": {"color": 1}}}
self.p = {3: {}, 0: {3: dd}, 1: {}, 2: {1: {"span": 2}}... | TestUnionMultiInner |
python | redis__redis-py | tests/test_asyncio/test_command_policies.py | {
"start": 567,
"end": 2972
} | class ____:
async def test_resolve(self):
zcount_policy = CommandPolicies(
request_policy=RequestPolicy.DEFAULT_KEYED,
response_policy=ResponsePolicy.DEFAULT_KEYED,
)
rpoplpush_policy = CommandPolicies(
request_policy=RequestPolicy.DEFAULT_KEYED,
... | TestBasePolicyResolver |
python | astropy__astropy | astropy/coordinates/tests/test_pickle.py | {
"start": 1258,
"end": 2247
} | class ____(coord.ICRS):
default_representation = coord.PhysicsSphericalRepresentation
@pytest.mark.parametrize(
"frame",
[
coord.SkyOffsetFrame(origin=coord.ICRS(0 * u.deg, 0 * u.deg)),
coord.SkyOffsetFrame(
5 * u.deg, 10 * u.deg, origin=coord.Galactic(2 * u.deg, -3 * u.deg)
... | _CustomICRS |
python | simplejson__simplejson | simplejson/tests/test_fail.py | {
"start": 3504,
"end": 6454
} | class ____(TestCase):
def test_failures(self):
for idx, doc in enumerate(JSONDOCS):
idx = idx + 1
if idx in SKIPS:
json.loads(doc)
continue
try:
json.loads(doc)
except json.JSONDecodeError:
pass
... | TestFail |
python | tensorflow__tensorflow | tensorflow/python/ops/init_ops.py | {
"start": 17402,
"end": 20543
} | class ____(Initializer):
"""Initializer that generates tensors with a normal distribution.
Args:
mean: a python scalar or a scalar tensor. Mean of the random values to
generate.
stddev: a python scalar or a scalar tensor. Standard deviation of the random
values to generate.
seed: A Python i... | RandomNormal |
python | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 29210,
"end": 29581
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to update a block document."""
block_schema_id: Optional[UUID] = Field(
default=None, description="A block schema ID"
)
data: Dict[str, Any] = Field(
default_factory=dict, description="The block document's data"
)
... | BlockDocumentUpdate |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/instrumentation.py | {
"start": 8073,
"end": 10431
} | class ____:
"""User-defined class instrumentation extension.
:class:`.InstrumentationManager` can be subclassed in order
to change
how class instrumentation proceeds. This class exists for
the purposes of integration with other object management
frameworks which would like to entirely modify th... | InstrumentationManager |
python | django__django | tests/absolute_url_overrides/tests.py | {
"start": 153,
"end": 2139
} | class ____(SimpleTestCase):
def test_get_absolute_url(self):
"""
get_absolute_url() functions as a normal method.
"""
def get_absolute_url(o):
return "/test-a/%s/" % o.pk
TestA = self._create_model_class("TestA", get_absolute_url)
self.assertTrue(hasatt... | AbsoluteUrlOverrideTests |
python | joke2k__faker | faker/providers/automotive/ja_JP/__init__.py | {
"start": 70,
"end": 2707
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``ja_JP`` locale.
Sources (retrieved on 2025-09-15):
- https://ja.wikipedia.org/wiki/%E6%97%A5%E6%9C%AC%E3%81%AE%E3%83%8A%E3%83%B3%E3%83%90%E3%83%BC%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E4%B8%80%E8%A6%A7
- http://nplate.cloudfree.jp/m... | Provider |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_setitem.py | {
"start": 23468,
"end": 31404
} | class ____:
"""
Check each of several methods that _should_ be equivalent to `obj[key] = val`
We assume that
- obj.index is the default Index(range(len(obj)))
- the setitem does not expand the obj
"""
@pytest.fixture
def is_inplace(self, obj, expected):
"""
Whet... | SetitemCastingEquivalents |
python | huggingface__transformers | src/transformers/models/dinov2_with_registers/modular_dinov2_with_registers.py | {
"start": 12991,
"end": 14057
} | class ____(Dinov2PreTrainedModel):
@torch.no_grad()
def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
"""Initialize the weights"""
if isinstance(module, (nn.Linear, nn.Conv2d)):
init.trunc_normal_(module.weight, mean=0.0, std=self.config.initializer_... | Dinov2WithRegistersPreTrainedModel |
python | openai__openai-python | src/openai/lib/streaming/responses/_responses.py | {
"start": 1020,
"end": 3166
} | class ____(Generic[TextFormatT]):
def __init__(
self,
*,
raw_stream: Stream[RawResponseStreamEvent],
text_format: type[TextFormatT] | Omit,
input_tools: Iterable[ToolParam] | Omit,
starting_after: int | None,
) -> None:
self._raw_stream = raw_stream
... | ResponseStream |
python | cython__cython | Cython/Compiler/CmdLine.py | {
"start": 1616,
"end": 1819
} | class ____(Action):
def __call__(self, parser, namespace, values, option_string=None):
namespace.error_on_unknown_names = False
namespace.error_on_uninitialized = False
| SetLenientAction |
python | ansible__ansible | lib/ansible/modules/service_facts.py | {
"start": 3766,
"end": 3857
} | class ____(object):
def __init__(self, module):
self.module = module
| BaseService |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_object_position15.py | {
"start": 315,
"end": 915
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("object_position15.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook =... | TestCompareXLSXFiles |
python | pypa__warehouse | tests/unit/accounts/test_services.py | {
"start": 1422,
"end": 53593
} | class ____:
def test_verify_service(self):
assert verifyClass(IUserService, services.DatabaseUserService)
def test_service_creation(self, monkeypatch):
crypt_context_obj = pretend.stub()
crypt_context_cls = pretend.call_recorder(lambda **kwargs: crypt_context_obj)
monkeypatch.se... | TestDatabaseUserService |
python | huggingface__transformers | src/transformers/models/nemotron/modeling_nemotron.py | {
"start": 39562,
"end": 43417
} | class ____(NemotronPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
def __init__(self, config):
super().__init__(config)
self.model = NemotronModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.... | NemotronForCausalLM |
python | psf__requests | src/requests/exceptions.py | {
"start": 225,
"end": 788
} | class ____(IOError):
"""There was an ambiguous exception that occurred while handling your
request.
"""
def __init__(self, *args, **kwargs):
"""Initialize RequestException with `request` and `response` objects."""
response = kwargs.pop("response", None)
self.response = response
... | RequestException |
python | jmcnamara__XlsxWriter | xlsxwriter/test/sharedstrings/test_sharedstrings01.py | {
"start": 372,
"end": 2228
} | class ____(unittest.TestCase):
"""
Test assembling a complete SharedStrings file.
"""
def test_assemble_xml_file(self):
"""Test the _write_sheet_data() method"""
string_table = SharedStringTable()
# Add some strings and check the returned indices.
index = string_table... | TestAssembleSharedStrings |
python | scipy__scipy | scipy/integrate/tests/test_quadpack.py | {
"start": 11089,
"end": 15839
} | class ____:
def test_double_integral(self):
# 8) Double Integral test
def simpfunc(y, x): # Note order of arguments.
return x+y
a, b = 1.0, 2.0
assert_quad(dblquad(simpfunc, a, b, lambda x: x, lambda x: 2*x),
5/6.0 * (b**3.0-a**3.0))
def te... | TestDblquad |
python | fastai__fastai | fastai/vision/augment.py | {
"start": 2792,
"end": 3913
} | class ____(RandTransform):
"Randomly flip with probability `p`"
def __init__(self, p:float=0.5): super().__init__(p=p)
def encodes(self, x:(Image.Image,*TensorTypes)): return x.flip_lr()
# %% ../../nbs/09_vision.augment.ipynb 21
@patch
def dihedral(x:PILImage,
k:int, # Dihedral transformation to apply... | FlipItem |
python | pytest-dev__pytest | src/_pytest/_py/path.py | {
"start": 3608,
"end": 4736
} | class ____:
def __init__(self, fil, rec, ignore, bf, sort):
if isinstance(fil, str):
fil = FNMatcher(fil)
if isinstance(rec, str):
self.rec: Callable[[LocalPath], bool] = FNMatcher(rec)
elif not hasattr(rec, "__call__") and rec:
self.rec = lambda path: Tru... | Visitor |
python | tensorflow__tensorflow | tensorflow/python/autograph/converters/control_flow.py | {
"start": 14345,
"end": 14837
} | class ____(reaching_definitions.Definition):
def __init__(self):
super(AnnotatedDef, self).__init__()
self.directives = {}
def transform(node, ctx):
graphs = cfg.build(node)
node = qual_names.resolve(node)
node = activity.resolve(node, ctx, None)
node = reaching_definitions.resolve(node, ctx, graph... | AnnotatedDef |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/bedrock.py | {
"start": 4909,
"end": 12398
} | class ____(AwsBaseOperator[BedrockHook]):
"""
Create a fine-tuning job to customize a base model.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BedrockCustomizeModelOperator`
:param job_name: A unique name for the fine-tun... | BedrockCustomizeModelOperator |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/teams/tutorial001.py | {
"start": 1064,
"end": 4877
} | class ____(SQLModel):
name: Optional[str] = None
secret_name: Optional[str] = None
age: Optional[int] = None
team_id: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo=... | HeroUpdate |
python | RaRe-Technologies__gensim | gensim/test/test_utils.py | {
"start": 4660,
"end": 5007
} | class ____(unittest.TestCase):
def test_merge_dicts(self):
d1 = {"word1": 5, "word2": 1, "word3": 2}
d2 = {"word1": 2, "word3": 3, "word4": 10}
res_dict = utils.merge_counts(d1, d2)
expected_dict = {"word1": 7, "word2": 1, "word3": 5, "word4": 10}
self.assertEqual(res_dict, ... | TestMergeDicts |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/duplicate_bases.py | {
"start": 532,
"end": 577
} | class ____(Foo, # 1
Foo # 2
):
pass
| Bar |
python | django__django | django/db/models/aggregates.py | {
"start": 7963,
"end": 8393
} | class ____(Aggregate):
function = "ANY_VALUE"
name = "AnyValue"
arity = 1
window_compatible = False
def as_sql(self, compiler, connection, **extra_context):
if not connection.features.supports_any_value:
raise NotSupportedError(
"ANY_VALUE is not supported on thi... | AnyValue |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 51908,
"end": 51993
} | class ____(Interface):
"""Interface representing a predicate list"""
| IPredicateList |
python | chroma-core__chroma | chromadb/api/models/AsyncCollection.py | {
"start": 635,
"end": 18574
} | class ____(CollectionCommon["AsyncServerAPI"]):
async def add(
self,
ids: OneOrMany[ID],
embeddings: Optional[
Union[
OneOrMany[Embedding],
OneOrMany[PyEmbedding],
]
] = None,
metadatas: Optional[OneOrMany[Metadata]] = N... | AsyncCollection |
python | pytorch__pytorch | torch/nn/modules/_functions.py | {
"start": 8432,
"end": 11832
} | class ____(Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(ctx, input, size, alpha=1e-4, beta=0.75, k=1):
ctx.size = size
ctx.alpha = alpha
ctx.beta = beta
ctx.k = k
ctx.scale = None
if input.dim() != 4:
raise ValueError(
... | CrossMapLRN2d |
python | sphinx-doc__sphinx | sphinx/ext/intersphinx/_shared.py | {
"start": 4008,
"end": 5490
} | class ____:
"""Inventory adapter for environment"""
def __init__(self, env: BuildEnvironment) -> None:
self.env = env
if not hasattr(env, 'intersphinx_cache'):
# initial storage when fetching inventories before processing
self.env.intersphinx_cache = {} # type: ignore[... | InventoryAdapter |
python | astropy__astropy | astropy/io/fits/hdu/base.py | {
"start": 3592,
"end": 27274
} | class ____:
"""Base class for all HDU (header data unit) classes."""
_hdu_registry = set()
# This HDU type is part of the FITS standard
_standard = True
# Byte to use for padding out blocks
_padding_byte = "\x00"
_default_name = ""
# _header uses a descriptor to delay the loading of... | _BaseHDU |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/partial.py | {
"start": 3269,
"end": 3564
} | class ____:
@PartialDecorator
def __init__(self, x: str, y: str) -> None:
self.x = x
self.y = y
def dunder_call_partial_constructor(x: str, y: str) -> C:
# pyre-ignore: Type[PartialConstructor] is not a function.
return PartialConstructor(x, y)
| PartialConstructor |
python | pypa__setuptools | setuptools/discovery.py | {
"start": 8603,
"end": 21190
} | class ____:
"""Fill-in metadata and options that can be automatically derived
(from other metadata/options, the file system or conventions)
"""
def __init__(self, distribution: Distribution) -> None:
self.dist = distribution
self._called = False
self._disabled = False
se... | ConfigDiscovery |
python | falconry__falcon | tests/test_wsgi.py | {
"start": 443,
"end": 5761
} | class ____:
def test_get(self, requests_lite, server_base_url):
resp = requests_lite.get(server_base_url)
assert resp.status_code == 200
assert resp.text == '127.0.0.1'
def test_get_file(self, requests_lite, server_base_url):
# NOTE(vytas): There was a breaking change in the beh... | TestWSGIServer |
python | PyCQA__pylint | pylint/checkers/typecheck.py | {
"start": 2495,
"end": 29681
} | class ____:
pass
VERSION_COMPATIBLE_OVERLOAD_SENTINEL = VERSION_COMPATIBLE_OVERLOAD()
def _is_owner_ignored(
owner: SuccessfulInferenceResult,
attrname: str | None,
ignored_classes: Iterable[str],
ignored_modules: Iterable[str],
) -> bool:
"""Check if the given owner should be ignored.
... | VERSION_COMPATIBLE_OVERLOAD |
python | more-itertools__more-itertools | tests/test_recipes.py | {
"start": 46070,
"end": 46234
} | class ____(TestCase):
def test_basic(self):
self.assertTrue(
all(list(mi.loops(n)) == [None] * n for n in range(-10, 10))
)
| LoopsTests |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructorCallable2.py | {
"start": 2562,
"end": 2847
} | class ____(Generic[T]):
def __new__(cls, x: T, y: list[T]) -> Self:
return super().__new__(cls)
r8 = accepts_callable(Class8)
reveal_type(r8, expected_text="(x: T@Class8, y: list[T@Class8]) -> Class8[T@Class8]")
reveal_type(r8("", [""]), expected_text="Class8[str]")
| Class8 |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_B.py | {
"start": 12515,
"end": 13716
} | class ____(Benchmark):
r"""
BoxBetts objective function.
The BoxBetts global optimization problem is a multimodal
minimization problem defined as follows
.. math::
f_{\text{BoxBetts}}(x) = \sum_{i=1}^k g(x_i)^2
Where, in this exercise:
.. math::
g(x) = e^{-0.1i x_1} -... | BoxBetts |
python | graphql-python__graphene | graphene/relay/tests/test_mutation.py | {
"start": 247,
"end": 291
} | class ____:
shared = String()
| SharedFields |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_us_county_name.py | {
"start": 1789,
"end": 4450
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid us county names.
See https://github.com/yaph/geonamescache for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [... | ExpectColumnValuesToBeValidUSCountyName |
python | wandb__wandb | wandb/apis/public/automations.py | {
"start": 531,
"end": 2095
} | class ____(RelayPaginator["ProjectTriggersFields", "Automation"]):
"""A lazy iterator of `Automation` objects.
<!-- lazydoc-ignore-class: internal -->
"""
QUERY: Document # Must be set per-instance
last_response: Connection[ProjectTriggersFields] | None
def __init__(
self,
cl... | Automations |
python | neetcode-gh__leetcode | python/0745-prefix-and-suffix-search.py | {
"start": 171,
"end": 1522
} | class ____:
def __init__(self, words: List[str]):
# Initialize root of the Trie
self.root = TrieNode()
# For each word, we create combined prefix-suffix keys
for index, word in enumerate(words):
# Insert all combinations of the form prefix{suffix into the Trie
... | WordFilter |
python | tensorflow__tensorflow | tensorflow/python/eager/polymorphic_function/function_spec_test.py | {
"start": 1323,
"end": 21697
} | class ____(test.TestCase, parameterized.TestCase):
@parameterized.product(
({
'input_signature': None,
'type_constraint': (None, None, None)
}, {
'input_signature': (tensor_spec.TensorSpec(shape=None),
tensor_spec.TensorSpec(shape=None),
... | FunctionSpecTest |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 319154,
"end": 322391
} | class ____(Response):
"""
Response of tasks.enqueue endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
:param queued: Number of tasks queued (0 or 1)
:type queued: int
:param queue_watched: ... | EnqueueResponse |
python | getsentry__sentry | src/sentry/net/http.py | {
"start": 951,
"end": 3915
} | class ____:
"""
HACK(mattrobenolt): Most of this is yanked out of core urllib3
to override `_new_conn` with the ability to create our own socket.
"""
is_ipaddress_permitted: IsIpAddressPermitted = None
def __init__(self, *args, is_ipaddress_permitted: IsIpAddressPermitted = None, **kwargs):
... | SafeConnectionMixin |
python | ray-project__ray | rllib/examples/_old_api_stack/models/custom_loss_model.py | {
"start": 697,
"end": 2341
} | class ____(TFModelV2):
"""Custom model that adds an imitation loss on top of the policy loss."""
def __init__(self, obs_space, action_space, num_outputs, model_config, name):
super().__init__(obs_space, action_space, num_outputs, model_config, name)
self.fcnet = FullyConnectedNetwork(
... | CustomLossModel |
python | huggingface__transformers | src/transformers/models/bert_generation/modeling_bert_generation.py | {
"start": 16115,
"end": 17547
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
# Ignore copy
self.layer = nn.ModuleList([BertGenerationLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
def forward(
self,
hidden_states: torch.Tensor... | BertEncoder |
python | PrefectHQ__prefect | tests/server/models/test_csrf_token.py | {
"start": 3686,
"end": 4619
} | class ____:
async def test_can_delete_expired_tokens(self, session: AsyncSession):
# Create some tokens
for i in range(5):
await models.csrf_token.create_or_update_csrf_token(
session=session, client=f"client{i}"
)
# Update some of them to be expired
... | TestDeleteExpiredTokens |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 24710,
"end": 24808
} | class ____(DagsterError):
"""Errors during an object store operation."""
| DagsterObjectStoreError |
python | TheAlgorithms__Python | knapsack/tests/test_knapsack.py | {
"start": 212,
"end": 1294
} | class ____(unittest.TestCase):
def test_base_case(self):
"""
test for the base case
"""
cap = 0
val = [0]
w = [0]
c = len(val)
assert k.knapsack(cap, w, val, c) == 0
val = [60]
w = [10]
c = len(val)
assert k.knapsack(ca... | Test |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/styles/style_transformation.py | {
"start": 1177,
"end": 1770
} | class ____(metaclass=ABCMeta):
"""
Base class for any style transformation.
"""
@abstractmethod
def transform_attrs(self, attrs: Attrs) -> Attrs:
"""
Take an `Attrs` object and return a new `Attrs` object.
Remember that the color formats can be either "ansi..." or a 6 digit... | StyleTransformation |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/links/datasync.py | {
"start": 1180,
"end": 1515
} | class ____(BaseAwsLink):
"""Helper class for constructing AWS DataSync TaskExecution console link."""
name = "DataSync Task Execution"
key = "datasync_task_execution"
format_str = (
BASE_AWS_CONSOLE_LINK + "/datasync/home?region={region_name}#/history/{task_id}/{task_execution_id}"
)
| DataSyncTaskExecutionLink |
python | cython__cython | Cython/Tests/TestJediTyper.py | {
"start": 1018,
"end": 1363
} | class ____(Visitor.VisitorTransform):
directives = None
visit_Node = Visitor.VisitorTransform.recurse_to_children
def visit_CompilerDirectivesNode(self, node):
if not self.directives:
self.directives = []
self.directives.append(node)
self.visitchildren(node)
ret... | DeclarationsFinder |
python | tensorflow__tensorflow | tensorflow/python/ops/distributions/bernoulli.py | {
"start": 1390,
"end": 7087
} | class ____(distribution.Distribution):
"""Bernoulli distribution.
The Bernoulli distribution with `probs` parameter, i.e., the probability of a
`1` outcome (vs a `0` outcome).
"""
@deprecation.deprecated(
"2019-01-01",
"The TensorFlow Distributions library has moved to "
"TensorFlow Probab... | Bernoulli |
python | modin-project__modin | modin/core/execution/python/implementations/pandas_on_python/partitioning/virtual_partition.py | {
"start": 2270,
"end": 2428
} | class ____(PandasOnPythonDataframeAxisPartition):
axis = 0
@_inherit_docstrings(PandasOnPythonDataframeAxisPartition)
| PandasOnPythonDataframeColumnPartition |
python | ansible__ansible | test/lib/ansible_test/_internal/coverage_util.py | {
"start": 1489,
"end": 9457
} | class ____(ApplicationError):
"""Exception caused while attempting to read a coverage file."""
def __init__(self, path: str, message: str) -> None:
self.path = path
self.message = message
super().__init__(f'Error reading coverage file "{os.path.relpath(path)}": {message}')
def get_co... | CoverageError |
python | spack__spack | lib/spack/spack/url_buildcache.py | {
"start": 54834,
"end": 54978
} | class ____(spack.error.SpackError):
"""Raised for problems finding or accessing binary cache entry on mirror"""
pass
| BuildcacheEntryError |
python | readthedocs__readthedocs.org | readthedocs/analytics/migrations/0005_add_unique_constraint.py | {
"start": 149,
"end": 665
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("analytics", "0004_merge_duplicate_records"),
]
operations = [
migrations.AddConstraint(
model_name="pageview",
constraint=models.UniqueConstraint(
condition=models.Q((... | Migration |
python | ansible__ansible | lib/ansible/utils/collection_loader/_collection_config.py | {
"start": 1178,
"end": 3057
} | class ____(type):
def __init__(cls, meta, name, bases):
cls._collection_finder = None
cls._default_collection = None
cls._on_collection_load = _EventSource()
@property
def collection_finder(cls):
return cls._collection_finder
@collection_finder.setter
def collection... | _AnsibleCollectionConfig |
python | pennersr__django-allauth | allauth/socialaccount/providers/agave/views.py | {
"start": 228,
"end": 1326
} | class ____(OAuth2Adapter):
provider_id = "agave"
settings = app_settings.PROVIDERS.get(provider_id, {})
provider_base_url = settings.get("API_URL", "https://public.agaveapi.co")
access_token_url = "{0}/token".format(provider_base_url)
authorize_url = "{0}/authorize".format(provider_base_url)
p... | AgaveAdapter |
python | plotly__plotly.py | plotly/graph_objs/candlestick/_legendgrouptitle.py | {
"start": 233,
"end": 2967
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "candlestick"
_path_str = "candlestick.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be... | Legendgrouptitle |
python | airbytehq__airbyte | airbyte-ci/connectors/live-tests/src/live_tests/report.py | {
"start": 1026,
"end": 2469
} | class ____(ABC):
TEMPLATE_NAME: str
def __init__(self, path: Path, pytest_config: Config) -> None:
self.path = path
self.pytest_config = pytest_config
self.created_at = datetime.datetime.utcnow()
self.updated_at = self.created_at
self.control_execution_results_per_comma... | BaseReport |
python | kamyu104__LeetCode-Solutions | Python/print-words-vertically.py | {
"start": 48,
"end": 273
} | class ____(object):
def printVertically(self, s):
"""
:type s: str
:rtype: List[str]
"""
return ["".join(c).rstrip() for c in itertools.izip_longest(*s.split(), fillvalue=' ')]
| Solution |
python | getsentry__sentry | tests/sentry/incidents/test_logic.py | {
"start": 144695,
"end": 146752
} | class ____(TestCase):
@patch("sentry.incidents.logic.schedule_invalidate_project_config")
def test_create_alert_rule(self, mocked_schedule_invalidate_project_config: MagicMock) -> None:
self.create_alert_rule()
mocked_schedule_invalidate_project_config.assert_not_called()
@patch("sentry.in... | TestCustomMetricAlertRule |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.