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 | pytorch__pytorch | torch/ao/nn/quantized/reference/modules/conv.py | {
"start": 10763,
"end": 13219
} | class ____(_ConvTransposeNd, nn.ConvTranspose2d):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
output_padding=0,
groups=1,
bias=True,
dilation=1,
padding_mode="zeros",
device=None,
... | ConvTranspose2d |
python | getsentry__sentry | src/sentry/sentry_apps/token_exchange/util.py | {
"start": 266,
"end": 485
} | class ____:
AUTHORIZATION = AUTHORIZATION
REFRESH = REFRESH
CLIENT_SECRET_JWT = CLIENT_SECRET_JWT
def token_expiration() -> datetime:
return timezone.now() + timedelta(hours=TOKEN_LIFE_IN_HOURS)
| GrantTypes |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 62861,
"end": 63838
} | class ____(MMTemplateConfigMixin):
"""
Ensure that _should_scale_configs is False
"""
# TODO(coconutruben): remove this once all tests work
# with proper scaling on mm_plus_mm
def __init__(self) -> None:
super().__init__()
self.should_scale_configs = False
def _get_template... | MMPlusMMTemplateConfigMixin |
python | pypa__pipenv | pipenv/vendor/click/utils.py | {
"start": 2723,
"end": 5597
} | class ____:
"""A lazy file works like a regular file but it does not fully open
the file but it does perform some basic checks early to see if the
filename parameter does make sense. This is useful for safely opening
files for writing.
"""
def __init__(
self,
filename: t.Union[... | LazyFile |
python | joke2k__faker | faker/providers/automotive/fi_FI/__init__.py | {
"start": 48,
"end": 276
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``fi_FI`` locale.
Source:
- https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Finland
"""
license_formats = ("???-###",)
| Provider |
python | huggingface__transformers | src/transformers/models/hunyuan_v1_dense/modeling_hunyuan_v1_dense.py | {
"start": 10513,
"end": 12384
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: HunYuanDenseV1Config, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = HunYuanDenseV1Attention(config=config, layer_idx=layer_idx)
self.mlp = HunYuanDenseV1MLP(config)
... | HunYuanDenseV1DecoderLayer |
python | pytorch__pytorch | torch/testing/_internal/distributed/common_state_dict.py | {
"start": 4665,
"end": 4953
} | class ____(nn.Module):
def __init__(self, vocab_size: int, fusion_vocab_size: int, embed_dim: int) -> None:
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.fusion_embedding = nn.Embedding(fusion_vocab_size, embed_dim)
| FusionEmbedding |
python | pypa__setuptools | pkg_resources/__init__.py | {
"start": 68057,
"end": 74565
} | class ____(EggProvider):
"""Resource support for zips and eggs"""
eagers: list[str] | None = None
_zip_manifests = MemoizedZipManifests()
# ZipProvider's loader should always be a zipimporter or equivalent
loader: zipimport.zipimporter
def __init__(self, module: _ZipLoaderModule) -> None:
... | ZipProvider |
python | django__django | django/contrib/postgres/forms/array.py | {
"start": 3730,
"end": 5857
} | class ____(forms.Widget):
template_name = "postgres/widgets/split_array.html"
def __init__(self, widget, size, **kwargs):
self.widget = widget() if isinstance(widget, type) else widget
self.size = size
super().__init__(**kwargs)
@property
def is_hidden(self):
return sel... | SplitArrayWidget |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/np_interop_test.py | {
"start": 13208,
"end": 13722
} | class ____(InteropTest):
def test(self):
tf_var = tf.Variable(2.0)
value = np.square(tf_var)
self.assertIsInstance(value, np.ndarray)
self.assertAllClose(4.0, value)
with tf.control_dependencies([tf_var.assign_add(value)]):
tf_var_value = tf_var.read_value()
self.assertAllClose(6.0, tf_... | VariableTest |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1302783,
"end": 1302994
} | class ____(VegaLiteSchema):
"""TextBaseline schema wrapper."""
_schema = {"$ref": "#/definitions/TextBaseline"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| TextBaseline |
python | lepture__mistune | src/mistune/renderers/rst.py | {
"start": 186,
"end": 5523
} | class ____(BaseRenderer):
"""A renderer for converting Markdown to ReST."""
NAME = "rst"
#: marker symbols for heading
HEADING_MARKERS = {
1: "=",
2: "-",
3: "~",
4: "^",
5: '"',
6: "'",
}
INLINE_IMAGE_PREFIX = "img-"
def iter_tokens(self, t... | RSTRenderer |
python | django__django | tests/queries/models.py | {
"start": 11127,
"end": 11363
} | class ____(models.Model):
first = models.ForeignKey(SimpleCategory, models.CASCADE, related_name="first_rel")
second = models.ForeignKey(
SimpleCategory, models.CASCADE, related_name="second_rel"
)
| CategoryRelationship |
python | django__django | tests/gis_tests/test_fields.py | {
"start": 179,
"end": 477
} | class ____(SimpleTestCase):
def test_area_field_deepcopy(self):
field = AreaField(None)
self.assertEqual(copy.deepcopy(field), field)
def test_distance_field_deepcopy(self):
field = DistanceField(None)
self.assertEqual(copy.deepcopy(field), field)
| FieldsTests |
python | huggingface__transformers | src/transformers/models/encodec/modeling_encodec.py | {
"start": 6977,
"end": 9407
} | class ____(nn.Module):
"""ConvTranspose1d with asymmetric or causal padding and normalization."""
def __init__(self, config, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1):
super().__init__()
self.causal = config.use_causal_conv
self.trim_right_ratio = config.tr... | EncodecConvTranspose1d |
python | joke2k__faker | faker/providers/ssn/sv_SE/__init__.py | {
"start": 148,
"end": 3016
} | class ____(SsnProvider):
@staticmethod
def _org_to_vat(org_id: str) -> str:
org_id = org_id.replace("-", "")
if len(org_id) == 10:
org_id = "16" + org_id
return f"SE{org_id}01"
def ssn(
self,
min_age: int = 18,
max_age: int = 90,
long: boo... | Provider |
python | pandas-dev__pandas | pandas/io/formats/style_render.py | {
"start": 1416,
"end": 77674
} | class ____:
"""
Base class to process rendering a Styler with a specified jinja2 template.
"""
this_dir = pathlib.Path(__file__).parent.resolve()
template_dir = this_dir / "templates"
loader = jinja2.FileSystemLoader(template_dir)
env = jinja2.Environment(loader=loader, trim_blocks=True)
... | StylerRenderer |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_relationship.py | {
"start": 85752,
"end": 87659
} | class ____(fixtures.MappedTest):
run_setup_mappers = "once"
run_inserts = None
run_deletes = None
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
... | SameNameOnJoined |
python | conda__conda | conda/gateways/logging.py | {
"start": 2020,
"end": 7384
} | class ____(StreamHandler):
"""Log StreamHandler that always writes to the current sys stream."""
terminator = "\n"
def __init__(self, sys_stream):
"""
Args:
sys_stream: stream name, either "stdout" or "stderr" (attribute of module sys)
"""
super().__init__(getat... | StdStreamHandler |
python | walkccc__LeetCode | solutions/2074. Reverse Nodes in Even Length Groups/2074.py | {
"start": 0,
"end": 1156
} | class ____:
def reverseEvenLengthGroups(self, head: ListNode | None) -> ListNode | None:
# prev -> (head -> ... -> tail) -> next -> ...
dummy = ListNode(0, head)
prev = dummy
tail = head
next = head.next
groupLength = 1
def getTailAndLength(head: ListNode | None, groupLength: int) -> tupl... | Solution |
python | astropy__astropy | astropy/modeling/rotations.py | {
"start": 6369,
"end": 8834
} | class ____(_EulerRotation, Model):
"""
Implements Euler angle intrinsic rotations.
Rotates one coordinate system into another (fixed) coordinate system.
All coordinate systems are right-handed. The sign of the angles is
determined by the right-hand rule..
Parameters
----------
phi, the... | EulerAngleRotation |
python | ray-project__ray | rllib/examples/compute_adapted_gae_on_postprocess_trajectory.py | {
"start": 842,
"end": 5695
} | class ____(RLlibCallback):
@override(RLlibCallback)
def on_postprocess_trajectory(
self,
*,
worker,
episode,
agent_id,
policy_id,
policies,
postprocessed_batch,
original_batches,
**kwargs
):
super().on_postprocess_trajec... | MyCallbacks |
python | nedbat__coveragepy | tests/test_arcs.py | {
"start": 23941,
"end": 38459
} | class ____(CoverageTest):
"""Arc-measuring tests involving exception handling."""
def test_try_except(self) -> None:
self.check_coverage(
"""\
a, b = 1, 1
try:
a = 3
except:
b = 5
assert a == 3 and b == 1
... | ExceptionArcTest |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_tests.py | {
"start": 68068,
"end": 81616
} | class ____(TestCase):
def test_plugin_config_without_options(self) -> None:
class Schema(Config):
plugins = c.Plugins()
cfg = {
'plugins': ['sample'],
}
conf = self.get_config(Schema, cfg)
assert_type(conf.plugins, PluginCollection)
self.asse... | PluginsTest |
python | sqlalchemy__sqlalchemy | test/orm/declarative/test_concurrency.py | {
"start": 502,
"end": 2652
} | class ____(fixtures.TestBase):
def teardown_test(self):
clear_mappers()
@classmethod
def make_a(cls, Base):
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
data = Column(String)
bs = relationship("B")
# need... | ConcurrentUseDeclMappingTest |
python | astropy__astropy | astropy/table/tests/conftest.py | {
"start": 1343,
"end": 3436
} | class ____(table.Table):
Row = MyRow
Column = MyColumn
MaskedColumn = MyMaskedColumn
TableColumns = MyTableColumns
TableFormatter = MyTableFormatter
# Fixture to run all the Column tests for both an unmasked (ndarray)
# and masked (MaskedArray) column.
@pytest.fixture(params=["unmasked", "masked... | MyTable |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_repo_path_parsing.py | {
"start": 410,
"end": 1671
} | class ____(APITestCase):
def setUp(self) -> None:
self.org = self.create_organization(owner=self.user, name="blap")
self.project = self.create_project(
name="foo", organization=self.org, teams=[self.create_team(organization=self.org)]
)
def make_post(
self,
s... | BaseStacktraceLinkTest |
python | getsentry__sentry | src/sentry/api/endpoints/organization_sampling_project_span_counts.py | {
"start": 1076,
"end": 3779
} | class ____(OrganizationEndpoint):
"""Endpoint for retrieving project span counts in all orgs."""
owner = ApiOwner.TELEMETRY_EXPERIENCE
permission_classes = (OrganizationPermission,)
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def get(self, request: Request, organization: Orga... | OrganizationSamplingProjectSpanCountsEndpoint |
python | huggingface__transformers | src/transformers/integrations/tensor_parallel.py | {
"start": 22612,
"end": 24598
} | class ____(TensorParallelLayer):
"""
This class is used to isolate computation in a TP layer from the rest of the world.
Parameters need to be LOCAL, so not dtensors
"""
@staticmethod
def _prepare_input_fn(input_layouts, desired_input_layouts, mod, inputs, device_mesh=None):
# annotate ... | IsolatedParallel |
python | bokeh__bokeh | setup.py | {
"start": 6482,
"end": 6732
} | class ____(sdist): # type: ignore
def run(self) -> None:
check_tags()
build_or_install_bokehjs(self.distribution.packages)
super().run()
setup(cmdclass={"build": Build, "editable_wheel": EditableWheel, "sdist": Sdist})
| Sdist |
python | tensorflow__tensorflow | tensorflow/compiler/tests/conv3d_test.py | {
"start": 1637,
"end": 20394
} | class ____(xla_test.XLATestCase, parameterized.TestCase):
def _VerifyValues(
self,
input_sizes=None,
filter_sizes=None,
strides=None,
dilations=None,
padding=None,
data_format_src="NDHWC",
data_format_dst="NDHWC",
expected=None,
op_name="Conv3D",
):
"... | Conv3DTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_selection.py | {
"start": 2058,
"end": 26454
} | class ____(ABC):
"""An AssetSelection defines a query over a set of assets and asset checks, normally all that are defined in a project.
You can use the "|", "&", and "-" operators to create unions, intersections, and differences of selections, respectively.
AssetSelections are typically used with :py:fun... | AssetSelection |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/uninitializedVariable2.py | {
"start": 687,
"end": 718
} | class ____(Abstract2):
pass
| E |
python | scikit-learn__scikit-learn | sklearn/metrics/_scorer.py | {
"start": 2964,
"end": 7262
} | class ____:
"""Callable for multimetric scoring used to avoid repeated calls
to `predict_proba`, `predict`, and `decision_function`.
`_MultimetricScorer` will return a dictionary of scores corresponding to
the scorers in the dictionary. Note that `_MultimetricScorer` can be
created with a dictionar... | _MultimetricScorer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 402031,
"end": 402899
} | class ____(sgqlc.types.Interface):
"""Entities that can be minimized."""
__schema__ = github_schema
__field_names__ = ("is_minimized", "minimized_reason", "viewer_can_minimize")
is_minimized = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isMinimized")
"""Returns whether or not a c... | Minimizable |
python | pola-rs__polars | py-polars/src/polars/datatype_expr/struct.py | {
"start": 122,
"end": 2008
} | class ____:
"""Namespace for struct datatype expressions."""
_accessor = "struct"
def __init__(self, expr: pl.DataTypeExpr) -> None:
self._pydatatype_expr = expr._pydatatype_expr
def __getitem__(self, item: str | int) -> pl.DataTypeExpr:
if isinstance(item, str):
return se... | DataTypeExprStructNameSpace |
python | cherrypy__cherrypy | cherrypy/process/servers.py | {
"start": 9166,
"end": 9885
} | class ____(object):
"""Adapter for a flup.server.cgi.WSGIServer."""
def __init__(self, *args, **kwargs):
"""Initialize the flup CGI Server plugin."""
self.args = args
self.kwargs = kwargs
self.ready = False
def start(self):
"""Start the CGI server."""
# We h... | FlupCGIServer |
python | wandb__wandb | wandb/vendor/pygments/lexers/haskell.py | {
"start": 22758,
"end": 23443
} | class ____(LiterateLexer):
"""
For Literate Agda source.
Additional options accepted:
`litstyle`
If given, must be ``"bird"`` or ``"latex"``. If not given, the style
is autodetected: if the first non-whitespace character in the source
is a backslash or percent character, LaTeX... | LiterateAgdaLexer |
python | yaml__pyyaml | tests/legacy_tests/test_multi_constructor.py | {
"start": 513,
"end": 553
} | class ____(yaml.FullLoader):
pass
| Multi1 |
python | spack__spack | lib/spack/spack/database.py | {
"start": 73730,
"end": 73865
} | class ____(SpackError):
"""Raised to signal Database.reindex that the reindex should happen via spec.json"""
| DatabaseNotReadableError |
python | pydantic__pydantic | pydantic/types.py | {
"start": 74935,
"end": 76047
} | class ____(EncoderProtocol):
"""URL-safe Base64 encoder."""
@classmethod
def decode(cls, data: bytes) -> bytes:
"""Decode the data from base64 encoded bytes to original bytes data.
Args:
data: The data to decode.
Returns:
The decoded data.
"""
... | Base64UrlEncoder |
python | spack__spack | lib/spack/spack/reporters/junit.py | {
"start": 181,
"end": 1045
} | class ____(Reporter):
"""Generate reports of spec installations for JUnit."""
_jinja_template = "reports/junit.xml"
def concretization_report(self, filename, msg):
pass
def build_report(self, filename, specs):
for spec in specs:
spec.summarize()
if not (os.path.sp... | JUnit |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-form-subsequence-with-target-sum.py | {
"start": 2615,
"end": 3452
} | class ____(object):
def minOperations(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def floor_log2_x(x):
return x.bit_length()-1
if sum(nums) < target:
return -1
cnt = [0]*(floor_log2_x(max(n... | Solution4 |
python | huggingface__transformers | src/transformers/models/rt_detr/modeling_rt_detr.py | {
"start": 24919,
"end": 26120
} | class ____(nn.Module):
"""
Convolutional backbone using the modeling_rt_detr_resnet.py.
nn.BatchNorm2d layers are replaced by RTDetrFrozenBatchNorm2d as defined above.
https://github.com/lyuwenyu/RT-DETR/blob/main/rtdetr_pytorch/src/nn/backbone/presnet.py#L142
"""
def __init__(self, config):
... | RTDetrConvEncoder |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/axislines.py | {
"start": 5356,
"end": 6536
} | class ____(_FixedAxisArtistHelperBase):
def __init__(self, axes, loc):
super().__init__(loc)
self.axis = [axes.xaxis, axes.yaxis][self.nth_coord]
# TICK
def get_tick_iterators(self, axes):
"""tick_loc, tick_angle, tick_label"""
angle_normal, angle_tangent = {0: (90, 0), 1:... | FixedAxisArtistHelperRectilinear |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_mlab.py | {
"start": 35135,
"end": 36665
} | class ____:
def test_kde_integer_input(self):
"""Regression test for #1181."""
x1 = np.arange(5)
kde = mlab.GaussianKDE(x1)
y_expected = [0.13480721, 0.18222869, 0.19514935, 0.18222869,
0.13480721]
np.testing.assert_array_almost_equal(kde(x1), y_expecte... | TestGaussianKDE |
python | marshmallow-code__apispec | tests/test_ext_marshmallow_openapi.py | {
"start": 15290,
"end": 23081
} | class ____:
def test_schema2jsonschema_with_nested_fields(self, spec_fixture):
res = spec_fixture.openapi.schema2jsonschema(PetSchema)
props = res["properties"]
assert props["category"]["items"] == build_ref(
spec_fixture.spec, "schema", "Category"
)
@pytest.mark.pa... | TestNesting |
python | great-expectations__great_expectations | great_expectations/execution_engine/pandas_execution_engine.py | {
"start": 2245,
"end": 31078
} | class ____(ExecutionEngine[str]):
"""PandasExecutionEngine instantiates the ExecutionEngine API to support computations using Pandas.
Constructor builds a PandasExecutionEngine, using provided configuration options.
Args:
*args: Positional arguments for configuring PandasExecutionEngine
**... | PandasExecutionEngine |
python | redis__redis-py | tests/test_connection.py | {
"start": 11350,
"end": 13579
} | class ____:
@pytest.mark.parametrize(
"max_conn", (-1, "str"), ids=("non-positive", "wrong type")
)
def test_throws_error_on_incorrect_max_connections(self, max_conn):
with pytest.raises(
ValueError, match='"max_connections" must be a positive integer'
):
Conn... | TestUnitConnectionPool |
python | getsentry__sentry | tests/sentry/conf/test_scopes.py | {
"start": 147,
"end": 1248
} | class ____(TestCase):
def test_scope_hierarchy_maintained(self) -> None:
assert "org:superuser" not in SENTRY_SCOPES
for scope in SENTRY_SCOPES:
assert scope in SENTRY_SCOPE_HIERARCHY_MAPPING
# exclude special OAuth scopes
if ":" not in scope:
con... | ScopesTest |
python | huggingface__transformers | src/transformers/models/dinov3_vit/modeling_dinov3_vit.py | {
"start": 16083,
"end": 17868
} | class ____(GradientCheckpointingLayer):
"""This corresponds to the Block class in the original implementation."""
def __init__(self, config: DINOv3ViTConfig):
super().__init__()
self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.attention = DINOv3ViTAttention... | DINOv3ViTLayer |
python | encode__httpx | httpx/_types.py | {
"start": 2676,
"end": 2965
} | class ____:
async def __aiter__(self) -> AsyncIterator[bytes]:
raise NotImplementedError(
"The '__aiter__' method must be implemented."
) # pragma: no cover
yield b"" # pragma: no cover
async def aclose(self) -> None:
pass
| AsyncByteStream |
python | celery__celery | celery/worker/consumer/agent.py | {
"start": 130,
"end": 525
} | class ____(bootsteps.StartStopStep):
"""Agent starts :pypi:`cell` actors."""
conditional = True
requires = (Connection,)
def __init__(self, c, **kwargs):
self.agent_cls = self.enabled = c.app.conf.worker_agent
super().__init__(c, **kwargs)
def create(self, c):
agent = c.ag... | Agent |
python | falconry__falcon | tests/test_response_media.py | {
"start": 4337,
"end": 5377
} | class ____:
def test_text(self, client):
client.simulate_get('/')
resp = client.resource.captured_resp
resp.text = 'body'
resp.data = b'data'
resp.media = ['media']
assert resp.render_body() == b'body'
def test_data(self, client):
client.simulate_get('... | TestRenderBodyPrecedence |
python | Pylons__pyramid | src/pyramid/predicates.py | {
"start": 4572,
"end": 5178
} | class ____:
def __init__(self, val, config):
val = as_sorted_tuple(val)
self.val = val
reqs = [p.split('=', 1) for p in val]
self.reqs = [(x.strip(), y.strip()) for x, y in reqs]
def text(self):
return 'match_param %s' % ','.join([f'{x}={y}' for x, y in self.reqs])
... | MatchParamPredicate |
python | python__mypy | mypy/suggestions.py | {
"start": 6434,
"end": 7473
} | class ____(Exception):
pass
def is_explicit_any(typ: AnyType) -> bool:
# Originally I wanted to count as explicit anything derived from an explicit any, but that
# seemed too strict in some testing.
# return (typ.type_of_any == TypeOfAny.explicit
# or (typ.source_any is not None and typ.so... | SuggestionFailure |
python | viewflow__viewflow | viewflow/views/create.py | {
"start": 917,
"end": 4673
} | class ____(
FormLayoutMixin, FormDependentSelectMixin, FormAjaxCompleteMixin, generic.CreateView
):
viewset = None
layout = None
form_widgets = None
template_name_suffix = "_create"
def has_add_permission(self, request):
if self.viewset is not None:
return self.viewset.has_... | CreateModelView |
python | ray-project__ray | release/ray_release/cluster_manager/cluster_manager.py | {
"start": 631,
"end": 5045
} | class ____(abc.ABC):
def __init__(
self,
test: Test,
project_id: str,
sdk: Optional["AnyscaleSDK"] = None,
smoke_test: bool = False,
log_streaming_limit: int = LAST_LOGS_LENGTH,
):
self.sdk = sdk or get_anyscale_sdk()
self.test = test
self... | ClusterManager |
python | huggingface__transformers | src/transformers/models/afmoe/modeling_afmoe.py | {
"start": 6651,
"end": 7806
} | class ____(nn.Module):
"""
Token-choice top-K router for MoE routing.
This router assigns each token to the top-K experts based on sigmoid scores, matching the released checkpoints.
"""
def __init__(self, config):
super().__init__()
self.config = config
self.top_k = config.... | AfmoeTokenChoiceRouter |
python | ansible__ansible | test/units/module_utils/common/test_sys_info.py | {
"start": 1276,
"end": 4604
} | class ____:
"""Tests for get_distribution that have to find something"""
def test_distro_known(self):
with patch('ansible.module_utils.distro.id', return_value="alpine"):
assert get_distribution() == "Alpine"
with patch('ansible.module_utils.distro.id', return_value="arch"):
... | TestGetDistribution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 225882,
"end": 226242
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "pull_request")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
pull_request = sgqlc.types.Field("PullRequest", graphql_n... | ClosePullRequestPayload |
python | google__jax | jax/_src/pallas/mosaic/interpret/interpret_pallas_call.py | {
"start": 31599,
"end": 41491
} | class ____:
id: int
src_device_id: int
src_local_core_id: int
src_memory_space: int
src_buffer_id: int
src_transforms: tuple[Any, ...]
dst_device_id: int
dst_local_core_id: int
dst_memory_space: int
dst_buffer_id: int
dst_transforms: tuple[Any, ...]
src_sem: memory.Semaphore | None
dst_sem: m... | DMA |
python | modin-project__modin | modin/tests/pandas/dataframe/test_default.py | {
"start": 8979,
"end": 55725
} | class ____:
@pytest.mark.parametrize("method", ["pearson", "kendall", "spearman"])
@pytest.mark.parametrize("backend", [None, "pyarrow"])
def test_corr(self, method, backend):
eval_general(
*create_test_dfs(test_data["int_data"], backend=backend),
lambda df: df.corr(method=me... | TestCorr |
python | scrapy__scrapy | tests/test_request_cb_kwargs.py | {
"start": 5746,
"end": 7153
} | class ____:
@classmethod
def setup_class(cls):
cls.mockserver = MockServer()
cls.mockserver.__enter__()
@classmethod
def teardown_class(cls):
cls.mockserver.__exit__(None, None, None)
@inlineCallbacks
def test_callback_kwargs(self):
crawler = get_crawler(Keyword... | TestCallbackKeywordArguments |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-microsoft-onedrive/source_microsoft_onedrive/stream_reader.py | {
"start": 699,
"end": 770
} | class ____(RemoteFile):
download_url: str
| MicrosoftOneDriveRemoteFile |
python | keras-team__keras | guides/making_new_layers_and_models_via_subclassing.py | {
"start": 2348,
"end": 3309
} | class ____(keras.layers.Layer):
def __init__(self, input_dim):
super().__init__()
self.total = self.add_weight(
initializer="zeros", shape=(input_dim,), trainable=False
)
def call(self, inputs):
self.total.assign_add(ops.sum(inputs, axis=0))
return self.total... | ComputeSum |
python | scrapy__scrapy | tests/test_downloadermiddleware_redirect.py | {
"start": 495,
"end": 44181
} | class ____:
class Test:
def test_priority_adjust(self):
req = Request("http://a.com")
rsp = self.get_response(req, "http://a.com/redirected")
req2 = self.mw.process_response(req, rsp)
assert req2.priority > req.priority
def test_dont_redirect(self):
... | Base |
python | google__pytype | pytype/attribute_test.py | {
"start": 459,
"end": 4925
} | class ____(test_base.UnitTest):
"""Tests for get_attribute's `valself` parameter."""
def setUp(self):
super().setUp()
options = config.Options.create(
python_version=self.python_version, color="never"
)
self.ctx = test_utils.make_context(options)
self.node = self.ctx.root_node
self.... | ValselfTest |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 1098,
"end": 1248
} | class ____(IntEnum):
Unknown = 0
ContiguousFormat = 1
ChannelsLast = 2
ChannelsLast3d = 3
PreserveFormat = 4
@dataclass
| MemoryFormat |
python | ApeWorX__ape | src/ape/logging.py | {
"start": 11046,
"end": 12368
} | class ____:
rich_console_map: dict[str, "RichConsole"] = {}
def get_console(self, file: Optional[IO[str]] = None, **kwargs) -> "RichConsole":
# Configure custom file console
file_id = str(file)
if file_id not in self.rich_console_map:
# perf: delay importing from rich, as it... | _RichConsoleFactory |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 9773,
"end": 11149
} | class ____(TypedDict, total=False):
type: Required[ExpectedSerializationTypes]
def simple_ser_schema(type: ExpectedSerializationTypes) -> SimpleSerSchema:
"""
Returns a schema for serialization with a custom type.
Args:
type: The type to use for serialization
"""
return SimpleSerSchem... | SimpleSerSchema |
python | bokeh__bokeh | src/bokeh/models/annotations/arrows.py | {
"start": 2573,
"end": 3169
} | class ____(ArrowHead):
''' Render a closed-body arrow head.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
line_props = Include(LineProps, help="""
The {prop} values for the arrow head outline... | NormalHead |
python | openai__openai-python | src/openai/cli/_errors.py | {
"start": 161,
"end": 196
} | class ____(OpenAIError): ...
| CLIError |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 93643,
"end": 95959
} | class ____(system_info):
# BLAS_SRC is deprecated, please do not use this!
# Build or install a BLAS library via your package manager or from
# source separately.
section = 'blas_src'
dir_env_var = 'BLAS_SRC'
notfounderror = BlasSrcNotFoundError
def get_paths(self, section, key):
pr... | blas_src_info |
python | django__django | tests/test_utils/tests.py | {
"start": 25748,
"end": 39541
} | class ____(SimpleTestCase):
def test_html_parser(self):
element = parse_html("<div><p>Hello</p></div>")
self.assertEqual(len(element.children), 1)
self.assertEqual(element.children[0].name, "p")
self.assertEqual(element.children[0].children[0], "Hello")
parse_html("<p>")
... | HTMLEqualTests |
python | pallets__werkzeug | tests/test_http.py | {
"start": 26198,
"end": 29882
} | class ____:
def test_best_match_works(self):
# was a bug in 0.6
rv = http.parse_accept_header(
"foo=,application/xml,application/xhtml+xml,"
"text/html;q=0.9,text/plain;q=0.8,"
"image/png,*/*;q=0.5",
datastructures.MIMEAccept,
).best_match(["fo... | TestRegression |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 874284,
"end": 875072
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for PullRequestReviewComment."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("PullRequestReviewCommentEdge"), graphql_name="edges")
"""A lis... | PullRequestReviewCommentConnection |
python | kamyu104__LeetCode-Solutions | Python/valid-parentheses.py | {
"start": 29,
"end": 401
} | class ____(object):
# @return a boolean
def isValid(self, s):
stack, lookup = [], {"(": ")", "{": "}", "[": "]"}
for parenthese in s:
if parenthese in lookup:
stack.append(parenthese)
elif len(stack) == 0 or lookup[stack.pop()] != parenthese:
... | Solution |
python | matplotlib__matplotlib | tools/boilerplate.py | {
"start": 2453,
"end": 3349
} | class ____:
"""
Format function default values as needed for inspect.formatargspec.
The interesting part is a hard-coded list of functions used
as defaults in pyplot methods.
"""
def __init__(self, value):
if value is mlab.detrend_none:
self._repr = "mlab.detrend_none"
... | value_formatter |
python | python-poetry__poetry | src/poetry/puzzle/transaction.py | {
"start": 494,
"end": 7842
} | class ____:
def __init__(
self,
current_packages: list[Package],
result_packages: list[Package] | dict[Package, TransitivePackageInfo],
installed_packages: list[Package] | None = None,
root_package: Package | None = None,
marker_env: Mapping[str, Any] | None = None,
... | Transaction |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/kms.py | {
"start": 1553,
"end": 6336
} | class ____(GoogleBaseHook):
"""
Hook for Google Cloud Key Management service.
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get... | CloudKMSHook |
python | pydantic__pydantic | pydantic/aliases.py | {
"start": 2683,
"end": 4937
} | class ____:
"""!!! abstract "Usage Documentation"
[Using an `AliasGenerator`](../concepts/alias.md#using-an-aliasgenerator)
A data class used by `alias_generator` as a convenience to create various aliases.
Attributes:
alias: A callable that takes a field name and returns an alias for it.
... | AliasGenerator |
python | tensorflow__tensorflow | tensorflow/python/saved_model/save_options.py | {
"start": 998,
"end": 3536
} | class ____(enum.Enum):
"""Enum defining options for variable handling when saving.
NONE
No policy applied: Distributed variables are saved as one variable, with no
device attached.
SAVE_VARIABLE_DEVICES
When saving variables, also save their device assignment.
This is useful if one wants to hard... | VariablePolicy |
python | kamyu104__LeetCode-Solutions | Python/task-scheduler.py | {
"start": 71,
"end": 402
} | class ____(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
counter = Counter(tasks)
_, max_count = counter.most_common(1)[0]
return max((max_count-1) * (n+1) + counter.values().count(max_count), len(t... | Solution |
python | django__django | tests/admin_views/models.py | {
"start": 23262,
"end": 23363
} | class ____(models.Model):
"""
Simple model with nothing on it for use in testing
"""
| Simple |
python | pydantic__pydantic | pydantic/experimental/pipeline.py | {
"start": 1102,
"end": 1270
} | class ____:
func: Callable[[], type[Any]]
@cached_property
def tp(self) -> type[Any]:
return self.func()
@dataclass(**_slots_frozen)
| _ValidateAsDefer |
python | pytorch__pytorch | benchmarks/dynamo/genai_layers/kernels.py | {
"start": 14149,
"end": 17781
} | class ____(BenchmarkKernel):
def __init__(self, script_args):
super().__init__(script_args)
self.available_backends = [
"eager",
"compiled",
"quack",
"liger",
]
def get_shapes(self) -> tuple[tuple[int, ...], ...]:
# TODO: OOM for (... | RMSNormBackward |
python | pypa__pipenv | pipenv/patched/pip/_internal/models/direct_url.py | {
"start": 3974,
"end": 4435
} | class ____:
name: ClassVar = "dir_info"
editable: bool = False
@classmethod
def _from_dict(cls, d: Optional[Dict[str, Any]]) -> Optional["DirInfo"]:
if d is None:
return None
return cls(editable=_get_required(d, bool, "editable", default=False))
def _to_dict(self) -> D... | DirInfo |
python | cython__cython | tests/run/withstat_py27.py | {
"start": 2590,
"end": 2703
} | class ____(object):
def __enter__(self): pass
def __exit__(self, *exc_info): raise RuntimeError()
| ExitRaises |
python | plotly__plotly.py | plotly/io/_defaults.py | {
"start": 42,
"end": 411
} | class ____(object):
"""
Class to store default settings for image generation.
"""
def __init__(self):
self.default_format = "png"
self.default_width = 700
self.default_height = 500
self.default_scale = 1
self.mathjax = None
self.topojson = None
se... | _Defaults |
python | django__django | tests/modeladmin/models.py | {
"start": 75,
"end": 306
} | class ____(models.Model):
name = models.CharField(max_length=100)
bio = models.TextField()
sign_date = models.DateField()
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
| Band |
python | huggingface__transformers | tests/models/qwen2/test_tokenization_qwen2.py | {
"start": 883,
"end": 2971
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "Qwen/Qwen2.5-VL-7B-Instruct"
tokenizer_class = Qwen2Tokenizer
integration_expected_tokens = ['This', 'Ġis', 'Ġa', 'Ġtest', 'ĠðŁĺ', 'Ĭ', 'Ċ', 'I', 'Ġwas', 'Ġborn', 'Ġin', 'Ġ', '9', '2', '0', '0', '0', ',', 'Ġand', 'Ġthis', 'Ġis', 'Ġf... | Qwen2TokenizationTest |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 37241,
"end": 37421
} | class ____(axis_ticks_major_y, axis_ticks_minor_y):
"""
y major and minor axis tick lines
Parameters
----------
theme_element : element_line
"""
| axis_ticks_y |
python | wandb__wandb | wandb/sdk/artifacts/_generated/project_artifact_type.py | {
"start": 343,
"end": 549
} | class ____(GQLResult):
artifact_type: Optional[ArtifactTypeFragment] = Field(alias="artifactType")
ProjectArtifactType.model_rebuild()
ProjectArtifactTypeProject.model_rebuild()
| ProjectArtifactTypeProject |
python | fastapi__sqlmodel | docs_src/tutorial/connect/select/tutorial003_py310.py | {
"start": 222,
"end": 2147
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
team_id: int | None = Field(default=None, foreign_key="team.id")
sqlite_file_name = "database.db"
sqlite_url = ... | Hero |
python | kamyu104__LeetCode-Solutions | Python/number-of-music-playlists.py | {
"start": 33,
"end": 611
} | class ____(object):
def numMusicPlaylists(self, N, L, K):
"""
:type N: int
:type L: int
:type K: int
:rtype: int
"""
M = 10**9+7
dp = [[0 for _ in xrange(1+L)] for _ in xrange(2)]
dp[0][0] = dp[1][1] = 1
for n in xrange(1, N+1):
... | Solution |
python | ray-project__ray | python/ray/air/tests/mocked_wandb_integration.py | {
"start": 899,
"end": 1688
} | class ____:
"""Thread-safe.
Note: Not implemented to mock re-init behavior properly. Proceed with caution."""
def __init__(self):
self.logs = []
self.config = _FakeConfig()
def init(self, *args, **kwargs):
mock = Mock()
mock.args = args
mock.kwargs = kwargs
... | _MockWandbAPI |
python | getsentry__sentry | src/sentry/models/projecttemplate.py | {
"start": 283,
"end": 1125
} | class ____(DefaultFieldsModelExisting):
"""
Identifies a project template that can be used to create new projects.
This model links the project template options to the organization that owns them.
"""
__relocation_scope__ = RelocationScope.Organization
name = models.CharField(max_length=200)
... | ProjectTemplate |
python | pytorch__pytorch | torch/_inductor/loop_body.py | {
"start": 785,
"end": 1809
} | class ____(torch.fx.Interpreter):
@staticmethod
@functools.cache
def _dummy_gm():
return torch.fx.symbolic_trace(identity)
def __init__(self, graph, submodules):
# call super() with a placeholder to avoid constructing a
# GraphModule which is very expensive (it does codegen).
... | InterpreterShim |
python | pypa__hatch | tests/env/plugin/test_interface.py | {
"start": 20012,
"end": 24857
} | class ____:
def test_default(self, isolation, isolated_data_dir, platform, global_application):
config = {"project": {"name": "my_app", "version": "0.0.1"}}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
... | TestFeatures |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.