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 | ansible__ansible | lib/ansible/module_utils/facts/namespace.py | {
"start": 2001,
"end": 2313
} | class ____(FactNamespace):
def __init__(self, namespace_name, prefix=None):
super(PrefixFactNamespace, self).__init__(namespace_name)
self.prefix = prefix
def transform(self, name):
new_name = self._underscore(name)
return '%s%s' % (self.prefix, new_name)
| PrefixFactNamespace |
python | pytorch__pytorch | benchmarks/tensorexpr/elementwise.py | {
"start": 240,
"end": 5619
} | class ____(benchmark.Benchmark):
# List of customization class variables.
op_str = None
binary_op_pt_func = None
binary_op_np_func = None
unary_op_pt_func = None
unary_op_np_func = None
split_input = True
def __init__(self, mode, device, dtype, N):
super().__init__(mode, device,... | ElementBench |
python | django__django | tests/postgres_tests/test_search.py | {
"start": 3625,
"end": 5242
} | class ____(GrailTestData, PostgreSQLTestCase):
def test_simple(self):
searched = Line.objects.filter(dialogue__search="elbows")
self.assertSequenceEqual(searched, [self.verse1])
def test_non_exact_match(self):
self.check_default_text_search_config()
searched = Line.objects.filte... | SimpleSearchTest |
python | numba__numba | numba/core/errors.py | {
"start": 21372,
"end": 21540
} | class ____(TypingError):
"""
For signalling that a function's typing requires a constant value for
some of its arguments.
"""
pass
| RequireLiteralValue |
python | protocolbuffers__protobuf | python/google/protobuf/internal/message_test.py | {
"start": 67421,
"end": 79978
} | class ____(unittest.TestCase):
def testFieldPresence(self):
message = unittest_pb2.TestAllTypes()
self.assertFalse(message.HasField('optional_int32'))
self.assertFalse(message.HasField('optional_bool'))
self.assertFalse(message.HasField('optional_nested_message'))
with self.assertRaises(ValueEr... | Proto2Test |
python | matplotlib__matplotlib | lib/matplotlib/backends/registry.py | {
"start": 41,
"end": 245
} | class ____(Enum):
"""
Filter used with :meth:`~matplotlib.backends.registry.BackendRegistry.list_builtin`
.. versionadded:: 3.9
"""
INTERACTIVE = 0
NON_INTERACTIVE = 1
| BackendFilter |
python | walkccc__LeetCode | solutions/2319. Check if Matrix Is X-Matrix/2319.py | {
"start": 0,
"end": 332
} | class ____:
def checkXMatrix(self, grid: list[list[int]]) -> bool:
n = len(grid)
for i in range(n):
for j in range(n):
if i == j or i + j == n - 1: # in diagonal
if grid[i][j] == 0:
return False
elif grid[i][j]: # not in diagonal
return False
retu... | Solution |
python | psf__black | src/black/report.py | {
"start": 183,
"end": 244
} | class ____(Enum):
NO = 0
CACHED = 1
YES = 2
| Changed |
python | joke2k__faker | faker/providers/isbn/isbn.py | {
"start": 1627,
"end": 2676
} | class ____(ISBN):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.check_digit = self._check_digit()
def _check_digit(self) -> str:
"""Calculate the check digit for ISBN-10.
See https://en.wikipedia.org/wiki/International_Standard_Boo... | ISBN10 |
python | jazzband__django-waffle | test_app/views.py | {
"start": 3443,
"end": 3524
} | class ____(WaffleSwitchMixin, BaseWaffleView):
waffle_switch = 'foo'
| SwitchView |
python | cython__cython | Cython/Build/Inline.py | {
"start": 998,
"end": 15933
} | class ____(EnvTransform, SkipDeclarations):
def __init__(self):
super(EnvTransform, self).__init__(context=None)
self.unbound = set()
def visit_NameNode(self, node):
if not self.current_env().lookup(node.name):
self.unbound.add(node.name)
return node
def __call__(... | UnboundSymbols |
python | kamyu104__LeetCode-Solutions | Python/concatenation-of-array.py | {
"start": 29,
"end": 247
} | class ____(object):
def getConcatenation(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums.extend(nums)
return nums
# Time: O(n)
# Space: O(1)
| Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/instrumentation.py | {
"start": 2495,
"end": 18004
} | class ____(
HasMemoized,
Dict[str, "QueryableAttribute[Any]"],
Generic[_O],
EventTarget,
):
"""Tracks state information at the class level."""
dispatch: dispatcher[ClassManager[_O]]
MANAGER_ATTR = base.DEFAULT_MANAGER_ATTR
STATE_ATTR = base.DEFAULT_STATE_ATTR
_state_setter = stati... | ClassManager |
python | huggingface__transformers | examples/pytorch/question-answering/run_seq2seq_qa.py | {
"start": 3655,
"end": 31748
} | class ____:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
"""
dataset_name: Optional[str] = field(
default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
)
dataset_config_name: Optional[str] = field(
... | DataTrainingArguments |
python | ansible__ansible | test/units/module_utils/facts/test_ansible_collector.py | {
"start": 18127,
"end": 18523
} | class ____(TestCollectedFacts):
gather_subset = ['pkg_mgr']
min_fact_count = 1
max_fact_count = 20
expected_facts = ['gather_subset',
'module_setup',
'pkg_mgr']
collected_facts = {
"ansible_distribution": "Fedora",
"ansible_distribution_maj... | TestPkgMgrFacts |
python | spyder-ide__spyder | spyder/utils/color_system.py | {
"start": 222,
"end": 562
} | class ____:
B0 = '#000000'
B10 = '#064738'
B20 = '#055C49'
B30 = '#007A5E'
B40 = '#008760'
B50 = '#019D70'
B60 = '#02BA85'
B70 = '#20C997'
B80 = '#44DEB0'
B90 = '#3BEBB7'
B100 = '#88F2D3'
B110 = '#B0F5E1'
B120 = '#D1FBEE'
B130 = '#E4FFF7'
B140 = '#F5FFFD'
... | Green |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_single.py | {
"start": 71372,
"end": 80657
} | class ____(
fixtures.DeclarativeMappedTest, AssertsCompiledSQL
):
__dialect__ = "default"
@classmethod
def setup_classes(cls, with_polymorphic=None, include_sub_defaults=False):
Base = cls.DeclarativeBasic
class Employee(Base):
__tablename__ = "employee"
id = Co... | SingleFromPolySelectableTest |
python | pola-rs__polars | py-polars/src/polars/io/partition.py | {
"start": 3919,
"end": 7577
} | class ____:
def __init__(
self,
base_path: str | Path,
*,
file_path_provider: Callable[
[KeyedPartitionContext], Path | str | IO[bytes] | IO[str]
]
| None = None,
partition_by: str
| Expr
| Sequence[str | Expr]
| Mapping[str... | _SinkDirectory |
python | Farama-Foundation__Gymnasium | tests/testing_env.py | {
"start": 1844,
"end": 5318
} | class ____(gym.Env):
"""A generic testing environment for use in testing with modified environments are required."""
def __init__(
self,
action_space: spaces.Space = spaces.Box(0, 1, (1,)),
observation_space: spaces.Space = spaces.Box(0, 1, (1,)),
reset_func: Callable = basic_re... | GenericTestEnv |
python | hynek__structlog | tests/test_output.py | {
"start": 5632,
"end": 8669
} | class ____:
def test_prints_to_stdout_by_default(self, capsys):
"""
Instantiating without arguments gives conveniently a logger to standard
out.
"""
BytesLogger().msg(b"hell\xc3\xb6")
out, err = capsys.readouterr()
assert "hellö\n" == out
assert "" ==... | TestBytesLogger |
python | kamyu104__LeetCode-Solutions | Python/convert-doubly-linked-list-to-array-i.py | {
"start": 43,
"end": 290
} | class ____:
def toArray(self, head):
"""
:type head: Node
:rtype: List[int]
"""
result = []
while head:
result.append(head.val)
head = head.next
return result
| Solution |
python | tensorflow__tensorflow | tensorflow/python/keras/testing_utils.py | {
"start": 19771,
"end": 22655
} | class ____(models.Model):
"""A Keras subclass model that uses a custom build method."""
def __init__(self, layer_generating_func, *args, **kwargs):
super(_SubclassModelCustomBuild, self).__init__(*args, **kwargs)
self.all_layers = None
self._layer_generating_func = layer_generating_func
def build(se... | _SubclassModelCustomBuild |
python | openai__openai-python | src/openai/types/responses/response_function_shell_call_output_content.py | {
"start": 451,
"end": 732
} | class ____(BaseModel):
exit_code: int
"""The exit code returned by the shell process."""
type: Literal["exit"]
"""The outcome type. Always `exit`."""
Outcome: TypeAlias = Annotated[Union[OutcomeTimeout, OutcomeExit], PropertyInfo(discriminator="type")]
| OutcomeExit |
python | urllib3__urllib3 | src/urllib3/response.py | {
"start": 2446,
"end": 5171
} | class ____(ContentDecoder):
def __init__(self) -> None:
self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
self._state = GzipDecoderState.FIRST_MEMBER
def decompress(self, data: bytes) -> bytes:
ret = bytearray()
if self._state == GzipDecoderState.SWALLOW_DATA or not data:
... | GzipDecoder |
python | huggingface__transformers | src/transformers/models/clvp/modeling_clvp.py | {
"start": 17102,
"end": 17755
} | class ____(nn.Module):
"""
`ClvpGatedLinearUnit` uses the second half of the `hidden_states` to act as a gate for the first half of the
`hidden_states` which controls the flow of data from the first of the tensor.
"""
def __init__(self, config):
super().__init__()
self.activation_fn... | ClvpGatedLinearUnit |
python | Farama-Foundation__Gymnasium | tests/envs/registration/test_env_spec.py | {
"start": 6001,
"end": 6099
} | class ____:
def __getstate__(self):
raise RuntimeError("Cannot pickle me!")
| Unpickleable |
python | google__pytype | pytype/tests/test_list2.py | {
"start": 798,
"end": 5157
} | class ____(test_base.BaseTest):
"""Tests for builtins.list in Python 3."""
def test_byte_unpack_ex(self):
ty = self.Infer("""
from typing import List
a, *b, c, d = 1, 2, 3, 4, 5, 6, 7
i, *j = 1, 2, 3, "4"
*k, l = 4, 5, 6
m, *n, o = [4, 5, "6", None, 7, 8]
p, *q, r = 4, 5, "6... | ListTest |
python | Pylons__pyramid | tests/test_traversal.py | {
"start": 1426,
"end": 3142
} | class ____(unittest.TestCase):
def _callFUT(self, path):
from pyramid.traversal import traversal_path_info
return traversal_path_info(path)
def test_path_startswith_endswith(self):
self.assertEqual(self._callFUT('/foo/'), (text_('foo'),))
def test_empty_elements(self):
sel... | TraversalPathInfoTests |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/focus_component_class.py | {
"start": 680,
"end": 944
} | class ____(App[None]):
def compose(self) -> ComposeResult:
yield Header()
with VerticalScroll():
for n in range(40):
yield Tester(n)
yield Footer()
if __name__ == "__main__":
StyleBugApp().run()
| StyleBugApp |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_submit_pipeline_execution.py | {
"start": 558,
"end": 13801
} | class ____(Config):
conn_string: str
port: int
@python_client_test_suite
def test_job_success(mock_client: MockClient):
mock_client.mock_gql_client.execute.return_value = launch_job_success_response
actual_run_id = mock_client.python_client.submit_job_execution(
"bar",
repository_locat... | AnOpConfig |
python | doocs__leetcode | solution/2900-2999/2996.Smallest Missing Integer Greater Than Sequential Prefix Sum/Solution.py | {
"start": 0,
"end": 305
} | class ____:
def missingInteger(self, nums: List[int]) -> int:
s, j = nums[0], 1
while j < len(nums) and nums[j] == nums[j - 1] + 1:
s += nums[j]
j += 1
vis = set(nums)
for x in count(s):
if x not in vis:
return x
| Solution |
python | getsentry__sentry-python | tests/integrations/langgraph/test_langgraph.py | {
"start": 1699,
"end": 1804
} | class ____:
def __init__(self):
self.nodes = {"tools": MockToolsNode()}
| MockGraphRepresentation |
python | numba__numba | numba/cuda/tests/cudadrv/test_is_fp16.py | {
"start": 105,
"end": 394
} | class ____(CUDATestCase):
def test_is_fp16_supported(self):
self.assertTrue(cuda.is_float16_supported())
@skip_on_cudasim
@skip_unless_cc_53
def test_device_supports_float16(self):
self.assertTrue(cuda.get_current_device().supports_float16)
| TestIsFP16Supported |
python | rapidsai__cudf | python/cudf/cudf/core/resample.py | {
"start": 3470,
"end": 15882
} | class ____(_Grouping):
bin_labels: Index
def __init__(self, obj, by=None, level=None):
self._freq = getattr(by, "freq", None)
super().__init__(obj, by, level)
def copy(self, deep=True):
out = super().copy(deep=deep)
result = _ResampleGrouping.__new__(_ResampleGrouping)
... | _ResampleGrouping |
python | sympy__sympy | sympy/stats/drv_types.py | {
"start": 3533,
"end": 5031
} | class ____(SingleDiscreteDistribution):
_argnames = ('a',)
set = S.Naturals
@staticmethod
def check(a):
_value_check((0 < a, a < 1), "a must be between 0 and 1")
def pdf(self, k):
a = self.a
return (a**2 * k * (1 - a)**(k - 1))
def _characteristic_function(self, t):
... | FlorySchulzDistribution |
python | pyinstaller__pyinstaller | PyInstaller/building/makespec.py | {
"start": 5353,
"end": 5770
} | class ____(_RemovedFlagAction):
def __call__(self, *args, **kwargs):
from PyInstaller.exceptions import RemovedWinSideBySideSupportError
raise RemovedWinSideBySideSupportError("Please remove your --win-no-prefer-redirects argument.")
# An object used in place of a "path string", which knows how to... | _RemovedWinNoPreferRedirectsAction |
python | boto__boto3 | tests/integration/test_session.py | {
"start": 637,
"end": 1911
} | class ____(unittest.TestCase):
def setUp(self):
self.botocore_session = botocore.session.get_session()
self.session = boto3.session.Session(
region_name='us-west-2', botocore_session=self.botocore_session
)
self.actual_user_agent = None
self.botocore_session.regis... | TestUserAgentCustomizations |
python | sqlalchemy__sqlalchemy | test/orm/test_syntax_extensions.py | {
"start": 1054,
"end": 1321
} | class ____(SyntaxExtension, ClauseElement):
_traverse_internals = []
def apply_to_select(self, select_stmt):
select_stmt.apply_syntax_extension_point(
lambda existing: [*existing, self],
"pre_columns",
)
| PreColumnsClause |
python | python__mypy | mypy/visitor.py | {
"start": 401,
"end": 5136
} | class ____(Generic[T]):
@abstractmethod
def visit_int_expr(self, o: mypy.nodes.IntExpr, /) -> T:
pass
@abstractmethod
def visit_str_expr(self, o: mypy.nodes.StrExpr, /) -> T:
pass
@abstractmethod
def visit_bytes_expr(self, o: mypy.nodes.BytesExpr, /) -> T:
pass
@ab... | ExpressionVisitor |
python | huggingface__transformers | src/transformers/models/modernbert_decoder/modeling_modernbert_decoder.py | {
"start": 15090,
"end": 16949
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: ModernBertDecoderConfig, layer_idx: Optional[int] = None):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.attention_type = config.layer_types[layer_idx]
self.attn_norm = (
... | ModernBertDecoderLayer |
python | pytorch__pytorch | tools/code_coverage/package/tool/parser/gcov_coverage_parser.py | {
"start": 106,
"end": 1643
} | class ____:
"""
Accepts a parsed json produced by gcov --json-format -- typically,
representing a single C++ test and produces a list
of CoverageRecord(s).
"""
def __init__(self, llvm_coverage: dict[str, Any]) -> None:
self._llvm_coverage = llvm_coverage
@staticmethod
def _skip... | GcovCoverageParser |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/endpoint_service.py | {
"start": 20263,
"end": 24056
} | class ____(GoogleCloudBaseOperator):
"""
Undeploys a Model from an Endpoint, removing a DeployedModel from it, and freeing all used resources.
: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... | UndeployModelOperator |
python | tensorflow__tensorflow | tensorflow/lite/python/lite_test.py | {
"start": 115485,
"end": 119026
} | class ____(TestModels, parameterized.TestCase):
def testConstantFolding(self):
ops.disable_eager_execution()
# Constant folding handles the tf.broadcast_to operation which was not
# supported by the TFLite at the time this test was added.
with ops.Graph().as_default():
in_tensor = array_ops.pla... | GrapplerTest |
python | doocs__leetcode | solution/3700-3799/3736.Minimum Moves to Equal Array Elements III/Solution.py | {
"start": 0,
"end": 157
} | class ____:
def minMoves(self, nums: List[int]) -> int:
n = len(nums)
mx = max(nums)
s = sum(nums)
return mx * n - s
| Solution |
python | scipy__scipy | benchmarks/benchmarks/sparse.py | {
"start": 2644,
"end": 4142
} | class ____(Benchmark):
param_names = ['sparse_type', 'name', 'format']
params = [
['spmatrix', 'sparray'],
['Identity', 'Poisson5pt', 'Block2x2', 'Block3x3'],
['dia', 'csr', 'csc', 'dok', 'lil', 'coo', 'bsr'],
]
def setup(self, sparse_type, name, format):
if name == 'Ide... | Matvec |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/softmax_op_test.py | {
"start": 1158,
"end": 11252
} | class ____(test.TestCase):
def _npSoftmax(self, features, dim=-1, log=False):
if dim == -1:
dim = len(features.shape) - 1
one_only_on_dim = list(features.shape)
one_only_on_dim[dim] = 1
is_fp16 = features.dtype == np.float16
if is_fp16:
# Do the compute in fp32 and cast the input back... | SoftmaxTest |
python | getsentry__sentry | tests/sentry/plugins/bases/test_issue2.py | {
"start": 603,
"end": 738
} | class ____(IssueTrackingPlugin2):
slug = "test-plugin-without-fields"
conf_key = slug
issue_fields = None
| PluginWithoutFields |
python | redis__redis-py | redis/commands/core.py | {
"start": 213557,
"end": 216306
} | class ____:
"""
An executable Lua script object returned by ``register_script``
"""
def __init__(self, registered_client: "redis.client.Redis", script: ScriptTextT):
self.registered_client = registered_client
self.script = script
# Precalculate and store the SHA1 hex digest of t... | Script |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-oci-data-science/llama_index/llms/oci_data_science/client.py | {
"start": 6188,
"end": 12081
} | class ____(ABC):
"""
Base class for invoking models via HTTP requests with retry logic.
Attributes:
endpoint (str): The URL endpoint to send the request.
auth (Any): The authentication signer for the requests.
retries (int): The number of retry attempts for the request.
back... | BaseClient |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/io_ops/parsing_ops_test.py | {
"start": 84505,
"end": 88087
} | class ____(test.TestCase):
def _decode_v1(self, words):
with self.cached_session():
examples = np.array(words)
example_tensor = constant_op.constant(
examples, shape=examples.shape, dtype=dtypes.string)
byte_tensor = parsing_ops.decode_raw_v1(example_tensor, dtypes.uint8)
return... | DecodeRawTest |
python | pytorch__pytorch | test/test_fx_reinplace_pass.py | {
"start": 530,
"end": 14496
} | class ____(TestCase):
def test_reinplace_basic(self):
# Basic test: the out-of-place add() call should be converted
# into add_()
def f(x):
a = x.clone()
b = a.add(1)
return b
inpt = torch.ones(2)
f2 = reinplace(make_fx(f)(inpt), inpt)
... | TestReinplacePass |
python | numba__numba | numba/parfors/parfor.py | {
"start": 24808,
"end": 54340
} | class ____(object):
"""Holds parfor diagnostic info, this is accumulated throughout the
PreParforPass and ParforPass, also in the closure inlining!
"""
def __init__(self):
# holds ref to the function for which this is providing diagnostics
self.func = None
# holds a map of the re... | ParforDiagnostics |
python | sympy__sympy | sympy/core/singleton.py | {
"start": 1009,
"end": 7370
} | class ____(Registry):
"""
The registry for the singleton classes (accessible as ``S``).
Explanation
===========
This class serves as two separate things.
The first thing it is is the ``SingletonRegistry``. Several classes in
SymPy appear so often that they are singletonized, that is, usin... | SingletonRegistry |
python | huggingface__transformers | src/transformers/models/owlvit/modeling_owlvit.py | {
"start": 22935,
"end": 24924
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: OwlViTConfig):
super().__init__()
self.embed_dim = config.hidden_size
self.self_attn = OwlViTAttention(config)
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
self.mlp = OwlViTMLP(co... | OwlViTEncoderLayer |
python | doocs__leetcode | lcof/面试题49. 丑数/Solution.py | {
"start": 0,
"end": 352
} | class ____:
def nthUglyNumber(self, n: int) -> int:
h = [1]
vis = {1}
ans = 1
for _ in range(n):
ans = heappop(h)
for v in [2, 3, 5]:
nxt = ans * v
if nxt not in vis:
vis.add(nxt)
heappush... | Solution |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1574658,
"end": 1574868
} | class ____(SelectionInitInterval):
"""Vector2boolean schema wrapper."""
_schema = {"$ref": "#/definitions/Vector2<boolean>"}
def __init__(self, *args):
super().__init__(*args)
| Vector2boolean |
python | falconry__falcon | falcon/testing/helpers.py | {
"start": 1956,
"end": 3435
} | class ____:
"""Emits ASGI lifespan events to an ASGI app.
This class can be used to drive a standard ASGI app callable in order to
perform functional tests on the app in question.
When simulating both lifespan and per-request events, each event stream
will require a separate invocation of the ASGI... | ASGILifespanEventEmitter |
python | walkccc__LeetCode | solutions/2921. Maximum Profitable Triplets With Increasing Prices II/2921.py | {
"start": 446,
"end": 1155
} | class ____:
# Same as 2907. Maximum Profitable Triplets With Increasing Prices I
def maxProfit(self, prices: list[int], profits: list[int]) -> int:
ans = -1
maxPrice = max(prices)
maxProfitTree1 = FenwickTree(maxPrice)
maxProfitTree2 = FenwickTree(maxPrice)
for price, profit in zip(prices, prof... | Solution |
python | PyCQA__pylint | tests/functional/e/e1101_9588_base_attr_aug_assign.py | {
"start": 241,
"end": 355
} | class ____:
"The base class"
def __init__(self):
"Set an attribute."
self.e1101 = 1
| BaseClass |
python | walkccc__LeetCode | solutions/1579. Remove Max Number of Edges to Keep Graph Fully Traversable/1579.py | {
"start": 0,
"end": 579
} | class ____:
def __init__(self, n: int):
self.count = n
self.id = list(range(n))
self.rank = [0] * n
def unionByRank(self, u: int, v: int) -> bool:
i = self._find(u)
j = self._find(v)
if i == j:
return False
if self.rank[i] < self.rank[j]:
self.id[i] = j
elif self.rank[i]... | UnionFind |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_sort.py | {
"start": 6416,
"end": 7764
} | class ____(__TestCase):
def test_bug453523(self):
# bug 453523 -- list.sort() crasher.
# If this fails, the most likely outcome is a core dump.
# Mutations during a list sort should raise a ValueError.
with torch._dynamo.error_on_graph_break(False):
class C:
... | TestBugs |
python | doocs__leetcode | solution/3000-3099/3036.Number of Subarrays That Match a Pattern II/Solution.py | {
"start": 715,
"end": 1086
} | class ____:
def countMatchingSubarrays(self, nums: List[int], pattern: List[int]) -> int:
s = []
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
s.append(1)
elif nums[i] == nums[i - 1]:
s.append(0)
else:
s.ap... | Solution |
python | getsentry__sentry | tests/sentry/seer/explorer/test_custom_tool_utils.py | {
"start": 1112,
"end": 1709
} | class ____(ExplorerTool):
@classmethod
def get_description(cls):
return "Test tool with default parameter"
@classmethod
def get_params(cls):
return [
ExplorerToolParam(name="value", description="Value", type=StringType()),
ExplorerToolParam(
name=... | TestToolWithDefault |
python | tensorflow__tensorflow | tensorflow/python/ops/math_ops_test.py | {
"start": 40914,
"end": 42447
} | class ____(test_util.TensorFlowTestCase):
def testXlogyNoZero(self):
for dtype in [dtypes.float16, dtypes.float32, dtypes.float64]:
x = constant_op.constant([[0.1, 0.2, 3.5], [-2., -5., 30.]], dtype=dtype)
y = constant_op.constant([[0.1, 0.2, 3.5], [3.1, 4., 2.]], dtype=dtype)
with test_util.us... | XlogyTest |
python | pyodide__pyodide | src/py/pyodide/http/_exceptions.py | {
"start": 1747,
"end": 1936
} | class ____(XHRError):
"""Timeout error for XMLHttpRequest."""
def __init__(self, timeout: int) -> None:
super().__init__(f"Request timed out after {timeout}ms")
| XHRTimeoutError |
python | PyCQA__pydocstyle | src/pydocstyle/parser.py | {
"start": 5421,
"end": 6838
} | class ____(Definition):
"""A Python source code function."""
_nest = staticmethod(
lambda s: {'def': NestedFunction, 'class': NestedClass}[s]
)
@property
def is_public(self):
"""Return True iff this function should be considered public."""
if self.dunder_all is not None:
... | Function |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0070_migrate_remaining_anomaly_detection_alerts.py | {
"start": 1558,
"end": 2149
} | class ____(Enum):
EMAIL = 0
PAGERDUTY = 1
SLACK = 2
MSTEAMS = 3
SENTRY_APP = 4
SENTRY_NOTIFICATION = 5 # Use personal notification platform (src/sentry/notifications)
OPSGENIE = 6
DISCORD = 7
MAX_ACTIONS = 3
ACTION_TYPE_TO_STRING = {
AlertRuleTriggerActionType.PAGERDUTY.value: "P... | AlertRuleTriggerActionType |
python | scikit-learn__scikit-learn | sklearn/decomposition/_fastica.py | {
"start": 11349,
"end": 26604
} | class ____(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator):
"""FastICA: a fast algorithm for Independent Component Analysis.
The implementation is based on [1]_.
Read more in the :ref:`User Guide <ICA>`.
Parameters
----------
n_components : int, default=None
Number o... | FastICA |
python | great-expectations__great_expectations | great_expectations/core/serdes.py | {
"start": 101,
"end": 178
} | class ____(BaseModel):
name: str
id: Union[str, None]
| _IdentifierBundle |
python | openai__openai-python | src/openai/types/beta/threads/runs/code_interpreter_output_image.py | {
"start": 408,
"end": 613
} | class ____(BaseModel):
index: int
"""The index of the output in the outputs array."""
type: Literal["image"]
"""Always `image`."""
image: Optional[Image] = None
| CodeInterpreterOutputImage |
python | django-compressor__django-compressor | compressor/exceptions.py | {
"start": 0,
"end": 100
} | class ____(Exception):
"""
A general error of the compressor
"""
pass
| CompressorError |
python | walkccc__LeetCode | solutions/711. Number of Distinct Islands II/711.py | {
"start": 0,
"end": 1417
} | class ____:
def numDistinctIslands2(self, grid: list[list[int]]) -> int:
seen = set()
def dfs(i: int, j: int):
if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]):
return
if grid[i][j] == 0 or (i, j) in seen:
return
seen.add((i, j))
island.append((i, j))
df... | Solution |
python | ray-project__ray | python/ray/_private/gcs_pubsub.py | {
"start": 8474,
"end": 9446
} | class ____(_AioSubscriber):
def __init__(
self,
worker_id: bytes = None,
address: str = None,
channel: grpc.Channel = None,
):
super().__init__(pubsub_pb2.GCS_NODE_INFO_CHANNEL, worker_id, address, channel)
async def poll(
self, batch_size, timeout=None
)... | GcsAioNodeInfoSubscriber |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/data_structures/lookup_ops_test.py | {
"start": 2513,
"end": 3372
} | class ____(test.TestCase):
def getHashTable(self):
if tf2.enabled():
return lookup_ops.StaticHashTable
else:
return lookup_ops.StaticHashTableV1
def getVocabularyTable(self):
if tf2.enabled():
return lookup_ops.StaticVocabularyTable
else:
return lookup_ops.StaticVocabularyT... | BaseLookupTableTest |
python | ansible__ansible | lib/ansible/inventory/manager.py | {
"start": 30212,
"end": 31743
} | class ____(_wrapt.ObjectProxy):
"""
Proxy wrapper around InventoryData.
Allows `set_variable` calls to automatically apply template trust for plugins that don't know how.
"""
# declared as class attrs to signal to ObjectProxy that we want them stored on the proxy, not the wrapped value
_target_... | _InventoryDataWrapper |
python | jina-ai__jina | tests/unit/orchestrate/deployments/test_deployments.py | {
"start": 5558,
"end": 8032
} | class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = self.runtime_args.name
@requests
def foo(self, docs: DocumentArray, **kwargs):
for doc in docs:
doc.text = str(self.name)
@pytest.mark.slow
def test_pod_in_flow_act... | SetNameExecutor |
python | pytorch__pytorch | test/jit/test_convert_activation.py | {
"start": 4326,
"end": 6437
} | class ____(JitTestCase):
def test_inplace_to_functional_activation(self):
for activation in activations:
def test_basic(x):
y = x + 1
activation(y, inplace=True)
return y
fn = torch.jit.script(test_basic)
self.run_pass("in... | TestInplaceToFunctionalActivation |
python | lazyprogrammer__machine_learning_examples | unsupervised_class2/rbm.py | {
"start": 581,
"end": 4520
} | class ____(object):
def __init__(self, M, an_id):
self.M = M
self.id = an_id
self.rng = RandomStreams()
def fit(self, X, learning_rate=0.1, epochs=1, batch_sz=100, show_fig=False):
# cast to float32
learning_rate = np.float32(learning_rate)
N, D = X.shape
... | RBM |
python | airbytehq__airbyte | airbyte-integrations/bases/base-normalization/normalization/destination_type.py | {
"start": 87,
"end": 633
} | class ____(Enum):
BIGQUERY = "bigquery"
CLICKHOUSE = "clickhouse"
MSSQL = "mssql"
MYSQL = "mysql"
ORACLE = "oracle"
POSTGRES = "postgres"
REDSHIFT = "redshift"
SNOWFLAKE = "snowflake"
TIDB = "tidb"
DUCKDB = "duckdb"
@classmethod
def from_string(cls, string_value: str) ->... | DestinationType |
python | apache__airflow | providers/google/tests/unit/google/cloud/utils/test_field_validator.py | {
"start": 1008,
"end": 11279
} | class ____:
def test_validate_should_not_raise_exception_if_field_and_body_are_both_empty(self):
specification = []
body = {}
validator = GcpBodyFieldValidator(specification, "v1")
assert validator.validate(body) is None
def test_validate_should_fail_if_body_is_none(self):
... | TestGcpBodyFieldValidator |
python | walkccc__LeetCode | solutions/1129. Shortest Path with Alternating Colors/1129.py | {
"start": 77,
"end": 914
} | class ____:
def shortestAlternatingPaths(
self,
n: int,
redEdges: list[list[int]],
blueEdges: list[list[int]],
) -> list[int]:
ans = [-1] * n
graph = [[] for _ in range(n)] # graph[u] := [(v, edgeColor)]
q = collections.deque([(0, Color.INIT)]) # [(u, prevColor)]
for u, v ... | Solution |
python | huggingface__transformers | tests/models/electra/test_modeling_electra.py | {
"start": 23009,
"end": 23791
} | class ____(unittest.TestCase):
@slow
def test_inference_no_head_absolute_embedding(self):
model = ElectraModel.from_pretrained("google/electra-small-discriminator")
input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
attention_mask = torch.tensor([[0, 1, 1, ... | ElectraModelIntegrationTest |
python | viewflow__viewflow | tests/contrib/test_contrib_admin.py | {
"start": 197,
"end": 524
} | class ____(TestCase):
fixtures = ['users.json']
def test_admin_viewset_entry(self):
self.assertTrue(self.client.login(username='admin', password='admin'))
response = self.client.get('/')
self.assertRedirects(response, '/admin/')
urlpatterns = [
path('', Site(viewsets=[Admin()]).u... | Test |
python | aimacode__aima-python | logic.py | {
"start": 3070,
"end": 15626
} | class ____(KB):
"""A KB for propositional logic. Inefficient, with no indexing."""
def __init__(self, sentence=None):
super().__init__(sentence)
self.clauses = []
def tell(self, sentence):
"""Add the sentence's clauses to the KB."""
self.clauses.extend(conjuncts(to_cnf(sent... | PropKB |
python | pytorch__pytorch | test/inductor/test_group_batch_fusion.py | {
"start": 9537,
"end": 10394
} | class ____(torch.nn.Module):
def __init__(self, device):
super().__init__()
self.device = device
def forward(self, x):
inputs = [x.to(self.device) for i in range(10)]
others = [x.to(self.device) for i in range(10)]
clamp_input = [x.clamp(min=-1000.1, max=1000.1) for x in... | TestMathOps |
python | wandb__wandb | tests/system_tests/test_core/test_tb_watcher.py | {
"start": 44,
"end": 1682
} | class ____:
def test_simple(self):
assert tb_watcher.is_tfevents_file_created_by(
"out.writer.tfevents.193.me.94.5", "me", 193
)
def test_no_tfevents(self):
assert (
tb_watcher.is_tfevents_file_created_by(
"out.writer.tfevent.193.me.94.5", "me", 1... | TestIsTfEventsFileCreatedBy |
python | getsentry__sentry | tests/snuba/search/test_backend.py | {
"start": 98360,
"end": 114144
} | class ____(TestCase, SharedSnubaMixin, OccurrenceTestMixin):
@property
def backend(self):
return EventsDatasetSnubaSearchBackend()
def test_trends_sort_old_and_new_events(self) -> None:
"""Test that an issue with only one old event is ranked lower than an issue with only one new event"""
... | EventsTrendsTest |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 67441,
"end": 68744
} | class ____(Response):
"""
Response of queues.move_task_forward endpoint.
:param position: The new position of the task entry in the queue (index, -1
represents bottom of queue)
:type position: int
"""
_service = "queues"
_action = "move_task_forward"
_version = "2.13"
_sche... | MoveTaskForwardResponse |
python | viewflow__viewflow | viewflow/workflow/nodes/job.py | {
"start": 286,
"end": 2480
} | class ____(mixins.NextNodeActivationMixin, Activation):
@classmethod
def create(cls, flow_task, prev_activation, token, data=None, seed=None):
"""Instantiate and persist new flow task."""
flow_class = flow_task.flow_class
task = flow_class.task_class(
process=prev_activation.... | AbstractJobActivation |
python | altair-viz__altair | altair/vegalite/v6/api.py | {
"start": 22788,
"end": 23562
} | class ____(TypedDict, closed=True, total=False): # type: ignore[call-arg]
# https://peps.python.org/pep-0728/
# Likely a Field predicate
empty: Optional[bool]
param: Parameter | str
test: _TestPredicateType
value: Any
__extra_items__: _StatementType | OneOrSeq[PrimitiveValue_T]
_Condition... | _ConditionExtra |
python | huggingface__transformers | examples/modular-transformers/modular_my_new_model2.py | {
"start": 1527,
"end": 1612
} | class ____(GemmaForSequenceClassification):
pass
| MyNewModel2ForSequenceClassification |
python | kamyu104__LeetCode-Solutions | Python/similar-string-groups.py | {
"start": 99,
"end": 654
} | class ____(object):
def __init__(self, n):
self.set = range(n)
self.__size = n
def find_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x]) # path compression.
return self.set[x]
def union_set(self, x, y):
x_root, y_root = map(se... | UnionFind |
python | jazzband__tablib | src/tablib/exceptions.py | {
"start": 540,
"end": 635
} | class ____(TablibException, NotImplementedError):
"""Format not supported."""
| UnsupportedFormat |
python | tensorflow__tensorflow | tensorflow/lite/python/op_hint.py | {
"start": 27454,
"end": 52962
} | class ____:
"""Represent a TensorFlow Lite custom function.
This is uses to accumulate found hints in the graphdef into a single
conceptual unit.
Attributes:
inputs: inputs to the op (hash from index # to argument)
outputs: outputs to the op (hash from index # to argument)
function_name: the tflit... | _LiteFuncCall |
python | kamyu104__LeetCode-Solutions | Python/remove-covered-intervals.py | {
"start": 33,
"end": 427
} | class ____(object):
def removeCoveredIntervals(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
intervals.sort(key=lambda x: [x[0], -x[1]])
result, max_right = 0, 0
for left, right in intervals:
result += int(right > max_right... | Solution |
python | pallets__click | src/click/types.py | {
"start": 23787,
"end": 24320
} | class ____(ParamType):
name = "uuid"
def convert(
self, value: t.Any, param: Parameter | None, ctx: Context | None
) -> t.Any:
import uuid
if isinstance(value, uuid.UUID):
return value
value = value.strip()
try:
return uuid.UUID(value)
... | UUIDParameterType |
python | django__django | tests/model_inheritance/models.py | {
"start": 3545,
"end": 3639
} | class ____:
def __init__(self):
self.other_attr = 1
super().__init__()
| Mixin |
python | has2k1__plotnine | tests/test_layout.py | {
"start": 4992,
"end": 8282
} | class ____:
g = ggplot(mtcars, aes(x="wt", y="mpg", color="gear")) + geom_point()
def test_outside_legend_right_bottom(self):
p = self.g + theme(legend_justification=0)
assert p == "outside_legend_right_bottom"
def test_outside_legend_left_top(self):
p = self.g + theme(
... | TestLegendPositioning |
python | getsentry__sentry | src/sentry/analytics/events/sentry_app_deleted.py | {
"start": 75,
"end": 227
} | class ____(analytics.Event):
user_id: int
organization_id: int
sentry_app: str
analytics.register(SentryAppDeletedEvent)
| SentryAppDeletedEvent |
python | ray-project__ray | python/ray/data/tests/test_partitioning.py | {
"start": 10817,
"end": 12345
} | class ____:
@pytest.mark.parametrize(
"relative_path", ["year=1970/country=fr/data.csv", "1970/fr/data.csv"]
)
def test_read_single_file(
self, relative_path, tmp_path, block_type, ray_start_regular_shared
):
path = os.path.join(tmp_path, relative_path)
write_csv({"number... | TestReadUnpartitionedFiles |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.