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 | getsentry__sentry | tests/sentry/issues/endpoints/test_organization_group_index.py | {
"start": 3392,
"end": 114619
} | class ____(APITestCase, SnubaTestCase, SearchIssueTestMixin):
endpoint = "sentry-api-0-organization-group-index"
def setUp(self) -> None:
super().setUp()
self.min_ago = before_now(minutes=1)
def _parse_links(self, header: str) -> dict[str | None, dict[str, str | None]]:
# links com... | GroupListTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol53.py | {
"start": 3324,
"end": 3520
} | class ____(Proto_ContraRecurs):
# This should generate a reportIncompatibleMethodOverride error.
def m[T: Impl_ContraGenericExplicit1](self: T, x: T) -> None: ...
| Impl_ContraGenericExplicit1 |
python | python-openxml__python-docx | tests/oxml/test__init__.py | {
"start": 4006,
"end": 4050
} | class ____(BaseOxmlElement):
pass
| CustElmCls |
python | pypa__warehouse | warehouse/organizations/models.py | {
"start": 22403,
"end": 24435
} | class ____(db.Model):
__tablename__ = "organization_manual_activations"
__repr__ = make_repr("organization_id", "seat_limit", "expires")
organization_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True),
ForeignKey("organizations.id", ondelete="CASCADE"),
primary_key=True,
... | OrganizationManualActivation |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/nn_functional.py | {
"start": 10620,
"end": 12209
} | class ____(Operator):
"""Operator for torch.nn.functional.dropout."""
def __init__(self):
super().__init__("torch.nn.functional.dropout")
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "torch.nn.functional.dropout"
def can_pr... | DropoutOperator |
python | spyder-ide__spyder | spyder/plugins/variableexplorer/widgets/main_widget.py | {
"start": 2850,
"end": 25245
} | class ____(ShellConnectMainWidget):
# PluginMainWidget class constants
ENABLE_SPINNER = True
SHOW_MESSAGE_WHEN_EMPTY = True
IMAGE_WHEN_EMPTY = "variable-explorer"
MESSAGE_WHEN_EMPTY = _("No variables to show")
DESCRIPTION_WHEN_EMPTY = _(
"Run code in the Editor or IPython console to see... | VariableExplorerWidget |
python | walkccc__LeetCode | solutions/2224. Minimum Number of Operations to Convert Time/2224.py | {
"start": 0,
"end": 322
} | class ____:
def convertTime(self, current: str, correct: str) -> int:
ops = [60, 15, 5, 1]
def getMinutes(s: str) -> int:
return int(s[:2]) * 60 + int(s[3:])
diff = getMinutes(correct) - getMinutes(current)
ans = 0
for op in ops:
ans += diff // op
diff %= op
return ans
| Solution |
python | PrefectHQ__prefect | src/prefect/exceptions.py | {
"start": 11984,
"end": 12292
} | class ____(PrefectException):
"""
Raised when an event exceeds the configured maximum size.
"""
def __init__(self, size: int, maximum: int):
super().__init__(f"Event is too large to emit ({size} > {maximum} bytes)")
self.size = size
self.maximum = maximum
| EventTooLarge |
python | nedbat__coveragepy | tests/test_config.py | {
"start": 22884,
"end": 36466
} | class ____(UsingModulesMixin, CoverageTest):
"""Tests of the config file settings in particular."""
# This sample file tries to use lots of variation of syntax...
# The {section} placeholder lets us nest these settings in another file.
LOTSA_SETTINGS = """\
# This is a settings file for coverag... | ConfigFileTest |
python | pandas-dev__pandas | pandas/core/internals/blocks.py | {
"start": 62528,
"end": 72963
} | class ____(EABackedBlock):
"""
Block for holding extension types.
Notes
-----
This holds all 3rd-party extension array types. It's also the immediate
parent class for our internal extension types' blocks.
ExtensionArrays are limited to 1-D.
"""
values: ExtensionArray
def fill... | ExtensionBlock |
python | ApeWorX__ape | src/ape/exceptions.py | {
"start": 17723,
"end": 18914
} | class ____(ChainError):
"""
Raised when a contract is not found at an address.
"""
# TODO: In 0.9, pass in provider object directly (instead of network choice + name)
def __init__(self, address: "AddressType", has_explorer: bool, network_choice: str):
msg = f"Failed to get contract type for... | ContractNotFoundError |
python | redis__redis-py | redis/commands/search/querystring.py | {
"start": 5820,
"end": 5998
} | class ____(Node):
"""
Create an intersection node. All children need to be satisfied in order for
this node to evaluate as true
"""
JOINSTR = " "
| IntersectNode |
python | getsentry__sentry | src/sentry/hybridcloud/tasks/deliver_webhooks.py | {
"start": 2398,
"end": 23908
} | class ____(Exception):
"""
Used to signal an expected delivery failure.
"""
pass
@instrumented_task(
name="sentry.hybridcloud.tasks.deliver_webhooks.schedule_webhook_delivery",
namespace=hybridcloud_control_tasks,
processing_deadline_duration=30,
silo_mode=SiloMode.CONTROL,
)
def sche... | DeliveryFailed |
python | pypa__warehouse | warehouse/manage/forms.py | {
"start": 5181,
"end": 5461
} | class ____(PasswordMixin, NewPasswordMixin, wtforms.Form):
__params__ = ["password", "new_password", "password_confirm"]
def __init__(self, *args, user_service, **kwargs):
super().__init__(*args, **kwargs)
self.user_service = user_service
| ChangePasswordForm |
python | allegroai__clearml | clearml/binding/frameworks/catboost_bind.py | {
"start": 295,
"end": 5836
} | class ____(PatchBaseModelIO):
_current_task = None
__patched = None
__callback_cls = None
@staticmethod
def update_current_task(task: Framework, **kwargs: Any) -> None:
PatchCatBoostModelIO._current_task = task
if not task:
return
PatchCatBoostModelIO._patch_mode... | PatchCatBoostModelIO |
python | fluentpython__example-code-2e | 08-def-type-hints/birds/protocol/swan.py | {
"start": 54,
"end": 336
} | class ____: # <2>
def honk(self, repetitions: int) -> None: # <3>
print('Honk! ' * repetitions)
def swim(self) -> None: # <4>
pass
bella = Swan()
alert(bella) # <5>
| Swan |
python | donnemartin__system-design-primer | solutions/system_design/web_crawler/web_crawler_mapreduce.py | {
"start": 55,
"end": 494
} | class ____(MRJob):
def mapper(self, _, line):
yield line, 1
def reducer(self, key, values):
total = sum(values)
if total == 1:
yield key, total
def steps(self):
"""Run the map and reduce steps."""
return [
self.mr(mapper=self.mapper,
... | RemoveDuplicateUrls |
python | falconry__falcon | examples/things_advanced.py | {
"start": 357,
"end": 555
} | class ____(Exception):
@staticmethod
def handle(req, resp, ex, params):
# TODO: Log the error, clean up, etc. before raising
raise falcon.HTTPInternalServerError()
| StorageError |
python | astropy__astropy | astropy/io/ascii/cds.py | {
"start": 1269,
"end": 8942
} | class ____(core.BaseHeader):
_subfmt = "CDS"
col_type_map = {
"e": core.FloatType,
"f": core.FloatType,
"i": core.IntType,
"a": core.StrType,
}
"The ReadMe file to construct header from."
readme = None
def get_type_map_key(self, col):
match = re.match(r... | CdsHeader |
python | kamyu104__LeetCode-Solutions | Python/remove-trailing-zeros-from-a-string.py | {
"start": 38,
"end": 253
} | class ____(object):
def removeTrailingZeros(self, num):
"""
:type num: str
:rtype: str
"""
return num[:next(i for i in reversed(xrange(len(num))) if num[i] != '0')+1]
| Solution |
python | getsentry__sentry | tests/sentry/models/test_projectownership.py | {
"start": 827,
"end": 30429
} | class ____(TestCase):
def setUp(self) -> None:
self.rpc_user = user_service.get_user(user_id=self.user.id)
self.user2 = self.create_user("bar@localhost", username="bar")
self.organization.member_set.create(user_id=self.user2.id)
self.team = self.create_team(
organization=... | ProjectOwnershipTestCase |
python | huggingface__transformers | src/transformers/models/got_ocr2/configuration_got_ocr2.py | {
"start": 5502,
"end": 9286
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GotOcr2ForConditionalGeneration`]. It is used to instantiate a
GotOcr2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yi... | GotOcr2Config |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 44199,
"end": 44848
} | class ____(dict, NonStrictDataModel):
"""
Task section params
"""
_schema = {
"additionalProperties": True,
"description": "Task section params",
"type": "object",
}
def __init__(self, *args: Any, **kwargs: Any) -> None:
self.assert_isinstance(args, "section_par... | SectionParams |
python | scipy__scipy | scipy/linalg/tests/test_basic.py | {
"start": 81352,
"end": 83698
} | class ____:
def test_types(self):
for dtype in np.typecodes['AllFloat']:
x = np.array([1, 2, 3], dtype=dtype)
tol = max(1e-15, np.finfo(dtype).eps.real * 20)
assert_allclose(norm(x), np.sqrt(14), rtol=tol)
assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
... | TestVectorNorms |
python | aimacode__aima-python | agents.py | {
"start": 28340,
"end": 36213
} | class ____(XYEnvironment):
pit_probability = 0.2 # Probability to spawn a pit in a location. (From Chapter 7.2)
# Room should be 4x4 grid of rooms. The extra 2 for walls
def __init__(self, agent_program, width=6, height=6):
super().__init__(width, height)
self.init_world(agent_program)
... | WumpusEnvironment |
python | wntrblm__nox | nox/_option_set.py | {
"start": 8564,
"end": 13626
} | class ____:
"""A set of options.
A high-level wrapper over ``argparse.ArgumentParser``. It allows for
introspection of options as well as quality-of-life features such as
finalization, callable defaults, and strongly typed namespaces for tests.
"""
def __init__(self, *args: Any, **kwargs: Any)... | OptionSet |
python | PyCQA__flake8 | src/flake8/processor.py | {
"start": 810,
"end": 16857
} | class ____:
"""Processes a file and holds state.
This processes a file by generating tokens, logical and physical lines,
and AST trees. This also provides a way of passing state about the file
to checks expecting that state. Any public attribute on this object can
be requested by a plugin. The know... | FileProcessor |
python | pypa__pipenv | pipenv/project.py | {
"start": 3138,
"end": 4052
} | class ____(json.JSONEncoder):
"""A specialized JSON encoder to convert loaded TOML data into a lock file.
This adds a few characteristics to the encoder:
* The JSON is always prettified with indents and spaces.
* TOMLKit's container elements are seamlessly encodable.
* The output is always UTF-8-e... | _LockFileEncoder |
python | RaRe-Technologies__gensim | gensim/test/test_similarities.py | {
"start": 21254,
"end": 22952
} | class ____(_TestSimilarityABC):
def setUp(self):
self.cls = similarities.Similarity
def factoryMethod(self):
# Override factoryMethod.
return self.cls(None, CORPUS, num_features=len(DICTIONARY), shardsize=5)
def test_sharding(self):
for num_best in [None, 0, 1, 9, 1000]:
... | TestSimilarity |
python | dask__dask | dask/layers.py | {
"start": 1598,
"end": 1815
} | class ____(ArrayBlockwiseDep):
"""Produce chunk shapes given a chunk index"""
def __getitem__(self, idx: tuple[int, ...]):
return tuple(chunk[i] for i, chunk in zip(idx, self.chunks))
| ArrayChunkShapeDep |
python | tensorflow__tensorflow | tensorflow/python/tpu/feature_column_v2_test.py | {
"start": 12356,
"end": 12994
} | class ____(test.TestCase,
parameterized.TestCase):
@test_util.deprecated_graph_mode_only
def test_error_dense_shape_invalid(self):
categorical_column_input = fc_lib.categorical_column_with_identity(
key='inp', num_buckets=5)
with self.assertRaisesRegex(Valu... | DeviceSpecificEmbeddingColumnTestV2 |
python | pytorch__pytorch | benchmarks/dynamo/pr_time_benchmarks/benchmarks/dynamo_inline.py | {
"start": 493,
"end": 697
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self._n = 1000
def forward(self, x):
for _ in range(self._n):
x = fn9(x)
return x
| InlineMod |
python | ray-project__ray | python/ray/util/collective/types.py | {
"start": 3886,
"end": 3995
} | class ____:
root_rank = 0
root_tensor = 0
timeout_ms = unset_timeout_ms
@dataclass
| BroadcastOptions |
python | wandb__wandb | wandb/sdk/artifacts/storage_handlers/s3_handler.py | {
"start": 1362,
"end": 12853
} | class ____(StorageHandler):
_scheme: str
_cache: ArtifactFileCache
_s3: boto3.resources.base.ServiceResource | None
def __init__(self, scheme: str = "s3") -> None:
self._scheme = scheme
self._cache = get_artifact_file_cache()
self._s3 = None
def can_handle(self, parsed_url:... | S3Handler |
python | doocs__leetcode | solution/0300-0399/0366.Find Leaves of Binary Tree/Solution.py | {
"start": 192,
"end": 637
} | class ____:
def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
l, r = dfs(root.left), dfs(root.right)
h = max(l, r)
if len(ans) == h:
ans.append... | Solution |
python | django-debug-toolbar__django-debug-toolbar | tests/panels/test_async_panel_compatibility.py | {
"start": 196,
"end": 247
} | class ____(Panel):
is_async = True
| MockAsyncPanel |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 6803,
"end": 6964
} | class ____(FileStrategy):
"""
This is a SLES Hostname strategy class - it edits the
/etc/HOSTNAME file.
"""
FILE = '/etc/HOSTNAME'
| SLESStrategy |
python | django__django | tests/gis_tests/geo3d/models.py | {
"start": 959,
"end": 1112
} | class ____(NamedModel):
poly = models.PolygonField(dim=3, srid=32140)
class Meta:
required_db_features = {"supports_3d_storage"}
| Polygon3D |
python | mlflow__mlflow | mlflow/store/artifact/azure_data_lake_artifact_repo.py | {
"start": 2390,
"end": 12111
} | class ____(CloudArtifactRepository):
"""
Stores artifacts on Azure Data Lake Storage Gen2.
This repository is used with URIs of the form
``abfs[s]://file_system@account_name.dfs.core.windows.net/<path>/<path>``.
Args
credential: Azure credential (see options in https://learn.microsoft.com/... | AzureDataLakeArtifactRepository |
python | joke2k__faker | faker/providers/job/bn_BD/__init__.py | {
"start": 41,
"end": 20843
} | class ____(JobProvider):
"""
Implement job provider for ``bn_BD`` locale.
"""
jobs = (
"একাডেমিক গ্রন্থাগারিক",
"আবাসন ব্যবস্থাপক",
"অ্যাকাউন্টেন্ট, চার্টার্ড",
"অ্যাকাউন্টেন্ট, চার্টার্ড সার্টিফাইড",
"অ্যাকাউন্টেন্ট, চার্টার্ড ম্যানেজমেন্ট",
"অ্যাকাউন্টে... | Provider |
python | kamyu104__LeetCode-Solutions | Python/closest-nodes-queries-in-a-binary-search-tree.py | {
"start": 1395,
"end": 2234
} | class ____(object):
def closestNodes(self, root, queries):
"""
:type root: Optional[TreeNode]
:type queries: List[int]
:rtype: List[List[int]]
"""
def dfs(node):
if not node:
return
dfs(node.left)
inorder.append(node... | Solution2 |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/dimension.py | {
"start": 434,
"end": 6948
} | class ____:
"""
Specified dimension (width/height) of a user control or window.
The layout engine tries to honor the preferred size. If that is not
possible, because the terminal is larger or smaller, it tries to keep in
between min and max.
:param min: Minimum size.
:param max: Maximum si... | Dimension |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 851239,
"end": 852871
} | class ____(sgqlc.types.Type):
"""The value of a pull request field in a Project item."""
__schema__ = github_schema
__field_names__ = ("field", "pull_requests")
field = sgqlc.types.Field(sgqlc.types.non_null("ProjectV2FieldConfiguration"), graphql_name="field")
"""The field that contains this value... | ProjectV2ItemFieldPullRequestValue |
python | bokeh__bokeh | src/bokeh/models/tools.py | {
"start": 40499,
"end": 41746
} | class ____(PlotActionTool):
""" Abstract base class for zoom action tools. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
renderers = Either(Auto, List(Instance(DataRenderer)), default="auto", help="""... | ZoomBaseTool |
python | gevent__gevent | src/gevent/tests/test__ssl.py | {
"start": 1088,
"end": 5597
} | class ____(test__socket.TestTCP):
# To generate:
# openssl req -x509 -newkey rsa:4096 -keyout test_server.key -out test_server.crt -days 36500 -nodes -subj '/CN=localhost'
certfile = os.path.join(os.path.dirname(__file__), 'test_server.crt')
privfile = os.path.join(os.path.dirname(__file__), 'test_serv... | TestSSL |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_getitem_test.py | {
"start": 4305,
"end": 26715
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
longMessage = True # Property in unittest.Testcase. pylint: disable=invalid-name
#=============================================================================
# RaggedTensor.__getitem__
#========================================================... | RaggedGetItemTest |
python | doocs__leetcode | solution/0400-0499/0487.Max Consecutive Ones II/Solution.py | {
"start": 0,
"end": 257
} | class ____:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
l = cnt = 0
for x in nums:
cnt += x ^ 1
if cnt > 1:
cnt -= nums[l] ^ 1
l += 1
return len(nums) - l
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-adjust/source_adjust/source.py | {
"start": 347,
"end": 476
} | class ____(YamlDeclarativeSource):
def __init__(self):
super().__init__(**{"path_to_yaml": "manifest.yaml"})
| SourceAdjust |
python | celery__celery | t/smoke/conftest.py | {
"start": 1010,
"end": 5068
} | class ____(
TaskTermination,
WorkerKill,
WorkerRestart,
):
"""Optional operations that can be performed with different methods,
shared across the smoke tests suite.
Example Usage:
>>> class test_mysuite(SuiteOperations):
>>> def test_something(self):
>>> self.prepare_wor... | SuiteOperations |
python | pypa__hatch | src/hatch/env/plugin/interface.py | {
"start": 36280,
"end": 38317
} | class ____:
"""
This class represents a synchronized path between the local file system and a potentially remote environment.
"""
def __init__(self, env: EnvironmentInterface, *, local_path: Path, env_path: str):
self.__env = env
self.__local_path = local_path
self.__env_path = ... | FileSystemContext |
python | huggingface__transformers | src/transformers/models/esm/tokenization_esm.py | {
"start": 1038,
"end": 5380
} | class ____(PreTrainedTokenizer):
"""
Constructs an ESM tokenizer.
"""
vocab_files_names = VOCAB_FILES_NAMES
model_input_names = ["input_ids", "attention_mask"]
def __init__(
self,
vocab_file,
unk_token="<unk>",
cls_token="<cls>",
pad_token="<pad>",
... | EsmTokenizer |
python | django__django | tests/sitemaps_tests/urls/http.py | {
"start": 855,
"end": 927
} | class ____(SimpleI18nSitemap):
alternates = True
| AlternatesI18nSitemap |
python | gabrielfalcao__HTTPretty | tests/functional/test_decorator.py | {
"start": 945,
"end": 1163
} | class ____(TestCase):
"""
Checks that the test methods in DecoratedNonUnitTest were decorated.
"""
def test_decorated(self):
DecoratedNonUnitTest().test_decorated()
@httprettified
| NonUnitTestTest |
python | pennersr__django-allauth | allauth/socialaccount/providers/gumroad/provider.py | {
"start": 343,
"end": 1111
} | class ____(OAuth2Provider):
id = "gumroad"
name = "Gumroad"
account_class = GumroadAccount
oauth2_adapter_class = GumroadOAuth2Adapter
def get_default_scope(self):
return ["edit_products"]
def extract_uid(self, data):
return str(data["user_id"])
def extract_common_fields(s... | GumroadProvider |
python | huggingface__transformers | src/transformers/models/d_fine/configuration_d_fine.py | {
"start": 1549,
"end": 21538
} | class ____(PreTrainedConfig):
"""
This is the configuration class to store the configuration of a [`DFineModel`]. It is used to instantiate a D-FINE
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configura... | DFineConfig |
python | huggingface__transformers | src/transformers/models/sam3_video/modeling_sam3_video.py | {
"start": 19025,
"end": 20341
} | class ____(ModelOutput):
r"""
object_ids (`list[int]`, *optional*):
List of object IDs being tracked in the current frame.
obj_id_to_mask (`dict[int, torch.FloatTensor]`, *optional*):
Dictionary mapping object IDs to their predicted low-resolution masks.
Each mask has shape `(1, H_lo... | Sam3VideoSegmentationOutput |
python | apache__airflow | providers/presto/tests/unit/presto/hooks/test_presto.py | {
"start": 2140,
"end": 8655
} | class ____:
@patch("airflow.providers.presto.hooks.presto.prestodb.auth.BasicAuthentication")
@patch("airflow.providers.presto.hooks.presto.prestodb.dbapi.connect")
@patch("airflow.providers.presto.hooks.presto.PrestoHook.get_connection")
def test_get_conn_basic_auth(self, mock_get_connection, mock_conn... | TestPrestoHookConn |
python | django__django | django/contrib/gis/geos/base.py | {
"start": 106,
"end": 181
} | class ____(CPointerBase):
null_ptr_exception_class = GEOSException
| GEOSBase |
python | fastai__fastai | fastai/learner.py | {
"start": 22507,
"end": 23140
} | class ____(Metric):
"Average the values of `func` taking into account potential different batch sizes"
def __init__(self, func): self.func = func
def reset(self): self.total,self.count = 0.,0
def accumulate(self, learn):
bs = find_bs(learn.yb)
self.total += learn.to_detach(sel... | AvgMetric |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataform.py | {
"start": 46184,
"end": 49180
} | class ____(GoogleCloudBaseOperator):
"""
Install NPM dependencies in the provided workspace.
Requires "package.json" to be created in the workspace.
:param project_id: Required. The ID of the Google Cloud project where workspace located.
:param region: Required. The ID of the Google Cloud region w... | DataformInstallNpmPackagesOperator |
python | pypa__pip | src/pip/_vendor/urllib3/exceptions.py | {
"start": 146,
"end": 232
} | class ____(Exception):
"""Base exception used by this module."""
pass
| HTTPError |
python | pyparsing__pyparsing | examples/simpleBool.py | {
"start": 1685,
"end": 3148
} | class ____(BoolBinOp):
repr_symbol = "|"
eval_fn = any
# define keywords and simple infix notation grammar for boolean
# expressions
TRUE = Keyword("True")
FALSE = Keyword("False")
NOT = Keyword("not")
AND = Keyword("and")
OR = Keyword("or")
boolOperand = TRUE | FALSE | Word(alphas, max=1)
boolOperand.set_par... | BoolOr |
python | pytorch__pytorch | test/jit/test_cuda.py | {
"start": 1078,
"end": 27908
} | class ____(JitTestCase):
"""
A suite of tests for the CUDA API in TorchScript.
"""
def tearDown(self):
gc.collect()
torch.cuda.empty_cache()
super().tearDown()
@unittest.skipIf(not TEST_MULTIGPU, "detected only one GPU")
def test_cuda_synchronize(self):
# Test d... | TestCUDA |
python | tiangolo__fastapi | tests/test_jsonable_encoder.py | {
"start": 467,
"end": 543
} | class ____:
def __init__(self, name: str):
self.name = name
| Person |
python | kamyu104__LeetCode-Solutions | Python/unique-morse-code-words.py | {
"start": 64,
"end": 600
} | class ____(object):
def uniqueMorseRepresentations(self, words):
"""
:type words: List[str]
:rtype: int
"""
MORSE = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.",
"---", ".--.", "--.-", ".-.... | Solution |
python | Netflix__metaflow | metaflow/plugins/kubernetes/kubernetes_job.py | {
"start": 1736,
"end": 16313
} | class ____(object):
def __init__(self, client, **kwargs):
self._client = client
self._kwargs = kwargs
def create_job_spec(self):
client = self._client.get()
# tmpfs variables
use_tmpfs = self._kwargs["use_tmpfs"]
tmpfs_size = self._kwargs["tmpfs_size"]
t... | KubernetesJob |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/records/users_records_builder.py | {
"start": 196,
"end": 481
} | class ____(ZendeskSupportRecordBuilder):
@classmethod
def record(cls) -> "UsersRecordBuilder":
record_template = cls.extract_record("users", __file__, NestedPath(["users", 0]))
return cls(record_template, FieldPath("id"), FieldPath("updated_at"))
| UsersRecordBuilder |
python | allegroai__clearml | clearml/utilities/gpu/pynvml.py | {
"start": 165884,
"end": 166328
} | class ____(_PrintableStructure):
_fields_ = [
("clusterUuid", c_char * NVML_DEVICE_UUID_BUFFER_SIZE),
("status", _nvmlReturn_t),
("partitionId", c_uint32),
("state", _nvmlGpuFabricState_t)
]
def nvmlDeviceGetGpuFabricInfo(device, gpuFabricInfo):
fn = _nvmlGetFunctionPointer... | c_nvmlGpuFabricInfo_t |
python | openai__openai-python | src/openai/resources/fine_tuning/checkpoints/checkpoints.py | {
"start": 3284,
"end": 3606
} | class ____:
def __init__(self, checkpoints: AsyncCheckpoints) -> None:
self._checkpoints = checkpoints
@cached_property
def permissions(self) -> AsyncPermissionsWithStreamingResponse:
return AsyncPermissionsWithStreamingResponse(self._checkpoints.permissions)
| AsyncCheckpointsWithStreamingResponse |
python | huggingface__transformers | src/transformers/models/align/modeling_align.py | {
"start": 2875,
"end": 6689
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
Contrastive loss for image-text similarity.
logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
The scaled dot product scores betwee... | AlignOutput |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_contrast.py | {
"start": 296,
"end": 5474
} | class ____(BaseImagePreprocessingLayer):
"""A preprocessing layer which randomly adjusts contrast during training.
This layer will randomly adjust the contrast of an image or images
by a random factor. Contrast is adjusted independently
for each channel of each image during training.
For each chan... | RandomContrast |
python | sqlalchemy__sqlalchemy | test/engine/test_reflection.py | {
"start": 53815,
"end": 57978
} | class ____(fixtures.TablesTest):
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
no_multibyte_period = {("plain", "col_plain", "ix_plain")}
no_has_table = [
(
"no_has_table_1",
"col_Unit\u00e9ble",
"... | UnicodeReflectionTest |
python | django-import-export__django-import-export | tests/core/models.py | {
"start": 4983,
"end": 5427
} | class ____(models.Model):
"""A model which uses a UUID pk (issue 1274)"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField("Book name", max_length=100)
author = models.ForeignKey(
NamedAuthor, blank=True, null=True, on_delete=models.CASCADE
... | UUIDBook |
python | django-extensions__django-extensions | tests/test_color.py | {
"start": 122,
"end": 664
} | class ____(SimpleTestCase):
def test_no_style(self):
with force_color_support:
style = color.no_style().MODULE_NAME
text = "csv"
styled_text = style(text)
self.assertEqual(text, styled_text)
def test_color_style(self):
with force_color_support:
... | ColorTest |
python | scipy__scipy | scipy/linalg/tests/test_interpolative.py | {
"start": 2641,
"end": 8616
} | class ____:
@pytest.mark.parametrize(
"rand,lin_op",
[(False, False), (True, False), (True, True)])
def test_real_id_fixed_precision(self, A, L, eps, rand, lin_op, rng):
# Test ID routines on a Hilbert matrix.
A_or_L = A if not lin_op else L
k, idx, proj = pymatrixid.in... | TestInterpolativeDecomposition |
python | tensorflow__tensorflow | tensorflow/python/distribute/failure_handling/failure_handling.py | {
"start": 15394,
"end": 56955
} | class ____(object):
# pylint: disable=line-too-long
"""Preemption and error handler for synchronous training.
Note: This API only supports use with
`tf.distribute.MultiWorkerMirroredStrategy` and `tf.distribute.TPUStrategy`.
A `PreemptionCheckpointHandler` coordinates all workers to save a checkpoint
upon... | PreemptionCheckpointHandler |
python | plotly__plotly.py | plotly/graph_objs/_scattermap.py | {
"start": 215,
"end": 64763
} | class ____(_BaseTraceType):
_parent_path_str = ""
_path_str = "scattermap"
_valid_props = {
"below",
"cluster",
"connectgaps",
"customdata",
"customdatasrc",
"fill",
"fillcolor",
"hoverinfo",
"hoverinfosrc",
"hoverlabel",
... | Scattermap |
python | pandas-dev__pandas | pandas/tests/extension/test_common.py | {
"start": 894,
"end": 2205
} | class ____:
@pytest.mark.parametrize(
"values",
[
pd.Categorical([]),
pd.Categorical([]).dtype,
pd.Series(pd.Categorical([])),
DummyDtype(),
DummyArray(np.array([1, 2])),
],
)
def test_is_extension_array_dtype(self, values):... | TestExtensionArrayDtype |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_quicksight.py | {
"start": 1521,
"end": 3383
} | class ____:
def setup_method(self):
self.default_op_kwargs = {
"task_id": "quicksight_create",
"aws_conn_id": None,
"data_set_id": DATA_SET_ID,
"ingestion_id": INGESTION_ID,
}
def test_init(self):
self.default_op_kwargs.pop("aws_conn_id", ... | TestQuickSightCreateIngestionOperator |
python | dask__distributed | distributed/core.py | {
"start": 42656,
"end": 55194
} | class ____:
"""A maximum sized pool of Comm objects.
This provides a connect method that mirrors the normal distributed.connect
method, but provides connection sharing and tracks connection limits.
This object provides an ``rpc`` like interface::
>>> rpc = ConnectionPool(limit=512)
>>... | ConnectionPool |
python | pypa__pipenv | pipenv/vendor/pipdeptree/_cli.py | {
"start": 606,
"end": 5205
} | class ____(ArgumentDefaultsHelpFormatter):
def __init__(self, prog: str) -> None:
super().__init__(prog, max_help_position=22, width=240)
def build_parser() -> ArgumentParser:
parser = ArgumentParser(description="Dependency tree of the installed python packages", formatter_class=_Formatter)
parser... | _Formatter |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis35.py | {
"start": 315,
"end": 1397
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis35.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | django__django | tests/forms_tests/tests/test_input_formats.py | {
"start": 8759,
"end": 12630
} | class ____(SimpleTestCase):
def test_timeField(self):
"TimeFields can parse dates in the default format"
f = forms.TimeField()
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
f.clean("1:30:05 PM")
# Parse a time in a ... | SimpleTimeFormatTests |
python | mlflow__mlflow | tests/tracing/test_fluent.py | {
"start": 2259,
"end": 2851
} | class ____:
@mlflow.trace(output_reducer=lambda x: sum(x))
def predict_stream(self, x, y):
z = x + y
for i in range(z):
yield i
# Generator with a normal func
for i in range(z):
yield self.square(i)
# Nested generator
yield from self.gene... | StreamTestModel |
python | doocs__leetcode | solution/1800-1899/1879.Minimum XOR Sum of Two Arrays/Solution3.py | {
"start": 0,
"end": 387
} | class ____:
def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums2)
f = [inf] * (1 << n)
f[0] = 0
for i in range(1, 1 << n):
k = i.bit_count() - 1
for j in range(n):
if i >> j & 1:
f[i] = min(f[i],... | Solution |
python | pydata__xarray | asv_bench/benchmarks/groupby.py | {
"start": 2450,
"end": 2941
} | class ____(GroupBy):
"""Run groupby tests using pandas DataFrame."""
def setup(self, *args, **kwargs):
# Skip testing in CI as it won't ever change in a commit:
_skip_slow()
super().setup(**kwargs)
self.ds1d = self.ds1d.to_dataframe()
self.ds1d_mean = self.ds1d.groupby(... | GroupByPandasDataFrame |
python | yandexdataschool__Practical_RL | week08_pomdp/env_pool.py | {
"start": 240,
"end": 4497
} | class ____(object):
def __init__(self, agent, make_env, n_parallel_games=1):
"""
A special class that handles training on multiple parallel sessions
and is capable of some auxilary actions like evaluating agent on one game session (See .evaluate()).
:param agent: Agent which interac... | EnvPool |
python | pytorch__pytorch | torch/testing/_internal/optests/generate_tests.py | {
"start": 26700,
"end": 29458
} | class ____(Exception):
pass
def generate_repro(
test: str,
op: torch._ops.OpOverload,
args: tuple[Any, ...],
kwargs: dict[str, Any],
*,
save_data: bool,
dry_run: bool = False,
) -> str:
if save_data:
now = datetime.datetime.now()
path = os.path.join(tempfile.gettemp... | OpCheckError |
python | xlwings__xlwings | xlwings/_xlwindows.py | {
"start": 29539,
"end": 33767
} | class ____(base_classes.Sheet):
def __init__(self, xl):
self.xl = xl
@property
def api(self):
return self.xl
@property
def name(self):
return self.xl.Name
@name.setter
def name(self, value):
self.xl.Name = value
@property
def names(self):
r... | Sheet |
python | python__mypy | mypy/reachability.py | {
"start": 12539,
"end": 13013
} | class ____(TraverserVisitor):
"""Visitor that sets is_mypy_only (which affects priority)."""
def visit_import(self, node: Import) -> None:
node.is_mypy_only = True
def visit_import_from(self, node: ImportFrom) -> None:
node.is_mypy_only = True
def visit_import_all(self, node: ImportAl... | MarkImportsMypyOnlyVisitor |
python | explosion__spaCy | spacy/language.py | {
"start": 2321,
"end": 4411
} | class ____:
"""Language data defaults, available via Language.Defaults. Can be
overwritten by language subclasses by defining their own subclasses of
Language.Defaults.
"""
config: Config = Config(section_order=CONFIG_SECTION_ORDER)
tokenizer_exceptions: Dict[str, List[dict]] = BASE_EXCEPTIONS
... | BaseDefaults |
python | ansible__ansible | lib/ansible/module_utils/_internal/_datatag/__init__.py | {
"start": 30395,
"end": 31727
} | class ____(datetime.datetime, AnsibleTaggedObject):
__slots__ = _ANSIBLE_TAGGED_OBJECT_SLOTS
@classmethod
def _instance_factory(cls, value: datetime.datetime, tags_mapping: _AnsibleTagsMapping) -> _AnsibleTaggedDateTime:
instance = cls(
year=value.year,
month=value.month,
... | _AnsibleTaggedDateTime |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 30519,
"end": 30653
} | class ____(BaseModel):
dag_id: str
run_id: str
type: Literal["GetTaskBreadcrumbs"] = "GetTaskBreadcrumbs"
| GetTaskBreadcrumbs |
python | astropy__astropy | astropy/time/core.py | {
"start": 127142,
"end": 129309
} | class ____(TypeError):
def __init__(self, left, right, op=None):
op_string = "" if op is None else f" for {op}"
super().__init__(
f"Unsupported operand type(s){op_string}: '{type(left).__name__}' "
f"and '{type(right).__name__}'"
)
def _check_leapsec():
global _... | OperandTypeError |
python | patrick-kidger__equinox | equinox/internal/_misc.py | {
"start": 335,
"end": 2259
} | class ____(type):
reverse_lookup: dict
def __new__(cls, name, bases, dict):
assert "reverse_lookup" not in dict
_dict = {}
reverse_lookup = []
i = 0
for key, value in dict.items():
if key.startswith("__") and key.endswith("__"):
_dict[key] = v... | ContainerMeta |
python | tensorflow__tensorflow | tensorflow/python/saved_model/load_v1_in_v2.py | {
"start": 1867,
"end": 2933
} | class ____(resource.CapturableResource):
"""Represents an initialization operation restored from a SavedModel.
Without this object re-export of imported 1.x SavedModels would omit the
original SavedModel's initialization procedure.
Created when `tf.saved_model.load` loads a TF 1.x-style SavedModel with an
i... | _Initializer |
python | wandb__wandb | tests/unit_tests/test_launch/test_runner/test_safe_watch.py | {
"start": 206,
"end": 2388
} | class ____:
"""Mock class for testing."""
def __init__(self):
self.is_alive = True
self.args = []
self.queue = []
async def stream(self, *args, **kwargs):
"""Simulate an input stream."""
self.args.append((args, kwargs))
while True:
if not self.is... | MockWatch |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/ppo/trainer.py | {
"start": 1089,
"end": 8375
} | class ____(OnPolicyTrainer):
"""The PPOTrainer is an implementation of the PPO algorithm."""
def __init__(
self,
behavior_name: str,
reward_buff_cap: int,
trainer_settings: TrainerSettings,
training: bool,
load: bool,
seed: int,
artifact_path: str... | PPOTrainer |
python | huggingface__transformers | src/transformers/models/olmo3/modular_olmo3.py | {
"start": 9665,
"end": 12130
} | class ____(Olmo2Attention):
def __init__(self, config: Olmo3Config, layer_idx: int):
super().__init__(config, layer_idx=layer_idx)
assert config.layer_types is not None
self.attention_type = config.layer_types[layer_idx]
self.sliding_window = config.sliding_window if self.attention_t... | Olmo3Attention |
python | sympy__sympy | sympy/tensor/array/expressions/array_expressions.py | {
"start": 11018,
"end": 12945
} | class ____(_CodegenArrayAbstract):
r"""
Class for elementwise array additions.
"""
def __new__(cls, *args, **kwargs):
args = [_sympify(arg) for arg in args]
ranks = [get_rank(arg) for arg in args]
ranks = list(set(ranks))
if len(ranks) != 1:
raise ValueError(... | ArrayAdd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.