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 | tensorflow__tensorflow | tensorflow/python/keras/optimizer_v1.py | {
"start": 16411,
"end": 20118
} | class ____(Optimizer):
"""Adam optimizer.
Default parameters follow those provided in the original paper.
Args:
lr: float >= 0. Learning rate.
beta_1: float, 0 < beta < 1. Generally close to 1.
beta_2: float, 0 < beta < 1. Generally close to 1.
epsilon: float >= 0. Fuzz factor.
If `None`, ... | Adam |
python | ray-project__ray | python/ray/data/_internal/compute.py | {
"start": 1896,
"end": 7306
} | class ____(ComputeStrategy):
"""Specify the actor-based compute strategy for a Dataset transform.
ActorPoolStrategy specifies that an autoscaling pool of actors should be used
for a given Dataset transform. This is useful for stateful setup of callable
classes.
For a fixed-sized pool of size ``n``... | ActorPoolStrategy |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/canonical/original.py | {
"start": 0,
"end": 158
} | class ____:
"""docstring"""
def meth(self):
"""docstring"""
def bar():
class Bar:
"""docstring"""
return Bar
Bar = bar()
| Foo |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 13458,
"end": 14520
} | class ____(PrefectBaseModel, OperatorMixin):
"""Filter task runs. Only task runs matching all criteria will be returned"""
id: Optional[TaskRunFilterId] = Field(
default=None, description="Filter criteria for `TaskRun.id`"
)
name: Optional[TaskRunFilterName] = Field(
default=None, descr... | TaskRunFilter |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_session.py | {
"start": 13433,
"end": 24347
} | class ____(AsyncFixture):
run_inserts = None
@async_test
async def test_interrupt_ctxmanager_connection(
self, async_trans_ctx_manager_fixture, async_session
):
fn = async_trans_ctx_manager_fixture
await fn(async_session, trans_on_subject=True, execute_on_subject=True)
@as... | AsyncSessionTransactionTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_excel2003_style08.py | {
"start": 315,
"end": 1003
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("excel2003_style08.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self... | TestCompareXLSXFiles |
python | walkccc__LeetCode | solutions/487. Max Consecutive Ones II/487-2.py | {
"start": 0,
"end": 348
} | class ____:
def findMaxConsecutiveOnes(self, nums: list[int]) -> int:
maxZeros = 1
ans = 0
q = collections.deque() # Store indices of zero.
l = 0
for r, num in enumerate(nums):
if num == 0:
q.append(r)
if len(q) > maxZeros:
l = q.popleft() + 1
ans = max(ans, r -... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_scatter13.py | {
"start": 315,
"end": 1602
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_scatter12.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.g... | TestCompareXLSXFiles |
python | keras-team__keras | keras/src/layers/core/einsum_dense.py | {
"start": 556,
"end": 60503
} | class ____(Layer):
"""A layer that uses `einsum` as the backing computation.
This layer can perform einsum calculations of arbitrary dimensionality.
Args:
equation: An equation describing the einsum to perform.
This equation must be a valid einsum string of the form
`ab,bc-... | EinsumDense |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 743221,
"end": 744295
} | class ____(sgqlc.types.Type, Node, RepositoryNode):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"created_at",
"description",
"emoji",
"emoji_html",
"is_answerable",
"name",
"slug",
"updated_at... | DiscussionCategory |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/psycopg.py | {
"start": 11020,
"end": 11196
} | class ____(PGIdentifierPreparer):
pass
def _log_notices(diagnostic):
logger.info("%s: %s", diagnostic.severity, diagnostic.message_primary)
| PGIdentifierPreparer_psycopg |
python | dagster-io__dagster | python_modules/dagster/dagster/_daemon/daemon.py | {
"start": 10693,
"end": 12653
} | class ____(DagsterDaemon):
def __init__(self, settings: Mapping[str, Any]) -> None:
super().__init__()
self._exit_stack = ExitStack()
self._threadpool_executor: Optional[InheritContextThreadPoolExecutor] = None
self._submit_threadpool_executor: Optional[InheritContextThreadPoolExecut... | SensorDaemon |
python | pydantic__pydantic | pydantic/types.py | {
"start": 57603,
"end": 58064
} | class ____(str, Enum):
amex = 'American Express'
mastercard = 'Mastercard'
visa = 'Visa'
other = 'other'
def __str__(self) -> str:
return self.value
@deprecated(
'The `PaymentCardNumber` class is deprecated, use `pydantic_extra_types` instead. '
'See https://docs.pydantic.dev/late... | PaymentCardBrand |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_polymorphic_rel.py | {
"start": 69337,
"end": 74816
} | class ____(
_PolymorphicTestBase, _PolymorphicPolymorphic
):
__dialect__ = "default"
def test_with_polymorphic_two_future_default_wp(self):
"""test #7262
compare to
test_with_polymorphic_two_future_adhoc_wp
"""
sess = fixture_session()
def go():
... | PolymorphicPolymorphicTest |
python | matplotlib__matplotlib | lib/matplotlib/backends/_backend_tk.py | {
"start": 40595,
"end": 40954
} | class ____(backend_tools.RubberbandBase):
def draw_rubberband(self, x0, y0, x1, y1):
NavigationToolbar2Tk.draw_rubberband(
self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)
def remove_rubberband(self):
NavigationToolbar2Tk.remove_rubberband(
self._make_cla... | RubberbandTk |
python | getsentry__sentry | src/sentry/auth_v2/endpoints/user_login_view.py | {
"start": 300,
"end": 541
} | class ____(AuthV2Endpoint):
owner = ApiOwner.ENTERPRISE
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def get(self, request: Request) -> Response:
return Response({"message": "Hello world"})
| UserLoginView |
python | crytic__slither | slither/slithir/operations/phi.py | {
"start": 530,
"end": 1686
} | class ____(OperationWithLValue):
def __init__(
self, left_variable: Union[LocalIRVariable, StateIRVariable], nodes: Set["Node"]
) -> None:
# When Phi operations are created the
# correct indexes of the variables are not yet computed
# We store the nodes where the variables are wr... | Phi |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 5324,
"end": 5525
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
return np.log(metafeatures.get_value("NumberOfFeatures"))
@helper_functions.define("MissingValues")
| LogNumberOfFeatures |
python | getsentry__sentry | tests/sentry/rules/history/test_preview.py | {
"start": 33563,
"end": 36007
} | class ____(TestCase, SnubaTestCase):
def test_get_first_seen(self) -> None:
prev_hour = timezone.now() - timedelta(hours=1)
two_hours = timezone.now() - timedelta(hours=2)
self.store_event(project_id=self.project.id, data={"timestamp": prev_hour.isoformat()})
event = self.store_event... | GetEventsTest |
python | getsentry__sentry | tests/sentry/integrations/slack/tasks/test_tasks.py | {
"start": 989,
"end": 20338
} | class ____(TestCase):
def setUp(self) -> None:
self.integration = install_slack(self.organization)
self.uuid = uuid4().hex
@pytest.fixture(autouse=True)
def mock_chat_scheduleMessage(self):
with mock_slack_response(
"chat_scheduleMessage",
body={"ok": True, "... | SlackTasksTest |
python | sympy__sympy | bin/test_optional_dependencies.py | {
"start": 276,
"end": 2802
} | class ____(Exception):
pass
test_list = [
# numpy
'*numpy*',
'sympy/core/',
'sympy/matrices/',
'sympy/physics/quantum/',
'sympy/utilities/tests/test_lambdify.py',
'sympy/physics/control/',
# scipy
'*scipy*',
# matplotlib
'sympy/plotting/',
# llvmlite
'*llvm*'... | TestsFailedError |
python | dagster-io__dagster | python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py | {
"start": 40706,
"end": 41859
} | class ____(ColumnConstraint):
"""A column constraint that ensures all values in a pandas column are unique.
Args:
ignore_missing_vals (bool): If true, this constraint will enforce the constraint on non missing values.
"""
def __init__(self, ignore_missing_vals):
description = "Column m... | UniqueColumnConstraint |
python | pytorch__pytorch | torch/ao/quantization/observer.py | {
"start": 65286,
"end": 65865
} | class ____(Granularity):
"""
Represents per-channel group granularity in quantization.
This granularity type calculates different quantization parameters
for each group of <group_size> elements.
For example if the input tensor is shape [8, 16], and the group size is 4, then
the input tensor is... | PerGroup |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail_baseConfig.py | {
"start": 990,
"end": 1111
} | class ____(BaseModel):
class Config:
extra = 1 # type: ignore[pydantic-config]
extra = 1
| BadExtraModel |
python | great-expectations__great_expectations | great_expectations/core/data_context_key.py | {
"start": 2073,
"end": 2502
} | class ____(DataContextKey):
"""A simple DataContextKey with just a single string value"""
def __init__(self, key) -> None:
self._key = key
@override
def to_tuple(self):
return (self._key,)
@override
def to_fixed_length_tuple(self):
return self.to_tuple()
@classmet... | StringKey |
python | joke2k__faker | faker/providers/date_time/nl_NL/__init__.py | {
"start": 46,
"end": 782
} | class ____(DateTimeProvider):
DAY_NAMES = {
"0": "zondag",
"1": "maandag",
"2": "dinsdag",
"3": "woensdag",
"4": "donderdag",
"5": "vrijdag",
"6": "zaterdag",
}
MONTH_NAMES = {
"01": "januari",
"02": "februari",
"03": "maart",
... | Provider |
python | tensorflow__tensorflow | tensorflow/python/ops/io_ops.py | {
"start": 14749,
"end": 15675
} | class ____(ReaderBase):
"""A Reader that outputs the entire contents of a file as a value.
To use, enqueue filenames in a Queue. The output of Read will
be a filename (key) and the contents of that file (value).
See ReaderBase for supported methods.
@compatibility(eager)
Readers are not compatible with ... | WholeFileReader |
python | pennersr__django-allauth | allauth/mfa/webauthn/views.py | {
"start": 3616,
"end": 4691
} | class ____(RedirectAuthenticatedUserMixin, FormView):
form_class = LoginWebAuthnForm
def get(self, request, *args, **kwargs):
if get_account_adapter().is_ajax(request):
request_options = auth.begin_authentication(user=None)
data = {"request_options": request_options}
... | LoginWebAuthnView |
python | coleifer__peewee | tests/regressions.py | {
"start": 34446,
"end": 34864
} | class ____(ModelTestCase):
requires = [NoPK]
def test_no_pk_hash_regression(self):
npk = NoPK.create(data=1)
npk_db = NoPK.get(NoPK.data == 1)
# When a model does not define a primary key, we cannot test equality.
self.assertTrue(npk != npk_db)
# Their hash is the same,... | TestNoPKHashRegression |
python | numba__numba | numba/tests/test_ufuncs.py | {
"start": 58357,
"end": 59070
} | class ____(_LoopTypesTester):
_ufuncs = [np.reciprocal] # issue #757
_required_types = 'bBhHiIlLqQfdFD'
_skip_types = 'mMO' + _LoopTypesTester._skip_types
def _arg_for_type(self, a_letter_type, index=0):
res = super(self.__class__, self)._arg_for_type(a_letter_type,
... | TestLoopTypesReciprocal |
python | pytorch__pytorch | test/dynamo/test_streams.py | {
"start": 868,
"end": 15635
} | class ____(torch._dynamo.test_case.TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
@classmethod
def tearDownClass(cls):
super().tearDownClass()
@requires_cuda
def test_stream_weakref(self):
s = torch.Stream()
weakref.ref(s)
@requires_cuda
... | TestStreams |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/traversals.py | {
"start": 2069,
"end": 5929
} | class ____(HasTraverseInternals):
"""attribute-wide operations that are useful for classes that use
__slots__ and therefore can't operate on their attributes in a dictionary.
"""
__slots__ = ()
if typing.TYPE_CHECKING:
def _generated_shallow_copy_traversal(self, other: Self) -> None: ..... | HasShallowCopy |
python | Textualize__textual | tests/input/test_input_key_movement_actions.py | {
"start": 177,
"end": 6772
} | class ____(App[None]):
"""Input widget testing app."""
def compose(self) -> ComposeResult:
for value, input_id in (
("", "empty"),
("Shiny", "single-word"),
("Curse your sudden but inevitable betrayal", "multi-no-punctuation"),
(
"We have ... | InputTester |
python | ipython__ipython | IPython/core/completer.py | {
"start": 18740,
"end": 19079
} | class ____(_MatcherResultBase, TypedDict):
"""Result of new-style completion matcher."""
# note: TypedDict is added again to the inheritance chain
# in order to get __orig_bases__ for documentation
#: List of candidate completions
completions: Sequence[SimpleCompletion] | Iterator[SimpleCompletion... | SimpleMatcherResult |
python | has2k1__plotnine | plotnine/scales/limits.py | {
"start": 3578,
"end": 3660
} | class ____(_lim):
"""
Color limits
"""
aesthetic = "color"
| colorlim |
python | spack__spack | lib/spack/spack/util/environment.py | {
"start": 14754,
"end": 16345
} | class ____(NameModifier):
def execute(self, env: MutableMapping[str, str]):
tty.debug(f"PruneDuplicatePaths: {self.name}", level=3)
environment_value = env.get(self.name, "")
directories = environment_value.split(self.separator) if environment_value else []
directories = prune_duplic... | PruneDuplicatePaths |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/mirror_gnu_broken/package.py | {
"start": 299,
"end": 598
} | class ____(AutotoolsPackage, GNUMirrorPackage):
"""Simple GNU package"""
homepage = "https://www.gnu.org/software/make/"
url = "https://ftpmirror.gnu.org/make/make-4.2.1.tar.gz"
version("4.2.1", sha256="e40b8f018c1da64edd1cc9a6fce5fa63b2e707e404e20cad91fbae337c98a5b7")
| MirrorGnuBroken |
python | huggingface__transformers | src/transformers/utils/hub.py | {
"start": 1884,
"end": 26461
} | class ____(TypedDict, total=False):
cache_dir: str | os.PathLike | None
force_download: bool
proxies: dict[str, str] | None
local_files_only: bool
token: str | bool | None
revision: str | None
subfolder: str
commit_hash: str | None
def is_offline_mode():
# Import inside the functio... | DownloadKwargs |
python | sanic-org__sanic | sanic/worker/restarter.py | {
"start": 175,
"end": 3038
} | class ____:
def restart(
self,
transient_processes: list[WorkerProcess],
durable_processes: list[WorkerProcess],
process_names: Optional[list[str]] = None,
restart_order=RestartOrder.SHUTDOWN_FIRST,
**kwargs,
) -> None:
"""Restart the worker processes.
... | Restarter |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/links/test_base_aws.py | {
"start": 1471,
"end": 3921
} | class ____:
@pytest.mark.parametrize(
("region_name", "aws_partition", "keywords", "expected_value"),
[
("eu-central-1", "aws", {}, {"region_name": "eu-central-1", "aws_domain": "aws.amazon.com"}),
("cn-north-1", "aws-cn", {}, {"region_name": "cn-north-1", "aws_domain": "amaz... | TestBaseAwsLink |
python | OmkarPathak__pygorithm | tests/test_math.py | {
"start": 687,
"end": 1111
} | class ____(unittest.TestCase):
def test_dec_to_bin(self):
self.assertEqual(conversion.decimal_to_binary(2), '10')
def test_bin_to_dec(self):
self.assertEqual(conversion.binary_to_decimal('1010'), 10)
def test_dec_to_hex(self):
self.assertEqual(conversion.decimal_to_hex(30), '1E')
... | TestConversion |
python | ApeWorX__ape | src/ape/contracts/base.py | {
"start": 34742,
"end": 35722
} | class ____:
"""
A wrapper used when multiple events have the same so that
you can still create mock-logs.
"""
def __init__(self, events: list[ContractEvent]):
self.events = events
def __call__(self, *args, **kwargs) -> MockContractLog:
"""
Create a mock contract log usi... | ContractEventWrapper |
python | wandb__wandb | wandb/old/summary.py | {
"start": 383,
"end": 5877
} | class ____:
"""Nested dict-like object that proxies read and write operations through a root object.
This lets us do synchronous serialization and lazy loading of large values.
"""
def __init__(self, root=None, path=()):
self._path = tuple(path)
if root is None:
self._root ... | SummarySubDict |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/strategies.py | {
"start": 40024,
"end": 41842
} | class ____:
"""semi-serializable loader object used by LazyLoader
Historically, this object would be carried along with instances that
needed to run lazyloaders, so it had to be serializable to support
cached instances.
this is no longer a general requirement, and the case where this object
is... | _LoadLazyAttribute |
python | facebookresearch__faiss | tests/test_index_composite.py | {
"start": 28620,
"end": 29744
} | class ____(unittest.TestCase):
def do_test(self, factory_string):
ds = SyntheticDataset(32, 1000, 100, 10)
index = faiss.index_factory(ds.d, factory_string)
index.train(ds.get_train())
index.add(ds.get_database())
index.nprobe
index.nprobe = 10
Dref, Iref ... | TestSearchAndGetCodes |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 3487,
"end": 3570
} | class ____:
def mixed(self, first, second, *, third, fourth):
pass
| Mixed |
python | kamyu104__LeetCode-Solutions | Python/backspace-string-compare.py | {
"start": 52,
"end": 587
} | class ____(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
def findNextChar(S):
skip = 0
for i in reversed(xrange(len(S))):
if S[i] == '#':
skip += 1
... | Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/agent/workflow/react_agent.py | {
"start": 1343,
"end": 11861
} | class ____(BaseWorkflowAgent):
"""React agent implementation."""
reasoning_key: str = "current_reasoning"
output_parser: ReActOutputParser = Field(
default_factory=ReActOutputParser, description="The react output parser"
)
formatter: ReActChatFormatter = Field(
default_factory=defau... | ReActAgent |
python | pennersr__django-allauth | allauth/socialaccount/providers/frontier/provider.py | {
"start": 322,
"end": 683
} | class ____(ProviderAccount):
def get_profile_url(self):
return None
def get_avatar_url(self):
return "https://www.gravatar.com/avatar/%s?%s" % (
hashlib.sha256(
self.account.extra_data.get("email").lower().encode("utf-8")
).hexdigest(),
urlenc... | FrontierAccount |
python | scipy__scipy | scipy/fft/tests/test_basic.py | {
"start": 17201,
"end": 19076
} | class ____:
threads = 16
input_shape = (800, 200)
def _test_mtsame(self, func, *args, xp=None):
def worker(args, q):
q.put(func(*args))
q = queue.Queue()
expected = func(*args)
# Spin off a bunch of threads to call the same function simultaneously
t = [... | TestFFTThreadSafe |
python | pydantic__pydantic | tests/mypy/outputs/mypy-default_ini/plugin_success.py | {
"start": 7543,
"end": 7774
} | class ____(BaseModel):
model_config = ConfigDict(populate_by_name=True)
my_field: str = Field(alias='my_alias')
m5 = Model5(my_field='foo')
# MYPY: error: Unexpected keyword argument "my_field" for "Model5" [call-arg]
| Model5 |
python | joke2k__faker | faker/providers/passport/__init__.py | {
"start": 187,
"end": 1507
} | class ____(BaseProvider):
"""Implement default Passport provider for Faker."""
passport_number_formats: ElementsType = ()
def passport_dob(self) -> datetime.date:
"""Generate a datetime date of birth."""
birthday = self.generator.date_of_birth()
return birthday
def passport_ow... | Provider |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/execution_api/test_app.py | {
"start": 1753,
"end": 4386
} | class ____:
def test_correlation_id_echoed_in_response_headers(self, client):
"""Test that correlation-id from request is echoed back in response headers."""
correlation_id = "test-correlation-id-12345"
response = client.get("/execution/health", headers={"correlation-id": correlation_id})
... | TestCorrelationIdMiddleware |
python | openai__openai-python | src/openai/types/responses/web_search_preview_tool.py | {
"start": 241,
"end": 917
} | class ____(BaseModel):
type: Literal["approximate"]
"""The type of location approximation. Always `approximate`."""
city: Optional[str] = None
"""Free text input for the city of the user, e.g. `San Francisco`."""
country: Optional[str] = None
"""
The two-letter [ISO country code](https://e... | UserLocation |
python | huggingface__transformers | src/transformers/models/textnet/modeling_textnet.py | {
"start": 7949,
"end": 8111
} | class ____(PreTrainedModel):
config: TextNetConfig
base_model_prefix = "textnet"
main_input_name = "pixel_values"
@auto_docstring
| TextNetPreTrainedModel |
python | django__django | tests/distinct_on_fields/tests.py | {
"start": 393,
"end": 7866
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.t1 = Tag.objects.create(name="t1")
cls.t2 = Tag.objects.create(name="t2", parent=cls.t1)
cls.t3 = Tag.objects.create(name="t3", parent=cls.t1)
cls.t4 = Tag.objects.create(name="t4", parent=cls.t3)
cls.t5 = Tag... | DistinctOnTests |
python | bokeh__bokeh | release/action.py | {
"start": 1225,
"end": 1326
} | class ____(ActionReturn):
""""""
kind = ActionResult.SKIP
ui = staticmethod(skipped)
| SKIPPED |
python | doocs__leetcode | solution/3000-3099/3095.Shortest Subarray With OR at Least K I/Solution.py | {
"start": 0,
"end": 674
} | class ____:
def minimumSubarrayLength(self, nums: List[int], k: int) -> int:
n = len(nums)
cnt = [0] * 32
ans = n + 1
s = i = 0
for j, x in enumerate(nums):
s |= x
for h in range(32):
if x >> h & 1:
cnt[h] += 1
... | Solution |
python | huggingface__transformers | src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py | {
"start": 3542,
"end": 3710
} | class ____(Qwen2VLConfig):
model_type = "qwen2_5_vl"
sub_configs = {"vision_config": Qwen2_5_VLVisionConfig, "text_config": Qwen2_5_VLTextConfig}
| Qwen2_5_VLConfig |
python | scikit-image__scikit-image | benchmarks/benchmark_filters.py | {
"start": 245,
"end": 536
} | class ____:
"""Benchmark for filter routines in scikit-image."""
def setup(self):
self.image = np.random.random((4000, 4000))
self.image[:2000, :2000] += 1
self.image[3000:, 3000] += 0.5
def time_sobel(self):
filters.sobel(self.image)
| FiltersSuite |
python | tensorflow__tensorflow | tensorflow/python/eager/benchmarks/resnet50/hvp_test.py | {
"start": 2868,
"end": 4375
} | class ____(tf.test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
("forward_over_back_eager", _forward_over_back_hvp),
("forward_over_back_function", tf.function(_forward_over_back_hvp)),
("tf_gradients", tf.function(_tf_gradients_forward_over_back_hvp)),
("back_over_back... | HVPTest |
python | django__django | tests/admin_filters/models.py | {
"start": 1699,
"end": 1917
} | class ____(models.Model):
code = models.CharField(max_length=4, unique=True)
description = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return self.description
| Department |
python | kamyu104__LeetCode-Solutions | Python/kth-largest-element-in-an-array.py | {
"start": 160,
"end": 1594
} | class ____(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def nth_element(nums, n, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target, compare):
mid = left
... | Solution |
python | doocs__leetcode | solution/1600-1699/1631.Path With Minimum Effort/Solution.py | {
"start": 639,
"end": 1330
} | class ____:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
m, n = len(heights), len(heights[0])
uf = UnionFind(m * n)
e = []
dirs = (0, 1, 0)
for i in range(m):
for j in range(n):
for a, b in pairwise(dirs):
x, y ... | Solution |
python | getsentry__sentry | tests/sentry/core/endpoints/scim/test_scim_user_index.py | {
"start": 20737,
"end": 22023
} | class ____(SCIMAzureTestCase):
def test_user_index_get_no_active(self) -> None:
member = self.create_member(organization=self.organization, email="test.user@okta.local")
url = reverse("sentry-api-0-organization-scim-member-index", args=[self.organization.slug])
response = self.client.get(
... | SCIMMemberIndexAzureTests |
python | getsentry__sentry | tests/sentry/api/endpoints/test_user_subscriptions.py | {
"start": 481,
"end": 2518
} | class ____(APITestCase):
endpoint = "sentry-api-0-user-subscriptions"
method = "put"
@pytest.fixture(autouse=True)
def enable_newsletter(self) -> Generator[None]:
with newsletter.backend.test_only__downcast_to(DummyNewsletter).enable():
yield
def setUp(self) -> None:
se... | UserSubscriptionsNewsletterTest |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 231656,
"end": 240818
} | class ____(torch.nn.Module):
def forward(self, L_self_modules_FX_CONST_FOLDED_ATTRS_parameters_0_: "f32[3, 3, 3]", L_self_modules_FX_CONST_FOLDED_ATTRS_parameters_1_: "f32[3, 3, 3]", L_flat_tangents_1_: "f32[3, 3, 3]"):
l_self_modules_fx_const_folded_attrs_parameters_0_ = L_self_modules_FX_CONST_FOLDED_ATTR... | GraphModule |
python | pypa__pip | src/pip/_vendor/urllib3/util/timeout.py | {
"start": 459,
"end": 10168
} | class ____(object):
"""Timeout configuration.
Timeouts can be defined as a default for a pool:
.. code-block:: python
timeout = Timeout(connect=2.0, read=7.0)
http = PoolManager(timeout=timeout)
response = http.request('GET', 'http://example.com/')
Or per-request (which override... | Timeout |
python | dagster-io__dagster | python_modules/libraries/dagster-sling/dagster_sling/dagster_sling_translator.py | {
"start": 384,
"end": 21428
} | class ____:
target_prefix: str = "target"
@public
def get_asset_spec(self, stream_definition: Mapping[str, Any]) -> AssetSpec:
"""A function that takes a stream definition from a Sling replication config and returns a
Dagster AssetSpec.
The stream definition is a dictionary key/val... | DagsterSlingTranslator |
python | huggingface__transformers | src/transformers/models/gptj/modeling_gptj.py | {
"start": 19029,
"end": 30479
} | class ____(GPTJPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.embed_dim = config.n_embd
self.vocab_size = config.vocab_size
self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
self.drop = nn.Dropout(config.embd_pdrop)
self.h = nn.M... | GPTJModel |
python | astropy__astropy | astropy/coordinates/solar_system.py | {
"start": 2413,
"end": 18562
} | class ____(ScienceState):
"""Default ephemerides for calculating positions of Solar-System bodies.
This can be one of the following:
- 'builtin': polynomial approximations to the orbital elements.
- 'dexxx[s]', for a JPL dynamical model, where xxx is the three digit
version number (e.g. de430), ... | solar_system_ephemeris |
python | tensorflow__tensorflow | tensorflow/python/framework/combinations.py | {
"start": 1844,
"end": 2998
} | class ____(test_combinations.TestCombination):
"""Control the execution of the test in TF1.x and TF2.
If TF2 is enabled then a test with TF1 test is going to be skipped and vice
versa.
Test targets continuously run in TF2 thanks to the tensorflow.v2 TAP target.
A test can be run in TF2 with bazel by passing... | TFVersionCombination |
python | astropy__astropy | astropy/visualization/tests/test_interval.py | {
"start": 3919,
"end": 6086
} | class ____(TestInterval):
# Make sure intervals work with MaskedArray
data = np.concatenate((np.linspace(-20.0, 60.0, 100), np.full(100, 1e6)))
data = Masked(data, data > 1000)
def test_zscale():
np.random.seed(42)
data = np.random.randn(100, 100) * 5 + 10
interval = ZScaleInterval()
vmin,... | TestIntervalMaskedNDArray |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 284560,
"end": 285176
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("DiscussionEdge"), graphql_name="edges"
)
nodes = sgqlc.ty... | DiscussionConnection |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 374292,
"end": 377446
} | class ____(Request):
"""
Request to stop a running task
:param force: If not true, call fails if the task status is not 'in_progress'
:type force: bool
:param task: Task ID
:type task: str
:param status_reason: Reason for status change
:type status_reason: str
:param status_message:... | StopRequest |
python | doocs__leetcode | solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.py | {
"start": 0,
"end": 476
} | class ____:
def maxSum(self, nums: List[int], k: int) -> int:
mod = 10**9 + 7
cnt = [0] * 31
for x in nums:
for i in range(31):
if x >> i & 1:
cnt[i] += 1
ans = 0
for _ in range(k):
x = 0
for i in range(3... | Solution |
python | huggingface__transformers | tests/utils/test_model_output.py | {
"start": 879,
"end": 984
} | class ____(ModelOutput):
a: float
b: float | None = None
c: float | None = None
| ModelOutputTest |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/service/local_workers_test.py | {
"start": 10891,
"end": 17952
} | class ____(data_service_test_base.TestBase,
parameterized.TestCase):
"""Tests garbage collecting unused local worker tasks.
The user typically creates an iterator in each epoch. This should delete the
previous iterator and releases the resources of it.
"""
@combinations.gen... | LocalTaskGarbageCollectTest |
python | django__django | tests/gis_tests/test_ptr.py | {
"start": 130,
"end": 2398
} | class ____(SimpleTestCase):
def test(self):
destructor_mock = mock.Mock()
class NullPointerException(Exception):
pass
class FakeGeom1(CPointerBase):
null_ptr_exception_class = NullPointerException
class FakeGeom2(FakeGeom1):
ptr_type = ctypes.PO... | CPointerBaseTests |
python | pytorch__pytorch | torch/sparse/semi_structured.py | {
"start": 910,
"end": 16031
} | class ____(torch.Tensor):
"""
This class implements semi-structured sparsity as a Tensor subclass.
Semi-structured sparsity describes a sparsity pattern where n in every 2n elements are sparse,
depending on the datatype. It is also referred to as 2:4 sparsity or fine-grained
structured sparsity.
... | SparseSemiStructuredTensor |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_basic.py | {
"start": 66502,
"end": 70491
} | class ____(fixtures.MappedTest):
"""test the construction of mapper.primary_key when an inheriting
relationship joins on a column other than primary key column."""
run_inserts = "once"
run_deletes = None
@classmethod
def define_tables(cls, metadata):
global person_table, employee_table... | DistinctPKTest |
python | django__django | tests/gis_tests/geoadmin/tests.py | {
"start": 2454,
"end": 3280
} | class ____(GeoAdminTest):
admin_site = site_gis # GISModelAdmin
def test_default_gis_widget_kwargs(self):
geoadmin = self.admin_site.get_model_admin(City)
form = geoadmin.get_changelist_form(None)()
widget = form["point"].field.widget
self.assertEqual(widget.attrs["default_lat"... | GISAdminTests |
python | doocs__leetcode | solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.py | {
"start": 0,
"end": 817
} | class ____:
def maximumDetonation(self, bombs: List[List[int]]) -> int:
n = len(bombs)
g = [[] for _ in range(n)]
for i in range(n - 1):
x1, y1, r1 = bombs[i]
for j in range(i + 1, n):
x2, y2, r2 = bombs[j]
dist = hypot(x1 - x2, y1 - y2... | Solution |
python | apache__airflow | providers/standard/tests/unit/standard/operators/test_python.py | {
"start": 87338,
"end": 96025
} | class ____:
@pytest.mark.parametrize(
("ignore_downstream_trigger_rules", "with_teardown", "should_skip", "expected"),
[
(False, True, True, ["op2"]),
(False, True, False, []),
(False, False, True, ["op2"]),
(False, False, False, []),
(True... | TestShortCircuitWithTeardown |
python | davidhalter__jedi | jedi/api/helpers.py | {
"start": 6787,
"end": 18982
} | class ____:
def __init__(self, bracket_leaf, children, position):
self.bracket_leaf = bracket_leaf
self._children = children
self._position = position
@property
def index(self):
return _get_index_and_key(self._children, self._position)[0]
@property
def keyword_name_... | CallDetails |
python | tensorflow__tensorflow | tensorflow/python/distribute/distribute_lib.py | {
"start": 37375,
"end": 38913
} | class ____(
collections.namedtuple("RunOptions", [
"experimental_enable_dynamic_batch_size",
"experimental_bucketizing_dynamic_shape",
"experimental_xla_options",
])):
"""Run options for `strategy.run`.
This can be used to hold some strategy specific configs.
Attributes:
expe... | RunOptions |
python | apache__airflow | airflow-ctl/tests/airflow_ctl/ctl/commands/test_connections_command.py | {
"start": 1141,
"end": 4510
} | class ____:
connection_id = "test_connection"
export_file_name = "exported_json.json"
parser = cli_parser.get_parser()
connection_collection_response = ConnectionCollectionResponse(
connections=[
ConnectionResponse(
connection_id=connection_id,
conn_ty... | TestCliConnectionCommands |
python | apache__airflow | providers/microsoft/winrm/src/airflow/providers/microsoft/winrm/operators/winrm.py | {
"start": 1519,
"end": 5154
} | class ____(BaseOperator):
"""
WinRMOperator to execute commands on given remote host using the winrm_hook.
:param winrm_hook: predefined ssh_hook to use for remote execution
:param ssh_conn_id: connection id from airflow Connections
:param remote_host: remote host to connect
:param command: com... | WinRMOperator |
python | joke2k__faker | faker/providers/company/nl_NL/__init__.py | {
"start": 45,
"end": 11847
} | class ____(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} & {{last_name}}",
"{{company_prefix}} {{last_name}}",
"{{large_company}}",
)
company_prefixes = (
"Stichting",
"Koninklijke",
"Royal",
)
company_suffi... | Provider |
python | Lightning-AI__lightning | tests/tests_pytorch/helpers/datamodules.py | {
"start": 4277,
"end": 4754
} | class ____(SklearnDataModule):
def __init__(self, num_features=16, length=800, batch_size=10):
if not _SKLEARN_AVAILABLE:
raise ImportError(str(_SKLEARN_AVAILABLE))
from sklearn.datasets import make_regression
x, y = make_regression(n_samples=length, n_features=num_features, ra... | RegressDataModule |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 99364,
"end": 99450
} | class ____(_numpy_info):
section = 'Numeric'
modulename = 'Numeric'
| Numeric_info |
python | qdrant__qdrant-client | qdrant_client/local/multi_distances.py | {
"start": 287,
"end": 1221
} | class ____:
def __init__(
self,
positive: Optional[list[list[list[float]]]] = None, # list of matrices
negative: Optional[list[list[list[float]]]] = None, # list of matrices
strategy: Optional[models.RecommendStrategy] = None,
):
assert strategy is not None, "Recommend ... | MultiRecoQuery |
python | kamyu104__LeetCode-Solutions | Python/find-the-longest-valid-obstacle-course-at-each-position.py | {
"start": 3009,
"end": 3559
} | class ____(object):
def longestObstacleCourseAtEachPosition(self, obstacles):
"""
:type obstacles: List[int]
:rtype: List[int]
"""
sorted_obstacles = sorted(set(obstacles))
lookup = {x:i for i, x in enumerate(sorted_obstacles)}
segment_tree = SegmentTree(len(l... | Solution2_TLE |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 17073,
"end": 18539
} | class ____(nodes.Inline, nodes.FixedTextElement):
"""Node for references to manpages."""
def setup(app: Sphinx) -> ExtensionMetadata:
app.add_node(toctree)
app.add_node(desc)
app.add_node(desc_signature)
app.add_node(desc_signature_line)
app.add_node(desc_content)
app.add_node(desc_inline... | manpage |
python | google__pytype | pytype/load_pytd.py | {
"start": 8011,
"end": 11236
} | class ____:
"""Resolve symbols in a pytd tree."""
def __init__(self, builtins_ast):
self.builtins_ast = builtins_ast
self.allow_singletons = False
def _lookup(self, visitor, mod_ast, lookup_ast):
if lookup_ast:
visitor.EnterTypeDeclUnit(lookup_ast)
mod_ast = mod_ast.Visit(visitor)
retu... | _Resolver |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_dataflow.py | {
"start": 6925,
"end": 14054
} | class ____:
@pytest.mark.parametrize(
("job_current_state", "fail_on_terminal_state"),
[
(DataflowJobStatus.JOB_STATE_RUNNING, True),
(DataflowJobStatus.JOB_STATE_RUNNING, False),
(DataflowJobStatus.JOB_STATE_DONE, False),
],
)
@mock.patch("airflow... | TestDataflowJobMetricsSensor |
python | pytorch__pytorch | torch/distributed/_shard/sharding_spec/chunk_sharding_spec.py | {
"start": 902,
"end": 9309
} | class ____(ShardingSpec):
"""
This is a type of PlacementSpec that defines the placement as being sharded
across multiple devices. In particular, it represents sharding a Tensor
along a single dimension into equal chunks (similar to :meth:`torch.chunk`).
The semantics of how a tensor is partitioned... | ChunkShardingSpec |
python | streamlit__streamlit | lib/streamlit/elements/lib/column_types.py | {
"start": 3151,
"end": 3283
} | class ____(TypedDict):
type: Literal["checkbox"]
SelectboxOptionValue: TypeAlias = str | int | float | bool
| CheckboxColumnConfig |
python | pytorch__pytorch | torch/fx/experimental/migrate_gradual_types/constraint.py | {
"start": 710,
"end": 1175
} | class ____(Constraint):
def __init__(self, disjuncts):
"""
:param disjuncts: Disjunction of constraints
"""
self.disjuncts = disjuncts
def __eq__(self, other):
if isinstance(other, Disj):
return (
self.disjuncts == other.disjuncts and self.dis... | Disj |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_experiment_service.py | {
"start": 3426,
"end": 5132
} | class ____:
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_no_default_project_id
):
self.hook = ExperimentHook(gcp_conn_id=TEST_GCP_CONN_ID)
@mock.patch(EXPERIMENT_SERVICE_STRING.format("aiplatform.init"))
... | TestExperimentWithoutDefaultProjectIdHook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.