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 | huggingface__transformers | src/transformers/models/gemma2/modular_gemma2.py | {
"start": 10994,
"end": 13907
} | class ____(GemmaRotaryEmbedding):
def __init__(self, config: Gemma2Config, device=None):
nn.Module.__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_type = self.confi... | Gemma2RotaryEmbedding |
python | pytorch__pytorch | test/autograd/test_logging.py | {
"start": 150,
"end": 841
} | class ____(LoggingTestCase):
@make_logging_test(autograd=logging.DEBUG)
def test_logging(self, records):
a = torch.rand(10, requires_grad=True)
b = a.mul(2).div(3).sum()
c = b.clone()
torch.autograd.backward((b, c))
self.assertEqual(len(records), 5)
expected = [
... | TestAutogradLogging |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_lambda_function.py | {
"start": 1266,
"end": 1402
} | class ____(LambdaHook):
conn = MagicMock(name="conn")
@pytest.fixture
def hook():
return LambdaHookForTests()
| LambdaHookForTests |
python | django__django | django/db/migrations/writer.py | {
"start": 542,
"end": 4527
} | class ____:
def __init__(self, operation, indentation=2):
self.operation = operation
self.buff = []
self.indentation = indentation
def serialize(self):
def _write(_arg_name, _arg_value):
if _arg_name in self.operation.serialization_expand_args and isinstance(
... | OperationWriter |
python | doocs__leetcode | solution/0500-0599/0568.Maximum Vacation Days/Solution.py | {
"start": 0,
"end": 545
} | class ____:
def maxVacationDays(self, flights: List[List[int]], days: List[List[int]]) -> int:
n = len(flights)
K = len(days[0])
f = [[-inf] * n for _ in range(K + 1)]
f[0][0] = 0
for k in range(1, K + 1):
for j in range(n):
f[k][j] = f[k - 1][j]
... | Solution |
python | keon__algorithms | tests/test_stack.py | {
"start": 2621,
"end": 4291
} | class ____(unittest.TestCase):
def test_ArrayStack(self):
stack = ArrayStack()
stack.push(1)
stack.push(2)
stack.push(3)
# test __iter__()
it = iter(stack)
self.assertEqual(3, next(it))
self.assertEqual(2, next(it))
self.assertEqual(1, next(it... | TestStack |
python | numpy__numpy | numpy/linalg/lapack_lite/make_lite.py | {
"start": 5002,
"end": 7972
} | class ____(FortranLibrary):
def _newFortranRoutine(self, rname, filename):
routine = FortranLibrary._newFortranRoutine(self, rname, filename)
if 'blas' in filename.lower():
routine.type = 'blas'
elif 'install' in filename.lower():
routine.type = 'config'
elif ... | LapackLibrary |
python | PrefectHQ__prefect | src/prefect/server/orchestration/rules.py | {
"start": 39573,
"end": 39685
} | class ____(
BaseOrchestrationRule[orm_models.FlowRun, core.FlowRunPolicy]
):
pass
| FlowRunOrchestrationRule |
python | doocs__leetcode | solution/0200-0299/0274.H-Index/Solution3.py | {
"start": 0,
"end": 299
} | class ____:
def hIndex(self, citations: List[int]) -> int:
l, r = 0, len(citations)
while l < r:
mid = (l + r + 1) >> 1
if sum(x >= mid for x in citations) >= mid:
l = mid
else:
r = mid - 1
return l
| Solution |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_hitl.py | {
"start": 9150,
"end": 15203
} | class ____:
@time_machine.travel(datetime(2025, 7, 3, 0, 0, 0), tick=False)
@pytest.mark.usefixtures("sample_hitl_detail")
def test_should_respond_200_with_existing_response(
self,
test_client: TestClient,
sample_ti_url_identifier: str,
sample_update_payload: dict[str, Any],
... | TestUpdateHITLDetailEndpoint |
python | tornadoweb__tornado | demos/blog/blog.py | {
"start": 2549,
"end": 4410
} | class ____(tornado.web.RequestHandler):
def row_to_obj(self, row, cur):
"""Convert a SQL row to an object supporting dict and attribute access."""
obj = tornado.util.ObjectDict()
for val, desc in zip(row, cur.description):
obj[desc.name] = val
return obj
async def ex... | BaseHandler |
python | pytorch__pytorch | torch/fx/_graph_pickler.py | {
"start": 17479,
"end": 17801
} | class ____(_OpPickleData):
def __init__(self, name: str) -> None:
self.name = name
def unpickle(self, unpickle_state: _UnpickleState) -> torch._ops.OpOverload:
obj = self._lookup_global_by_name(self.name)
assert isinstance(obj, torch._ops.OpOverload)
return obj
| _OpOverloadPickleData |
python | walkccc__LeetCode | solutions/564. Find the Closest Palindrome/564.py | {
"start": 0,
"end": 1215
} | class ____:
def nearestPalindromic(self, n: str) -> str:
prevPalindrome, nextPalindrome = self._getPalindromes(n)
return (str(prevPalindrome)
if abs(prevPalindrome - int(n)) <= abs(nextPalindrome - int(n))
else str(nextPalindrome))
def _getPalindromes(self, s: str) -> tuple[str, str... | Solution |
python | pandas-dev__pandas | pandas/tests/series/methods/test_nlargest.py | {
"start": 593,
"end": 8020
} | class ____:
@pytest.mark.parametrize(
"r",
[
Series([3.0, 2, 1, 2, "5"], dtype="object"),
Series([3.0, 2, 1, 2, 5], dtype="object"),
# not supported on some archs
# Series([3., 2, 1, 2, 5], dtype='complex256'),
Series([3.0, 2, 1, 2, 5], dty... | TestSeriesNLargestNSmallest |
python | tensorflow__tensorflow | tensorflow/compiler/tests/fake_quant_ops_test.py | {
"start": 21207,
"end": 26000
} | class ____(xla_test.XLATestCase):
"""Test cases for FakeQuantWithMinMaxVarsPerChannelGradient operation."""
# 8 bits, wide range.
def testOp_with8Bits(self):
self._TestOp(
[0.0, 0.5, -128.0, -0.1],
[255.0, 128.0, -0.5, 127.4],
8,
False,
[0.0, 0.0, -127.5, 0.0],
... | FakeQuantWithMinMaxVarsPerChannelGradientTest |
python | getsentry__sentry | src/sentry/api/paginator.py | {
"start": 11262,
"end": 15013
} | class ____(OffsetPaginator):
"""This paginator uses a function to first look up items from an
independently paginated resource to only then fall back to a query set.
This is for instance useful if you want to query snuba for the primary
sort order and then look up data in postgres.
"""
def __in... | MergingOffsetPaginator |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_tests.py | {
"start": 54959,
"end": 58323
} | class ____(TestCase):
def defaults(self):
return {
'nav': {
'omitted_files': logging.INFO,
'not_found': logging.WARNING,
'absolute_links': logging.INFO,
},
'links': {
'not_found': logging.WARNING,
... | NestedSubConfigTest |
python | jazzband__prettytable | src/prettytable/prettytable.py | {
"start": 2248,
"end": 3310
} | class ____(IntEnum):
DEFAULT = 10
MSWORD_FRIENDLY = 11
PLAIN_COLUMNS = 12
MARKDOWN = 13
ORGMODE = 14
DOUBLE_BORDER = 15
SINGLE_BORDER = 16
RANDOM = 20
# keep for backwards compatibility
_DEPRECATED_FRAME: Final = 0
_DEPRECATED_ALL: Final = 1
_DEPRECATED_NONE: Final = 2
_DEPRECATED_HEAD... | TableStyle |
python | nedbat__coveragepy | tests/test_data.py | {
"start": 37321,
"end": 38294
} | class ____(CoverageTest):
"""Tests of CoverageData.dumps and loads."""
run_in_temp_dir = False
@pytest.mark.parametrize("klass", [CoverageData, DebugCoverageData])
def test_serialization(self, klass: TCoverageData) -> None:
covdata1 = klass(no_disk=True)
covdata1.add_lines(LINES_1)
... | DumpsLoadsTest |
python | ray-project__ray | rllib/utils/tests/test_actor_manager.py | {
"start": 636,
"end": 2009
} | class ____(FaultAwareApply):
def __init__(self, i, maybe_crash=True):
self.random_numbers = RANDOM_NUMS[i]
self.count = 0
self.maybe_crash = maybe_crash
self.config = {
"restart_failed_env_runners": True,
}
def _maybe_crash(self):
if not self.maybe_cr... | Actor |
python | joke2k__faker | tests/providers/test_date_time.py | {
"start": 25018,
"end": 25374
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("de_DE")
Faker.seed(0)
def test_day(self):
day = self.fake.day_of_week()
assert day in DeDeProvider.DAY_NAMES.values()
def test_month(self):
month = self.fake.month_name()
assert month in DeDe... | TestDeDe |
python | pypa__pipenv | pipenv/vendor/packaging/specifiers.py | {
"start": 2875,
"end": 26456
} | class ____(BaseSpecifier):
"""This class abstracts handling of version specifiers.
.. tip::
It is generally not required to instantiate this manually. You should instead
prefer to work with :class:`SpecifierSet` instead, which can parse
comma-separated version specifiers (which is what... | Specifier |
python | apache__airflow | airflow-core/src/airflow/timetables/simple.py | {
"start": 2576,
"end": 3668
} | class ____(_TrivialTimetable):
"""
Timetable that schedules the execution once as soon as possible.
This corresponds to ``schedule="@once"``.
"""
description: str = "Once, as soon as possible"
@property
def summary(self) -> str:
return "@once"
def next_dagrun_info(
se... | OnceTimetable |
python | joke2k__faker | faker/providers/company/it_IT/__init__.py | {
"start": 95,
"end": 9708
} | class ____(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}}-{{last_name}} {{company_suffix}}",
"{{last_name}}, {{last_name}} e {{last_name}} {{company_suffix}}",
)
catch_phrase_words = (
(
"Abilità",
"Access",
... | Provider |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 2342,
"end": 2591
} | class ____(RootModel[dict[str, Any]]):
model_config = {
"json_schema_extra": {
"$ref": create_definition_ref("io.k8s.api.core.v1.PodSecurityContext"),
"additionalProperties": True,
}
}
| PodSecurityContext |
python | kamyu104__LeetCode-Solutions | Python/game-of-life.py | {
"start": 33,
"end": 1142
} | class ____(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0]) if m else 0
for i in xrange(m):
for j in xrange(n):
... | Solution |
python | astropy__astropy | astropy/utils/metadata/tests/test_metadata.py | {
"start": 1826,
"end": 1930
} | class ____:
meta = MetaData()
def __init__(self, meta=None):
self.meta = meta
| ExampleData |
python | PyCQA__pylint | tests/functional/u/unused/unused_import_py30.py | {
"start": 414,
"end": 469
} | class ____(metaclass=SomethingElse):
""" test """
| Meta3 |
python | scipy__scipy | benchmarks/benchmarks/stats_sampling.py | {
"start": 6072,
"end": 7006
} | class ____(Benchmark):
param_names = ['dist', 'order']
params = [allcontdists, [3, 5]]
def setup(self, dist, order):
self.urng = np.random.default_rng(0xb235b58c1f616c59c18d8568f77d44d1)
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
... | NumericalInverseHermite |
python | google__jax | tests/lax_vmap_op_test.py | {
"start": 973,
"end": 2942
} | class ____(jtu.JaxTestCase):
def _CheckBatching(self, op, bdim_size, bdims, shapes, dtypes, rng,
rtol=None, atol=None, multiple_results=False):
batched_shapes = map(functools.partial(lax_test_util.add_bdim, bdim_size),
bdims, shapes)
args = [rng(shape, dtype) for... | LaxVmapOpTest |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 5754,
"end": 5992
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("bg_BG")
Faker.seed(0)
def test_vat_id(self):
for _ in range(100):
assert re.search(r"^BG\d{9,10}$", self.fake.vat_id())
| TestBgBG |
python | plotly__plotly.py | plotly/graph_objs/layout/_slider.py | {
"start": 235,
"end": 24393
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout"
_path_str = "layout.slider"
_valid_props = {
"active",
"activebgcolor",
"bgcolor",
"bordercolor",
"borderwidth",
"currentvalue",
"font",
"len",
"lenmode",
"minort... | Slider |
python | dask__dask | dask/tests/test_multiprocessing.py | {
"start": 5098,
"end": 8457
} | class ____:
value = 0
def proc_init():
global_.value = 1
@pytest.mark.parametrize(
"scheduler, initializer, expected_results",
[
("threading", None, [1] * 10),
("processes", None, [0] * 10),
("processes", proc_init, [1] * 10),
],
)
def test_process_initializer(scheduler, ... | global_ |
python | sympy__sympy | sympy/assumptions/sathandlers.py | {
"start": 2429,
"end": 9418
} | class ____:
"""
Register handlers against classes.
Explanation
===========
``register`` method registers the handler function for a class. Here,
handler function should return a single fact. ``multiregister`` method
registers the handler function for multiple classes. Here, handler functio... | ClassFactRegistry |
python | Textualize__rich | rich/align.py | {
"start": 7781,
"end": 10288
} | class ____(JupyterMixin):
"""Vertically aligns a renderable.
Warn:
This class is deprecated and may be removed in a future version. Use Align class with
`vertical="middle"`.
Args:
renderable (RenderableType): A renderable object.
style (StyleType, optional): An optional sty... | VerticalCenter |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 118867,
"end": 120020
} | class ____(Response):
"""
Response of tasks.add_or_update_artifacts endpoint.
:param updated: Indicates if the task was updated successfully
:type updated: int
"""
_service = "tasks"
_action = "add_or_update_artifacts"
_version = "2.23"
_schema = {
"definitions": {},
... | AddOrUpdateArtifactsResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-okta/unit_tests/test_migration.py | {
"start": 486,
"end": 1636
} | class ____:
test_not_migrated_config_path = "unit_tests/migration_configs/not_migrated_config.json"
test_migrated_config_path = "unit_tests/migration_configs/migrated_config.json"
def test_migrate_config(self, capsys):
config = load_config(self.test_not_migrated_config_path)
assert "domain"... | TestMigrateConfig |
python | google__pytype | pytype/tests/test_cmp1.py | {
"start": 5957,
"end": 6975
} | class ____(test_base.BaseTest):
"""Test for "x == y". Also test overloading."""
def test_concrete(self):
self.Check("""
def f(x, y):
return x == y
assert_type(f(1, 2), bool)
assert_type(f(1, "a"), bool)
assert_type(f(object(), "x"), bool)
""")
def test_overloaded(self):
... | EqTest |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_mic_match_country_code.py | {
"start": 1059,
"end": 2305
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_mic_match_country_code"
condition_value_keys = ("country_code",)
url = "https://www.iso20022.org/sites/default/files/ISO10383_MIC/ISO10383_MIC.csv"
d... | ColumnValuesToBeValidMicMatchCountryCode |
python | ipython__ipython | IPython/core/error.py | {
"start": 1294,
"end": 1535
} | class ____(IPythonCoreError, NotImplementedError):
"""raw_input was requested in a context where it is not supported
For use in IPython kernels, where only some frontends may support
stdin requests.
"""
| StdinNotImplementedError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1048187,
"end": 1048895
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for User."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("UserEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.... | UserConnection |
python | spyder-ide__spyder | spyder/widgets/helperwidgets.py | {
"start": 1487,
"end": 2833
} | class ____(QMessageBox):
"""
A QMessageBox derived widget that includes a QCheckBox aligned to the right
under the message and on top of the buttons.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowModality(Qt.NonModal)
self._checkbox... | MessageCheckBox |
python | fastai__fastai | fastai/vision/widgets.py | {
"start": 4291,
"end": 5215
} | class ____(GetAttr):
"A widget that provides an `ImagesCleaner` for a CNN `Learner`"
def __init__(self, learn, **kwargs):
vocab = learn.dls.vocab
self.default = self.iw = ImagesCleaner(vocab, **kwargs)
self.dd_cats = Dropdown(options=vocab)
self.dd_ds = Dropdown(options=('Train... | ImageClassifierCleaner |
python | optuna__optuna | optuna/trial/_trial.py | {
"start": 947,
"end": 29607
} | class ____(BaseTrial):
"""A trial is a process of evaluating an objective function.
This object is passed to an objective function and provides interfaces to get parameter
suggestion, manage the trial's state, and set/get user-defined attributes of the trial.
Note that the direct use of this construct... | Trial |
python | Pylons__pyramid | src/pyramid/config/factories.py | {
"start": 9175,
"end": 9281
} | class ____:
def __init__(self):
self.descriptors = {}
self.methods = {}
| _RequestExtensions |
python | huggingface__transformers | src/transformers/time_series_utils.py | {
"start": 2583,
"end": 5302
} | class ____:
distribution_class: type
in_features: int
args_dim: dict[str, int]
def __init__(self, dim: int = 1) -> None:
self.dim = dim
self.args_dim = {k: dim * self.args_dim[k] for k in self.args_dim}
def _base_distribution(self, distr_args):
if self.dim == 1:
... | DistributionOutput |
python | gevent__gevent | src/gevent/_config.py | {
"start": 18257,
"end": 18386
} | class ____(AresSettingMixin, Setting):
name = 'ares_tries'
default = None
environment_key = 'GEVENTARES_TRIES'
| AresTries |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 7414,
"end": 23384
} | class ____(unittest.TestCase):
def test_no_sleep(self):
r = Retrying()
self.assertEqual(0, r.wait(make_retry_state(18, 9879)))
def test_fixed_sleep(self):
for wait in (1, datetime.timedelta(seconds=1)):
with self.subTest():
r = Retrying(wait=tenacity.wait_fix... | TestWaitConditions |
python | huggingface__transformers | src/transformers/models/clap/modeling_clap.py | {
"start": 4610,
"end": 5288
} | class ____(ModelOutput):
r"""
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
The text embeddings obtained by applying the projection layer to the pooler_output.
"""
text_embeds: Optional[torch.Floa... | ClapTextModelOutput |
python | pypa__pip | src/pip/_internal/index/collector.py | {
"start": 6345,
"end": 8017
} | class ____(Protocol):
def __call__(self, page: IndexContent) -> Iterable[Link]: ...
def with_cached_index_content(fn: ParseLinks) -> ParseLinks:
"""
Given a function that parses an Iterable[Link] from an IndexContent, cache the
function's result (keyed by CacheablePageContent), unless the IndexContent... | ParseLinks |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard_python3/bundled-services/blobstore/wsgi/main.py | {
"start": 1533,
"end": 2028
} | class ____(blobstore.BlobstoreUploadHandler):
"""Upload handler called by blobstore when a blob is uploaded in the test."""
def post(self, environ):
upload = self.get_uploads(environ)[0]
user_photo = UserPhoto(blob_key=upload.key())
user_photo.put()
# Redirect to the '/view_pho... | UploadPhotoHandler |
python | huggingface__transformers | src/transformers/models/modernbert/modeling_modernbert.py | {
"start": 32527,
"end": 41703
} | class ____(ModernBertPreTrainedModel):
def __init__(self, config: ModernBertConfig):
super().__init__(config)
self.config = config
self.embeddings = ModernBertEmbeddings(config)
self.layers = nn.ModuleList(
[ModernBertEncoderLayer(config, layer_id) for layer_id in range(c... | ModernBertModel |
python | mlflow__mlflow | mlflow/tracing/otel/translation/open_inference.py | {
"start": 292,
"end": 1971
} | class ____(OtelSchemaTranslator):
"""
Translator for OpenInference semantic conventions.
Only defines the attribute keys and mappings. All translation logic
is inherited from the base class.
"""
# OpenInference span kind attribute key
# Reference: https://github.com/Arize-ai/openinference/... | OpenInferenceTranslator |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/declarative_automation/operands/operands.py | {
"start": 3756,
"end": 4241
} | class ____(SubsetAutomationCondition):
@property
def name(self) -> str:
return "missing"
async def compute_subset(self, context: AutomationContext) -> EntitySubset: # pyright: ignore[reportIncompatibleMethodOverride]
return await context.asset_graph_view.compute_missing_subset(
... | MissingAutomationCondition |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/input_spec.py | {
"start": 1134,
"end": 11165
} | class ____(object):
"""Specifies the rank, dtype and shape of every input to a layer.
Layers can expose (if appropriate) an `input_spec` attribute:
an instance of `InputSpec`, or a nested structure of `InputSpec` instances
(one per input tensor). These objects enable the layer to run input
compatibility chec... | InputSpec |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/dms.py | {
"start": 7208,
"end": 8743
} | class ____(AwsBaseWaiterTrigger):
"""
Trigger when an AWS DMS Serverless replication is de-provisioned.
:param replication_config_arn: The ARN of the replication config.
:param waiter_delay: The amount of time in seconds to wait between attempts.
:param waiter_max_attempts: The maximum number of at... | DmsReplicationDeprovisionedTrigger |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/_row_cy.py | {
"start": 1455,
"end": 7417
} | class ____:
__slots__ = ("_parent", "_data", "_key_to_index")
if cython.compiled:
_parent: ResultMetaData = cython.declare(object, visibility="readonly")
_key_to_index: Dict[_KeyType, int] = cython.declare(
dict, visibility="readonly"
)
_data: Tuple[Any, ...] = cytho... | BaseRow |
python | pytorch__pytorch | torch/_dynamo/package.py | {
"start": 37887,
"end": 40119
} | class ____(DynamoStore):
"""
A DynamoStore implementation that keeps state about CompilePackages on disk.
"""
def __init__(self, path_prefix: str = ""):
"""
Initialize a DiskDynamoStore with a path prefix.
Args:
path_prefix: Prefix directory for where to put Compile... | DiskDynamoStore |
python | ray-project__ray | python/ray/autoscaler/_private/util.py | {
"start": 3769,
"end": 38174
} | class ____:
def __init__(self):
self._lock = threading.RLock()
self._counter = collections.defaultdict(int)
def inc(self, key, count):
with self._lock:
self._counter[key] += count
return self.value
def dec(self, key, count):
with self._lock:
... | ConcurrentCounter |
python | ray-project__ray | rllib/utils/replay_buffers/tests/test_prioritized_replay_buffer_replay_buffer_api.py | {
"start": 305,
"end": 23694
} | class ____(unittest.TestCase):
"""
Tests insertion and (weighted) sampling of the PrioritizedReplayBuffer.
"""
capacity = 10
alpha = 1.0
beta = 1.0
def _generate_data(self):
return SampleBatch(
{
SampleBatch.T: [np.random.random((4,))],
S... | TestPrioritizedReplayBuffer |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | experiments/Robot_arm/arm_env.py | {
"start": 269,
"end": 3963
} | class ____(object):
action_bound = [-1, 1]
action_dim = 2
state_dim = 7
dt = .1 # refresh rate
arm1l = 100
arm2l = 100
viewer = None
viewer_xy = (400, 400)
get_point = False
mouse_in = np.array([False])
point_l = 15
grab_counter = 0
def __init__(self, mode='easy'):
... | ArmEnv |
python | huggingface__transformers | src/transformers/models/sam3_tracker/modular_sam3_tracker.py | {
"start": 5232,
"end": 5294
} | class ____(Sam2MaskEmbedding):
pass
| Sam3TrackerMaskEmbedding |
python | FactoryBoy__factory_boy | tests/test_alchemy.py | {
"start": 2289,
"end": 3444
} | class ____(TransactionTestCase):
def setUp(self):
super().setUp()
StandardFactory.reset_sequence(1)
def test_pk_first(self):
std = StandardFactory.build()
self.assertEqual('foo1', std.foo)
def test_pk_many(self):
std1 = StandardFactory.build()
std2 = Standar... | SQLAlchemyPkSequenceTestCase |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1009785,
"end": 1010252
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UnlinkProjectV2FromTeam"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "team")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the m... | UnlinkProjectV2FromTeamPayload |
python | apache__airflow | providers/fab/tests/unit/fab/auth_manager/cli_commands/test_utils.py | {
"start": 1723,
"end": 3530
} | class ____:
def test_get_application_builder(self):
"""Test that get_application_builder returns an AirflowAppBuilder instance."""
with get_application_builder() as appbuilder:
assert isinstance(appbuilder, AirflowAppBuilder)
def test_sqlalchemy_uri_configured(self, flask_app):
... | TestCliUtils |
python | pytorch__pytorch | torch/export/dynamic_shapes.py | {
"start": 15645,
"end": 16462
} | class ____(_ConstraintTarget):
"""
This represents a derived Dim, whose root is either a regular constraint target
(which directly specifies the shape of some input dimension) or a phantom root
(which does so indirectly).
It can be thought of as a subclass of `_Constraint`, except that it does not
... | _DerivedConstraint |
python | mlflow__mlflow | mlflow/gateway/providers/anthropic.py | {
"start": 11777,
"end": 16467
} | class ____(BaseProvider, AnthropicAdapter):
NAME = "Anthropic"
CONFIG_TYPE = AnthropicConfig
def __init__(self, config: EndpointConfig) -> None:
super().__init__(config)
if config.model.config is None or not isinstance(config.model.config, AnthropicConfig):
raise TypeError(f"Inv... | AnthropicProvider |
python | tensorflow__tensorflow | tensorflow/python/feature_column/sequence_feature_column_integration_test.py | {
"start": 1164,
"end": 5669
} | class ____(test.TestCase):
def test_seq_ex_in_sequence_categorical_column_with_identity(self):
self._test_parsed_sequence_example(
'int_list', sfc.sequence_categorical_column_with_identity,
10, [3, 6], [2, 4, 6])
def test_seq_ex_in_sequence_categorical_column_with_hash_bucket(self):
self._... | SequenceExampleParsingTest |
python | zarr-developers__zarr-python | src/zarr/codecs/numcodecs/_codecs.py | {
"start": 7773,
"end": 7842
} | class ____(_NumcodecsBytesBytesCodec, codec_name="lzma"):
pass
| LZMA |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 16273,
"end": 16407
} | class ____(PydanticValueError):
code = 'payment_card_number.digits'
msg_template = 'card number is not all digits'
| NotDigitError |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_dow_ticker.py | {
"start": 671,
"end": 1669
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_dow_ticker"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas... | ColumnValuesToBeValidDowTicker |
python | apache__airflow | airflow-core/tests/unit/utils/test_log_handlers.py | {
"start": 26720,
"end": 32158
} | class ____:
def test_python_formatting(self, create_log_template, create_task_instance, logical_date):
create_log_template("{dag_id}/{task_id}/{logical_date}/{try_number}.log")
filename_rendering_ti = create_task_instance(
dag_id="dag_for_testing_filename_rendering",
task_id=... | TestFilenameRendering |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline.py | {
"start": 5826,
"end": 6070
} | class ____(GrapheneTimePartitionRange):
status = graphene.NonNull(GraphenePartitionRangeStatus)
class Meta: # pyright: ignore[reportIncompatibleVariableOverride]
name = "TimePartitionRangeStatus"
| GrapheneTimePartitionRangeStatus |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 121983,
"end": 122368
} | class ____(IRNode):
dtype: torch.dtype
device: torch.device
def get_size(self) -> Sequence[Expr]:
return ()
def get_device(self) -> Optional[torch.device]:
return self.device
def get_origin_node(self) -> Optional[torch.fx.Node]:
return None
def get_reads(self) -> Orde... | BaseConstant |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_select.py | {
"start": 19881,
"end": 22794
} | class ____(fixtures.TablesTest):
"""tests for #7471"""
__sparse_driver_backend__ = True
__requires__ = ("schemas",)
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
schema... | SameNamedSchemaTableTest |
python | Pylons__pyramid | tests/test_events.py | {
"start": 11371,
"end": 11569
} | class ____:
def __init__(self):
self.attached = []
def attach(self, wrapped, fn, category=None, depth=None):
self.attached.append((wrapped, fn, category, depth))
| DummyVenusian |
python | django__django | django/contrib/auth/views.py | {
"start": 9252,
"end": 12545
} | class ____(PasswordContextMixin, FormView):
form_class = SetPasswordForm
post_reset_login = False
post_reset_login_backend = None
reset_url_token = "set-password"
success_url = reverse_lazy("password_reset_complete")
template_name = "registration/password_reset_confirm.html"
title = _("Enter... | PasswordResetConfirmView |
python | wandb__wandb | wandb/vendor/pygments/lexer.py | {
"start": 9317,
"end": 10730
} | class ____(object):
"""
A pseudo match object constructed from a string.
"""
def __init__(self, start, text):
self._text = text
self._start = start
def start(self, arg=None):
return self._start
def end(self, arg=None):
return self._start + len(self._text)
... | _PseudoMatch |
python | getsentry__sentry | src/sentry/issues/suspect_tags.py | {
"start": 287,
"end": 7469
} | class ____(NamedTuple):
key: str
score: float
@sentry_sdk.trace
def get_suspect_tag_scores(
org_id: int,
project_id: int,
start: datetime,
end: datetime,
envs: list[str],
group_id: int,
) -> list[Score]:
"""
Queries the baseline and outliers sets. Computes the KL scores of each... | Score |
python | scikit-learn__scikit-learn | sklearn/tree/_classes.py | {
"start": 41630,
"end": 55420
} | class ____(RegressorMixin, BaseDecisionTree):
"""A decision tree regressor.
Read more in the :ref:`User Guide <tree>`.
Parameters
----------
criterion : {"squared_error", "friedman_mse", "absolute_error", \
"poisson"}, default="squared_error"
The function to measure the quality... | DecisionTreeRegressor |
python | kamyu104__LeetCode-Solutions | Python/check-if-a-string-contains-all-binary-codes-of-size-k.py | {
"start": 39,
"end": 309
} | class ____(object):
def hasAllCodes(self, s, k):
"""
:type s: str
:type k: int
:rtype: bool
"""
return 2**k <= len(s) and len({s[i:i+k] for i in xrange(len(s)-k+1)}) == 2**k
# Time: O(n * k)
# Space: O(2^k)
| Solution |
python | crytic__slither | slither/detectors/variables/uninitialized_state_variables.py | {
"start": 871,
"end": 5947
} | class ____(AbstractDetector):
"""
Constant function detector
"""
ARGUMENT = "uninitialized-state"
HELP = "Uninitialized state variables"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#u... | UninitializedStateVarsDetection |
python | numba__numba | numba/cuda/simulator/kernelapi.py | {
"start": 1425,
"end": 1544
} | class ____(object):
'''
CUDA Const arrays
'''
def array_like(self, ary):
return ary
| FakeCUDAConst |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/jit/rpc_test.py | {
"start": 10669,
"end": 11455
} | class ____(torch.jit.ScriptModule):
def __init__(self, rank):
super().__init__()
self.a = torch.ones(rank)
@torch.jit.script_method
def forward(self) -> Tensor:
return self.a
@torch.jit.script_method
def custom_func(self) -> Tensor:
return self.a
def owner_create_... | MyScriptModule |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/context.py | {
"start": 3444,
"end": 7917
} | class ____:
__slots__ = (
"top_level_context",
"compile_state",
"query",
"user_passed_query",
"params",
"load_options",
"bind_arguments",
"execution_options",
"session",
"autoflush",
"populate_existing",
"invoke_all_eage... | QueryContext |
python | getsentry__sentry | tests/sentry/utils/test_committers.py | {
"start": 2917,
"end": 3647
} | class ____(unittest.TestCase):
def test_equal_paths(self) -> None:
assert score_path_match_length("foo/bar/baz", "foo/bar/baz") == 3
def test_partial_match_paths(self) -> None:
assert score_path_match_length("foo/bar/baz", "bar/baz") == 2
assert score_path_match_length("foo/bar/baz", "b... | ScorePathMatchLengthTest |
python | pydata__xarray | xarray/tests/test_dataset.py | {
"start": 299797,
"end": 300843
} | class ____:
@pytest.mark.parametrize("keep", ["first", "last", False])
def test_drop_duplicates_1d(self, keep) -> None:
ds = xr.Dataset(
{"a": ("time", [0, 5, 6, 7]), "b": ("time", [9, 3, 8, 2])},
coords={"time": [0, 0, 1, 2]},
)
if keep == "first":
a... | TestDropDuplicates |
python | sphinx-doc__sphinx | tests/test_ext_autodoc/autodoc_util.py | {
"start": 633,
"end": 2539
} | class ____(EventManager):
def __init__(self) -> None:
super().__init__(SimpleNamespace(pdb=False)) # type: ignore[arg-type]
self.add('autodoc-before-process-signature')
self.add('autodoc-process-docstring')
self.add('autodoc-process-signature')
self.add('autodoc-skip-member... | FakeEvents |
python | pallets__werkzeug | examples/simplewiki/application.py | {
"start": 657,
"end": 3499
} | class ____:
"""
Our central WSGI application.
"""
def __init__(self, database_uri):
self.database_engine = create_engine(database_uri)
# apply our middlewares. we apply the middlewars *inside* the
# application and not outside of it so that we never lose the
# referen... | SimpleWiki |
python | cython__cython | Cython/Compiler/Symtab.py | {
"start": 137463,
"end": 137637
} | class ____(Scope):
def __init__(self, name, outer_scope):
Scope.__init__(self, name, outer_scope, None)
self.directives = outer_scope.directives
| TemplateScope |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/bincount_op_test.py | {
"start": 22603,
"end": 28195
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
@parameterized.parameters([{
"dtype": np.int32,
}, {
"dtype": np.int64,
}])
def test_ragged_bincount_count(self, dtype):
x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]])
expect... | RaggedBincountOpTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/model_service.py | {
"start": 23041,
"end": 26306
} | class ____(GoogleCloudBaseOperator):
"""
Sets the desired Model version as Default.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param model_id: Required. The ID ... | SetDefaultVersionOnModelOperator |
python | apache__airflow | providers/smtp/tests/unit/smtp/hooks/test_smtp.py | {
"start": 17914,
"end": 24124
} | class ____:
"""Tests for async functionality in SmtpHook."""
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id=CONN_ID_DEFAULT,
conn_type=CONN_TYPE,
h... | TestSmtpHookAsync |
python | has2k1__plotnine | plotnine/positions/position.py | {
"start": 623,
"end": 8325
} | class ____(ABC, metaclass=Register):
"""Base class for all positions"""
REQUIRED_AES: set[str] = set()
"""
Aesthetics required for the positioning
"""
params: dict[str, Any]
def __init__(self):
self.params = {}
def setup_params(self, data: pd.DataFrame) -> dict[str, Any]:
... | position |
python | django__django | tests/decorators/test_http.py | {
"start": 304,
"end": 2330
} | class ____(SimpleTestCase):
def test_wrapped_sync_function_is_not_coroutine_function(self):
def sync_view(request):
return HttpResponse()
wrapped_view = require_http_methods(["GET"])(sync_view)
self.assertIs(iscoroutinefunction(wrapped_view), False)
def test_wrapped_async_f... | RequireHttpMethodsTest |
python | bokeh__bokeh | tests/unit/bokeh/plotting/test__legends.py | {
"start": 5353,
"end": 6420
} | class ____:
@pytest.mark.parametrize('arg', [1, 2.7, None, False, [], {}])
def test_bad_arg(self, arg: Any) -> None:
with pytest.raises(ValueError):
bpl._handle_legend_label(arg, Legend(), GlyphRenderer())
def test_label_already_exists(self) -> None:
legend = Legend(items=[Legen... | Test__handle_legend_label |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/auth/managers/test_base_auth_manager.py | {
"start": 1974,
"end": 4907
} | class ____(BaseAuthManager[BaseAuthManagerUserTest]):
def deserialize_user(self, token: dict[str, Any]) -> BaseAuthManagerUserTest:
raise NotImplementedError()
def serialize_user(self, user: BaseAuthManagerUserTest) -> dict[str, Any]:
raise NotImplementedError()
def is_authorized_configura... | EmptyAuthManager |
python | pytest-dev__pytest | src/_pytest/config/argparsing.py | {
"start": 16417,
"end": 17566
} | class ____(argparse.Action):
"""Custom argparse action that makes a CLI flag equivalent to overriding an
option, in addition to behaving like `store_true`.
This can simplify things since code only needs to inspect the config option
and not consider the CLI flag.
"""
def __init__(
self,... | OverrideIniAction |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_task_runner.py | {
"start": 79615,
"end": 90342
} | class ____:
@pytest.mark.parametrize(
("do_xcom_push", "should_push_xcom", "expected_xcom_value"),
[
pytest.param(False, False, None, id="do_xcom_push_false"),
pytest.param(True, True, "Hello World!", id="do_xcom_push_true"),
],
)
def test_xcom_push_flag(
... | TestXComAfterTaskExecution |
python | spack__spack | lib/spack/spack/multimethod.py | {
"start": 11484,
"end": 11655
} | class ____(spack.error.SpackError):
"""Superclass for multimethod dispatch errors"""
def __init__(self, message):
super().__init__(message)
| MultiMethodError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.