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 | apache__thrift | lib/py/src/protocol/TBase.py | {
"start": 828,
"end": 2042
} | class ____(object):
__slots__ = ()
def __repr__(self):
L = ['%s=%r' % (key, getattr(self, key)) for key in self.__slots__]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
f... | TBase |
python | walkccc__LeetCode | solutions/973. K Closest Points to Origin/973-3.py | {
"start": 0,
"end": 935
} | class ____:
def kClosest(self, points: list[list[int]], k: int) -> list[list[int]]:
def squareDist(p: list[int]) -> int:
return p[0] * p[0] + p[1] * p[1]
def quickSelect(l: int, r: int, k: int) -> None:
randIndex = random.randint(0, r - l + 1) + l
points[randIndex], points[r] = points[r], p... | Solution |
python | scikit-learn__scikit-learn | sklearn/model_selection/_split.py | {
"start": 61821,
"end": 63871
} | class ____(_UnsupportedGroupCVMixin, _RepeatedSplits):
"""Repeated K-Fold cross validator.
Repeats K-Fold `n_repeats` times with different randomization in each repetition.
Read more in the :ref:`User Guide <repeated_k_fold>`.
Parameters
----------
n_splits : int, default=5
Number of ... | RepeatedKFold |
python | graphql-python__graphene | graphene/types/objecttype.py | {
"start": 1636,
"end": 5802
} | class ____(BaseType, metaclass=ObjectTypeMeta):
"""
Object Type Definition
Almost all of the GraphQL types you define will be object types. Object types
have a name, but most importantly describe their fields.
The name of the type defined by an _ObjectType_ defaults to the class name. The type
... | ObjectType |
python | walkccc__LeetCode | solutions/2058. Find the Minimum and Maximum Number of Nodes Between Critical Points/2058.py | {
"start": 0,
"end": 781
} | class ____:
def nodesBetweenCriticalPoints(self, head: ListNode | None) -> list[int]:
minDistance = math.inf
firstMaIndex = -1
prevMaIndex = -1
index = 1
prev = head # Point to the index 0.
curr = head.next # Point to the index 1.
while curr.next:
if (curr.val > prev.val and curr.... | Solution |
python | ray-project__ray | python/ray/data/expressions.py | {
"start": 6544,
"end": 17112
} | class ____(ABC):
"""Base class for all expression nodes.
This is the abstract base class that all expression types inherit from.
It provides operator overloads for building complex expressions using
standard Python operators.
Expressions form a tree structure where each node represents an operatio... | Expr |
python | pytest-dev__pytest | src/_pytest/config/__init__.py | {
"start": 7103,
"end": 11924
} | class ____: # compatibility namespace
main = staticmethod(main)
def filename_arg(path: str, optname: str) -> str:
"""Argparse type validator for filename arguments.
:path: Path of filename.
:optname: Name of the option.
"""
if os.path.isdir(path):
raise UsageError(f"{optname} must be... | cmdline |
python | huggingface__transformers | src/transformers/models/sam3_tracker/modular_sam3_tracker.py | {
"start": 4681,
"end": 4763
} | class ____(Sam2ImageSegmentationOutput):
pass
| Sam3TrackerImageSegmentationOutput |
python | scipy__scipy | scipy/constants/tests/test_constants.py | {
"start": 3563,
"end": 3923
} | class ____:
def test_lambda_to_nu(self, xp):
xp_assert_equal(sc.lambda2nu(xp.asarray([sc.speed_of_light, 1])),
xp.asarray([1, sc.speed_of_light]))
def test_lambda_to_nu_array_like(self):
xp_assert_close(sc.lambda2nu([sc.speed_of_light, 1]), [1, sc.speed_of_light])
@ma... | TestLambdaToNu |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/model_query_cache.py | {
"start": 1122,
"end": 1283
} | class ____(Table):
def attribute_x(self):
return 0
def attribute_z(self):
return 0
def non_attribute_t(self):
return 0
| BarTable |
python | pandas-dev__pandas | asv_bench/benchmarks/tslibs/timestamp.py | {
"start": 3312,
"end": 3602
} | class ____:
def setup(self):
dt = datetime(2016, 3, 27, 1, fold=0)
self.tzinfo = dt.astimezone(zoneinfo.ZoneInfo("Europe/Berlin")).tzinfo
self.ts2 = Timestamp(dt)
def time_replace_across_dst(self):
self.ts2.replace(tzinfo=self.tzinfo)
| TimestampAcrossDst |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linalg_grad_test.py | {
"start": 2039,
"end": 3520
} | class ____(test_lib.TestCase):
pass # Filled in below
# TODO(b/417809163): re-enable this test when upstream issues are resolved
# see commit msg for details
# def _GetMatrixUnaryFunctorGradientTest(functor_, dtype_, shape_, **kwargs_):
#
# @test_util.enable_control_flow_v2
# @test_util.run_in_graph_and_eager_mod... | MatrixUnaryFunctorGradientTest |
python | RaRe-Technologies__gensim | gensim/topic_coherence/text_analysis.py | {
"start": 8211,
"end": 8869
} | class ____(InvertedIndexBased):
"""Gather word occurrence stats from a corpus by iterating over its BoW representation."""
def analyze_text(self, text, doc_num=None):
"""Build an inverted index from a sequence of corpus texts."""
doc_words = frozenset(x[0] for x in text)
top_ids_in_doc ... | CorpusAccumulator |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/io_ops/parsing_ops_test.py | {
"start": 88087,
"end": 91107
} | class ____(test.TestCase):
def _testRoundTrip(self, examples):
examples = np.array(examples, dtype=np.object_)
json_tensor = constant_op.constant(
[json_format.MessageToJson(m) for m in examples.flatten()],
shape=examples.shape,
dtype=dtypes.string)
binary_tensor = parsing_ops.de... | DecodeJSONExampleTest |
python | joke2k__faker | tests/providers/test_currency.py | {
"start": 16788,
"end": 17213
} | class ____:
"""Test tr_TR currency provider"""
num_samples = 100
@classmethod
def setup_class(cls):
from faker.providers.currency.tr_TR import Provider as TrTrCurrencyProvider
cls.provider = TrTrCurrencyProvider
def test_pricetag(self, faker, num_samples):
for _ in range(... | TestTrTr |
python | doocs__leetcode | solution/0700-0799/0795.Number of Subarrays with Bounded Maximum/Solution2.py | {
"start": 0,
"end": 684
} | class ____:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
n = len(nums)
l, r = [-1] * n, [n] * n
stk = []
for i, v in enumerate(nums):
while stk and nums[stk[-1]] <= v:
stk.pop()
if stk:
l[i] = ... | Solution |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 161254,
"end": 162922
} | class ____(torch.nn.Module):
def forward(self, L_inputs_: "f32[64, 3]", L_targets_: "f32[64, 3]"):
l_inputs_ = L_inputs_
l_targets_ = L_targets_
prediction: "f32[64, 3]" = self.model(l_inputs_); l_inputs_ = None
mse_loss: "f32[]" = torch.nn.functional.mse_loss(prediction, l_target... | GraphModule |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-intercom/components.py | {
"start": 6150,
"end": 7045
} | class ____(DefaultErrorHandler):
"""
The difference between the built-in `DefaultErrorHandler` and this one is the custom decorator,
applied on top of `interpret_response` to preserve the api calls for a defined amount of time,
calculated using the rate limit headers and not use the custom backoff strat... | ErrorHandlerWithRateLimiter |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/parameterTypes/text.py | {
"start": 530,
"end": 664
} | class ____(Parameter):
"""Editable string, displayed as large text box in the tree."""
itemClass = TextParameterItem
| TextParameter |
python | great-expectations__great_expectations | great_expectations/compatibility/not_imported.py | {
"start": 665,
"end": 2442
} | class ____:
def __init__(self, message: str) -> None:
self.__dict__["gx_error_message"] = message
def __getattr__(self, attr: str) -> NoReturn:
raise ModuleNotFoundError(self.__dict__["gx_error_message"])
@override
def __setattr__(self, key: str, value: Any) -> NoReturn:
raise ... | NotImported |
python | openai__openai-python | src/openai/types/beta/chatkit/chat_session_workflow_param.py | {
"start": 257,
"end": 391
} | class ____(TypedDict, total=False):
enabled: bool
"""Whether tracing is enabled during the session. Defaults to true."""
| Tracing |
python | ray-project__ray | python/ray/data/_internal/execution/operators/task_pool_map_operator.py | {
"start": 503,
"end": 7428
} | class ____(MapOperator):
"""A MapOperator implementation that executes tasks on a task pool."""
def __init__(
self,
map_transformer: MapTransformer,
input_op: PhysicalOperator,
data_context: DataContext,
name: str = "TaskPoolMap",
target_max_block_size_override: ... | TaskPoolMapOperator |
python | cython__cython | tests/run/test_templatelib.py | {
"start": 3364,
"end": 8641
} | class ____(unittest.TestCase, TStringBaseCase):
def test_common(self):
self.assertEqual(type(t'').__name__, 'Template')
self.assertEqual(type(t'').__qualname__, 'Template')
self.assertEqual(type(t'').__module__, 'string.templatelib')
a = 'a'
i = t'{a}'.interpolations[0]
... | TestTemplate |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/asset_graph_view/serializable_entity_subset.py | {
"start": 1071,
"end": 1772
} | class ____(DataclassSerializer):
"""Ensures that the inner PartitionsSubset is converted to a serializable form if necessary."""
def get_storage_name(self) -> str:
# backcompat
return "AssetSubset"
def before_pack(self, value: "SerializableEntitySubset") -> "SerializableEntitySubset": # p... | EntitySubsetSerializer |
python | cython__cython | tests/run/pure_cdef_class_dataclass.py | {
"start": 928,
"end": 1043
} | class ____:
def __repr__(self):
return "DummyObj()"
@cython.dataclasses.dataclass
@cython.cclass
| DummyObj |
python | django__django | tests/middleware_exceptions/middleware.py | {
"start": 1469,
"end": 1669
} | class ____(BaseMiddleware):
async def process_view(self, request, view_func, view_args, view_kwargs):
return HttpResponse("Processed view %s" % view_func.__name__)
| AsyncProcessViewMiddleware |
python | kubernetes-client__python | kubernetes/client/models/rbac_v1_subject.py | {
"start": 383,
"end": 6882
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | RbacV1Subject |
python | allegroai__clearml | clearml/automation/optimization.py | {
"start": 1686,
"end": 9580
} | class ____(_ObjectiveInterface):
"""
Optimization ``Objective`` class to maximize / minimize over all experiments. This class will sample a specific
scalar from all experiments, and maximize / minimize over single scalar (i.e., title and series combination).
``SearchStrategy`` and ``HyperParameterOptim... | Objective |
python | huggingface__transformers | src/transformers/models/seed_oss/modular_seed_oss.py | {
"start": 5775,
"end": 7148
} | class ____(LlamaForCausalLM):
def forward(
self,
**super_kwargs: Unpack[TransformersKwargs],
) -> CausalLMOutputWithPast:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Ind... | SeedOssForCausalLM |
python | doocs__leetcode | solution/3200-3299/3259.Maximum Energy Boost From Two Drinks/Solution.py | {
"start": 0,
"end": 440
} | class ____:
def maxEnergyBoost(self, energyDrinkA: List[int], energyDrinkB: List[int]) -> int:
n = len(energyDrinkA)
f = [[0] * 2 for _ in range(n)]
f[0][0] = energyDrinkA[0]
f[0][1] = energyDrinkB[0]
for i in range(1, n):
f[i][0] = max(f[i - 1][0] + energyDrinkA[... | Solution |
python | eventlet__eventlet | eventlet/db_pool.py | {
"start": 286,
"end": 380
} | class ____(Exception):
pass
def cleanup_rollback(conn):
conn.rollback()
| ConnectTimeout |
python | celery__celery | t/unit/tasks/test_result.py | {
"start": 16673,
"end": 21207
} | class ____:
def test_resultset_repr(self):
assert repr(self.app.ResultSet(
[self.app.AsyncResult(t) for t in ['1', '2', '3']]))
def test_eq_other(self):
assert self.app.ResultSet([
self.app.AsyncResult(t) for t in [1, 3, 3]]) != 1
rs1 = self.app.ResultSet([self.... | test_ResultSet |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/refurb/FURB189.py | {
"start": 80,
"end": 292
} | class ____:
__slots__ = ()
def __setitem__(self, key, value):
if key in self:
raise KeyError(str(key) + ' already set')
return super().__setitem__(key, value)
| SetOnceMappingMixin |
python | sympy__sympy | sympy/physics/quantum/tests/test_dagger.py | {
"start": 1270,
"end": 2632
} | class ____(Expr):
def _eval_adjoint(self):
return I
def test_eval_adjoint():
f = Foo()
d = Dagger(f)
assert d == I
np = import_module('numpy')
def test_numpy_dagger():
if not np:
skip("numpy not installed.")
a = np.array([[1.0, 2.0j], [-1.0j, 2.0]])
adag = a.copy().tra... | Foo |
python | sqlalchemy__sqlalchemy | test/sql/test_quote.py | {
"start": 31207,
"end": 34071
} | class ____(fixtures.TestBase):
def test_concat_quotetrue(self):
q1 = quoted_name("x", True)
self._assert_not_quoted("y" + q1)
def test_concat_quotefalse(self):
q1 = quoted_name("x", False)
self._assert_not_quoted("y" + q1)
def test_concat_quotenone(self):
q1 = quote... | QuotedIdentTest |
python | keras-team__keras | keras/src/layers/reshaping/zero_padding2d.py | {
"start": 287,
"end": 4646
} | class ____(Layer):
"""Zero-padding layer for 2D input (e.g. picture).
This layer can add rows and columns of zeros at the top, bottom, left and
right side of an image tensor.
Example:
>>> input_shape = (1, 1, 2, 2)
>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)
>>> x
[[[... | ZeroPadding2D |
python | facebookresearch__faiss | tests/test_index_accuracy.py | {
"start": 24173,
"end": 25463
} | class ____(unittest.TestCase):
def do_test(self, metric):
d = 32
xt, xb, xq = get_dataset_2(d, 2000, 1000, 200)
index1 = faiss.index_factory(d, "PQ4x4np", metric)
Dref, Iref = faiss.knn(xq, xb, 10, metric)
index1.train(xt)
index1.add(xb)
D1, I1 = index1.sear... | TestRefine |
python | ray-project__ray | rllib/algorithms/impala/impala_tf_policy.py | {
"start": 6181,
"end": 7894
} | class ____:
"""VTrace version of gradient computation logic."""
def __init__(self):
"""No special initialization required."""
pass
def compute_gradients_fn(
self, optimizer: LocalOptimizer, loss: TensorType
) -> ModelGradients:
# Supporting more than one loss/optimizer.... | VTraceClipGradients |
python | streamlit__streamlit | lib/tests/streamlit/git_util_test.py | {
"start": 4798,
"end": 11692
} | class ____(unittest.TestCase):
def test_git_repo_invalid(self):
with patch("git.Repo") as mock:
mock.side_effect = InvalidGitRepositoryError("Not a git repo")
repo = GitRepo(".")
assert not repo.is_valid()
def test_old_git_version(self):
"""If the installed g... | GitUtilTest |
python | kamyu104__LeetCode-Solutions | Python/maximum-area-rectangle-with-point-constraints-i.py | {
"start": 1588,
"end": 2302
} | class ____(object):
def maxRectangleArea(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
result = -1
points.sort()
for i in xrange(len(points)-3):
if points[i][0] != points[i+1][0]:
continue
j = next((j ... | Solution2 |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 342152,
"end": 343283
} | class ____(Response):
"""
Response of tasks.make_public endpoint.
:param updated: Number of tasks updated
:type updated: int
"""
_service = "tasks"
_action = "make_public"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"updated": {
... | MakePublicResponse |
python | ray-project__ray | python/ray/serve/tests/unit/test_grpc_util.py | {
"start": 503,
"end": 4367
} | class ____:
def __init__(self):
self.address = None
def add_insecure_port(self, address):
self.address = address
def fake_service_handler_factory(service_method: str, stream: bool) -> Callable:
def foo() -> bytes:
return f"{'stream' if stream else 'unary'} call from {service_metho... | FakeGrpcServer |
python | sqlalchemy__sqlalchemy | test/orm/test_cascade.py | {
"start": 102736,
"end": 107686
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(self, metadata):
Table(
"core",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("related_one_id", Integer, ForeignKey("re... | OrphanCriterionTest |
python | pandas-dev__pandas | pandas/core/resample.py | {
"start": 70662,
"end": 70914
} | class ____( # type: ignore[misc]
_GroupByMixin, PeriodIndexResampler
):
"""
Provides a resample of a groupby implementation.
"""
@property
def _resampler_cls(self):
return PeriodIndexResampler
| PeriodIndexResamplerGroupby |
python | cherrypy__cherrypy | cherrypy/process/wspbus.py | {
"start": 3575,
"end": 4579
} | class ____(Exception):
"""Exception raised during errors on Bus.publish()."""
delimiter = '\n'
def __init__(self, *args, **kwargs):
"""Initialize ChannelFailures errors wrapper."""
super(ChannelFailures, self).__init__(*args, **kwargs)
self._exceptions = list()
def handle_exce... | ChannelFailures |
python | pyca__cryptography | src/cryptography/hazmat/_oid.py | {
"start": 9196,
"end": 9949
} | class ____:
SERVER_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.1")
CLIENT_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.2")
CODE_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.3")
EMAIL_PROTECTION = ObjectIdentifier("1.3.6.1.5.5.7.3.4")
TIME_STAMPING = ObjectIdentifier("1.3.6.1.5.5.7.3.8")
OCSP_SIGNING = O... | ExtendedKeyUsageOID |
python | apache__airflow | providers/databricks/tests/unit/databricks/hooks/test_databricks.py | {
"start": 51546,
"end": 52730
} | class ____:
"""
Tests for DatabricksHook.
"""
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id=DEFAULT_CONN_ID,
conn_type="databricks",
host=... | TestDatabricksHookTokenInPassword |
python | PyCQA__pylint | tests/functional/f/function_redefined.py | {
"start": 455,
"end": 2025
} | class ____: # [function-redefined]
"""docstring"""
def __init__(self):
pass
def yeah(self):
"""hehehe"""
def yoo(self):
"""yoo"""
def func1():
"""docstring"""
def func2():
"""docstring"""
def func2(): # [function-redefined]
"""docstring"""
__revision__ = 1 # [re... | AAAA |
python | tensorflow__tensorflow | tensorflow/python/client/session_clusterspec_prop_test.py | {
"start": 1754,
"end": 23373
} | class ____(test_util.TensorFlowTestCase):
def testClusterSpecPropagationSimple(self):
server1 = server_lib.Server.create_local_server()
server2 = server_lib.Server.create_local_server()
cluster_def = cluster_pb2.ClusterDef()
job = cluster_def.job.add()
job.name = 'worker'
job.tasks[0] = serve... | SessionClusterSpecPropagationTest |
python | weaviate__weaviate-python-client | weaviate/collections/classes/generative.py | {
"start": 9597,
"end": 10476
} | class ____(_GenerativeConfigRuntime):
generative: Union[GenerativeSearches, _EnumLikeStr] = Field(
default=GenerativeSearches.NVIDIA, frozen=True, exclude=True
)
base_url: Optional[AnyHttpUrl]
max_tokens: Optional[int]
model: Optional[str]
temperature: Optional[float]
top_p: Optional... | _GenerativeNvidia |
python | rq__rq | tests/test_job_dependency.py | {
"start": 349,
"end": 23896
} | class ____(RQTestCase):
def test_dependency_parameter_constraints(self):
"""Ensures the proper constraints are in place for values passed in as job references."""
dep_job = Job.create(func=fixtures.say_hello, connection=self.connection)
# raise error on empty jobs
self.assertRaises(V... | TestJobDependency |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/inference.py | {
"start": 568,
"end": 3322
} | class ____(NamedTuple):
"""The information about an input that can be inferred from the function signature."""
annotation: Any
description: Optional[str]
def _infer_input_description_from_docstring(fn: Callable[..., Any]) -> Mapping[str, Optional[str]]:
doc_str = fn.__doc__
if doc_str is None:
... | InferredOutputProps |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/scalarfloat.py | {
"start": 3694,
"end": 3913
} | class ____(ScalarFloat):
def __new__(cls, value, width=None, underscore=None):
# type: (Any, Any, Any) -> Any
return ScalarFloat.__new__(cls, value, width=width, underscore=underscore)
| ExponentialFloat |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_audio.py | {
"start": 5067,
"end": 6003
} | class ____(nn.Module):
"""Construct the features from raw audio waveform"""
def __init__(self, config):
super().__init__()
self.conv_layers = nn.ModuleList(
[Data2VecAudioConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)]
)
self.gradient_ch... | Data2VecAudioFeatureEncoder |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py | {
"start": 5088,
"end": 5207
} | class ____(ParentI):
def f(self):
builtins.super(ChildI1, self).f() # no __class__ in the local scope
| ChildI1 |
python | pypa__pip | src/pip/_vendor/rich/progress_bar.py | {
"start": 458,
"end": 8154
} | class ____(JupyterMixin):
"""Renders a (progress) bar. Used by rich.progress.
Args:
total (float, optional): Number of steps in the bar. Defaults to 100. Set to None to render a pulsing animation.
completed (float, optional): Number of steps completed. Defaults to 0.
width (int, optiona... | ProgressBar |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/batch.py | {
"start": 2112,
"end": 17276
} | class ____(AwsBaseOperator[BatchClientHook]):
"""
Execute a job on AWS Batch.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BatchOperator`
:param job_name: the name for the job that will run on AWS Batch (templated)
:p... | BatchOperator |
python | conda__conda | conda/exceptions.py | {
"start": 14627,
"end": 14730
} | class ____(CondaError):
def __init__(self, message: str):
super().__init__(message)
| LinkError |
python | pandas-dev__pandas | pandas/tests/indexes/datetimelike_/test_equals.py | {
"start": 374,
"end": 1286
} | class ____:
def test_not_equals_numeric(self, index):
assert not index.equals(Index(index.asi8))
assert not index.equals(Index(index.asi8.astype("u8")))
assert not index.equals(Index(index.asi8).astype("f8"))
def test_equals(self, index):
assert index.equals(index)
asser... | EqualsTests |
python | django-import-export__django-import-export | tests/core/tests/test_results.py | {
"start": 1574,
"end": 5978
} | class ____(SimpleTestCase):
def setUp(self):
self.result = Result()
headers = ["id", "book_name"]
rows = [(1, "Some book")]
self.dataset = Dataset(*rows, headers=headers)
def test_add_dataset_headers(self):
target = ["some_header", "Error"]
self.result.add_datase... | ResultTest |
python | xlwings__xlwings | xlwings/pro/_xlcalamine.py | {
"start": 13642,
"end": 14273
} | class ____(base_classes.Name):
def __init__(self, parent, api):
self.parent = parent # only implemented for Book, not Sheet
self.api = api
@property
def name(self):
return self.api["name"]
@property
def refers_to(self):
sheet_name = self.parent.sheets(self.api["she... | Name |
python | joblib__joblib | joblib/test/test_hashing.py | {
"start": 1276,
"end": 1336
} | class ____(object):
def f(self, x):
return x
| Klass |
python | python-openxml__python-docx | tests/opc/unitdata/rels.py | {
"start": 614,
"end": 1654
} | class ____:
"""Builder class for test Relationships"""
partname_tmpls = {
RT.SLIDE_MASTER: "/ppt/slideMasters/slideMaster%d.xml",
RT.SLIDE: "/ppt/slides/slide%d.xml",
}
def __init__(self):
self.relationships = []
self.next_rel_num = 1
self.next_partnums = {}
... | RelationshipsBuilder |
python | getsentry__sentry | tests/sentry/snuba/test_models.py | {
"start": 987,
"end": 5430
} | class ____(TestCase):
def setUp(self) -> None:
self.snuba_query = create_snuba_query(
SnubaQuery.Type.ERROR,
Dataset.Events,
"release:123",
"count()",
timedelta(minutes=10),
timedelta(minutes=1),
None,
[SnubaQuer... | QuerySubscriptionDataSourceHandlerTest |
python | django__django | tests/delete/models.py | {
"start": 6863,
"end": 7090
} | class ____(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
generic_delete_top = GenericForeignKey("content_type", "object_id")
| GenericB1 |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/input_layer.py | {
"start": 1643,
"end": 16072
} | class ____(base_layer.Layer):
"""Layer to be used as an entry point into a Network (a graph of layers).
It can either wrap an existing tensor (pass an `input_tensor` argument)
or create a placeholder tensor (pass arguments `input_shape`, and
optionally, `dtype`).
It is generally recommend to use the functio... | InputLayer |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/_internal/contextmanager.py | {
"start": 1834,
"end": 2506
} | class ____(type):
_context: deque
# TODO: Task-SDK:
# share_parent_context can go away once the Dag and TaskContext manager in airflow.models are removed and
# everything uses sdk fully for definition/parsing
def __new__(cls, name, bases, namespace, share_parent_context: bool = False, **kwargs: Any... | ContextStackMeta |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 94325,
"end": 94489
} | class ____(TypedDict):
name: str
fields: list[str]
aggregates: list[str]
columns: list[str]
fieldAliases: list[str]
conditions: str
| _QueryDict |
python | mlflow__mlflow | mlflow/genai/judges/optimizers/simba.py | {
"start": 1330,
"end": 5281
} | class ____(DSPyAlignmentOptimizer):
"""
SIMBA (Simplified Multi-Bootstrap Aggregation) alignment optimizer.
Uses DSPy's SIMBA algorithm to optimize judge prompts through
bootstrap aggregation with simplified parametrization.
Note on Logging:
By default, SIMBA optimization suppresses DSPy's... | SIMBAAlignmentOptimizer |
python | getsentry__sentry | src/sentry/users/api/serializers/useremail.py | {
"start": 324,
"end": 449
} | class ____(TypedDict):
email: str
isPrimary: bool
isVerified: bool
@register(UserEmail)
| UserEmailSerializerResponse |
python | encode__django-rest-framework | tests/schemas/views.py | {
"start": 6381,
"end": 6763
} | class ____(generics.GenericAPIView):
serializer_class = ExampleValidatedSerializer
schema = AutoSchema(component_name="Duplicate")
def get(self, *args, **kwargs):
from datetime import datetime
now = datetime.now()
serializer = self.get_serializer(data=now.date(), datetime=now)
... | ExampleAutoSchemaDuplicate1 |
python | google__jax | jax/_src/interpreters/partial_eval.py | {
"start": 54119,
"end": 73533
} | class ____(NamedTuple):
src: MemoryKind
dst: MemoryKind
RematCases = Union[RecomputeType, SaveableType, Offloadable]
RematCases_ = Union[RematCases, bool]
def ensure_enum(case: bool | RematCases) -> RematCases:
if isinstance(case, bool):
return Saveable if case else Recompute
if not isinstance(case, (Reco... | Offloadable |
python | Netflix__metaflow | metaflow/plugins/env_escape/communication/socket_bytestream.py | {
"start": 230,
"end": 3572
} | class ____(ByteStream):
@classmethod
def connect(cls, host, port):
family, socktype, proto, _, sockaddr = socket.getaddrinfo(
host, port, socket.AF_INET, socket.SOCK_STREAM
)
try:
sock = socket.socket(family=family, type=socktype)
sock.settimeout(CONNE... | SocketByteStream |
python | jina-ai__jina | jina/proto/docarray_v1/pb/jina_pb2_grpc.py | {
"start": 15393,
"end": 16386
} | class ____(object):
"""*
jina gRPC service to expose information about running jina version and environment.
"""
def _status(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_detail... | JinaInfoRPCServicer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/initsubclass1.py | {
"start": 1143,
"end": 1279
} | class ____(ClassG):
pass
# This should generate two errors because "a" is not present
# in the object.__init_subclass__ method.
| ClassH |
python | nedbat__coveragepy | tests/test_mixins.py | {
"start": 2344,
"end": 3015
} | class ____(TempDirMixin, RestoreModulesMixin):
"""Tests of SysPathModulesMixin."""
@pytest.mark.parametrize("val", [17, 42])
def test_module_independence(self, val: int) -> None:
self.make_file("xyzzy.py", f"A = {val}")
import xyzzy # pylint: disable=import-error
assert xyzzy.A ==... | RestoreModulessMixinTest |
python | numba__numba | numba/core/target_extension.py | {
"start": 3992,
"end": 4051
} | class ____(GPU):
"""Mark the target as CUDA.
"""
| CUDA |
python | numpy__numpy | numpy/_core/tests/test_unicode.py | {
"start": 9202,
"end": 12071
} | class ____:
"""Check the byteorder of unicode arrays in round-trip conversions"""
def test_values0D(self):
# Check byteorder of 0-dimensional objects
ua = np.array(self.ucs_value * self.ulen, dtype=f'U{self.ulen}')
ua2 = ua.view(ua.dtype.newbyteorder())
# This changes the interp... | ByteorderValues |
python | automl__auto-sklearn | test/test_metalearning/pyMetaLearn/test_meta_base.py | {
"start": 178,
"end": 2253
} | class ____(unittest.TestCase):
_multiprocess_can_split_ = True
def setUp(self):
self.cwd = os.getcwd()
data_dir = os.path.dirname(__file__)
data_dir = os.path.join(data_dir, "test_meta_base_data")
os.chdir(data_dir)
pipeline = autosklearn.pipeline.classification.SimpleC... | MetaBaseTest |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws_tests/s3_tests/test_io_manager.py | {
"start": 826,
"end": 6868
} | class ____(ConfigurableResource, IAttachDifferentObjectToOpContext):
def get_client(self) -> Any:
return construct_s3_client(max_attempts=5)
def get_object_to_set_on_execution_context(self) -> Any:
return self.get_client()
@resource
def s3_test_resource(_):
return construct_s3_client(max_... | S3TestResource |
python | pytorch__pytorch | torch/testing/_internal/distributed/ddp_under_dist_autograd_test.py | {
"start": 17683,
"end": 24047
} | class ____(CommonDdpComparisonTest):
def _run_test_ddp_comparision(self, simulate_uneven_inputs=False):
gLogger.info("Running trainer rank: %s", self.rank)
# Each trainer uses a different random seed. Otherwise, they are going
# to have exactly the same initial model parameters, input, and
... | DdpComparisonTest |
python | bokeh__bokeh | tests/unit/bokeh/server/test_tornado__server.py | {
"start": 11185,
"end": 12706
} | class ____:
def test_app_static_path(self):
app = Application()
app._static_path = "foo"
result = bst.create_static_handler("/prefix", "/key", app)
assert len(result) == 3
assert result[0] == "/prefix/key/static/(.*)"
assert result[1] == StaticFileHandler
as... | Test_create_static_handler |
python | huggingface__transformers | src/transformers/models/vitpose_backbone/modeling_vitpose_backbone.py | {
"start": 9355,
"end": 10461
} | class ____(nn.Module):
def __init__(self, config: VitPoseBackboneConfig):
super().__init__()
in_features = out_features = config.hidden_size
hidden_features = int(config.hidden_size * config.mlp_ratio)
num_experts = config.num_experts
part_features = config.part_features
... | VitPoseBackboneMoeMLP |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 21795,
"end": 21975
} | class ____(models.Model):
name = models.CharField(max_length=15, unique=True)
history = HistoricalRecords(custom_model_name=lambda x: f"Audit{x}")
| OverrideModelNameAsCallable |
python | facebookresearch__faiss | faiss/gpu/test/test_index_cpu_to_gpu.py | {
"start": 230,
"end": 3934
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.res = faiss.StandardGpuResources()
def create_index(self, factory_string):
dimension = 128
n = 2500
db_vectors = np.random.random((n, dimension)).astype('float32')
index = faiss.index_factory(dimen... | TestMoveToGpu |
python | django__django | django/contrib/gis/geos/prototypes/geom.py | {
"start": 1062,
"end": 1249
} | class ____(GEOSFuncFactory):
"Argument is a geometry, return type is an integer."
argtypes = [GEOM_PTR]
restype = c_int
errcheck = staticmethod(check_minus_one)
| IntFromGeom |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/dml.py | {
"start": 64520,
"end": 68695
} | class ____(
DMLWhereBase, UpdateBase, HasSyntaxExtensions[Literal["post_criteria"]]
):
"""Represent a DELETE construct.
The :class:`_expression.Delete` object is created using the
:func:`_expression.delete()` function.
Available extension points:
* ``post_criteria``: applies additional logic ... | Delete |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py | {
"start": 6044,
"end": 6167
} | class ____(ParentI):
def f(self):
__class__ = None
super
builtins.super(ChildI7, self).f()
| ChildI7 |
python | sphinx-doc__sphinx | tests/test_markup/test_markup.py | {
"start": 2583,
"end": 29521
} | class ____(LaTeXTranslator, ForgivingTranslator):
pass
def rst_to_html(rst: str, *, app: SphinxTestApp) -> str:
document = parse_rst(rst, env=app.env)
html_translator = ForgivingHTMLTranslator(document, app.builder)
document.walkabout(html_translator)
html_translated = ''.join(html_translator.frag... | ForgivingLaTeXTranslator |
python | huggingface__transformers | src/transformers/models/zoedepth/modeling_zoedepth.py | {
"start": 6452,
"end": 7460
} | class ____(nn.Module):
def __init__(self, config: ZoeDepthConfig):
super().__init__()
self.layers = nn.ModuleList()
for _ in range(len(config.neck_hidden_sizes)):
self.layers.append(ZoeDepthFeatureFusionLayer(config))
def forward(self, hidden_states):
# reversing the... | ZoeDepthFeatureFusionStage |
python | huggingface__transformers | src/transformers/models/flaubert/modeling_flaubert.py | {
"start": 12711,
"end": 15651
} | class ____(nn.Module):
"""
Compute SQuAD end logits from sequence hidden states.
Args:
config ([`FlaubertConfig`]):
The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
to use.
"""
def __init__(self, config: Flau... | FlaubertPoolerEndLogits |
python | facebook__pyre-check | tools/upgrade/commands/fixme_all.py | {
"start": 760,
"end": 3032
} | class ____(ErrorSuppressingCommand):
def __init__(
self,
command_arguments: CommandArguments,
*,
repository: Repository,
upgrade_version: bool,
error_source: ErrorSource,
) -> None:
super().__init__(command_arguments, repository=repository)
self._u... | FixmeAll |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 13299,
"end": 13446
} | class ____(nodes.Element):
"""Node for "horizontal lists", i.e. lists that should be compressed to
take up less vertical space.
"""
| hlist |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_poly_loading.py | {
"start": 5367,
"end": 5915
} | class ____(
BaseAndSubFixture,
fixtures.DeclarativeMappedTest,
testing.AssertsExecutionResults,
):
use_options = True
def test_load(self):
A, B, ASub, C = self.classes("A", "B", "ASub", "C")
s = fixture_session()
q = (
s.query(A)
.order_by(A.id)
... | LoadBaseAndSubWEagerRelOpt |
python | walkccc__LeetCode | solutions/425. Word Squares/425.py | {
"start": 120,
"end": 615
} | class ____:
def __init__(self, words: list[str]):
self.root = TrieNode()
for word in words:
self._insert(word)
def findBy(self, prefix: str) -> list[str]:
node = self.root
for c in prefix:
if c not in node.children:
return []
node = node.children[c]
return node.startsW... | Trie |
python | euske__pdfminer | pdfminer/pdfinterp.py | {
"start": 1047,
"end": 1273
} | class ____(PDFException):
pass
## Constants
##
LITERAL_PDF = LIT('PDF')
LITERAL_TEXT = LIT('Text')
LITERAL_FONT = LIT('Font')
LITERAL_FORM = LIT('Form')
LITERAL_IMAGE = LIT('Image')
## PDFTextState
##
| PDFInterpreterError |
python | huggingface__transformers | src/transformers/models/informer/modular_informer.py | {
"start": 14458,
"end": 15385
} | class ____(TimeSeriesTransformerDecoderLayer):
def __init__(self, config: InformerConfig, layer_idx: Optional[int] = None):
super().__init__(config)
del self.self_attn
if config.attention_type == "prob":
self.self_attn = InformerProbSparseAttention(
embed_dim=se... | InformerDecoderLayer |
python | keon__algorithms | tests/test_maths.py | {
"start": 9826,
"end": 10717
} | class ____(unittest.TestCase):
"""[summary]
Test for the file factorial.py
Arguments:
unittest {[type]} -- [description]
"""
def test_factorial(self):
self.assertEqual(1, factorial(0))
self.assertEqual(120, factorial(5))
self.assertEqual(3628800, factorial(10))
... | TestFactorial |
python | readthedocs__readthedocs.org | readthedocs/core/unresolver.py | {
"start": 2962,
"end": 3179
} | class ____(Enum):
"""Where the custom domain was resolved from."""
custom_domain = auto()
public_domain = auto()
external_domain = auto()
http_header = auto()
@dataclass(slots=True)
| DomainSourceType |
python | PyCQA__pylint | doc/data/messages/t/too-many-positional-sub-patterns/bad.py | {
"start": 0,
"end": 316
} | class ____:
__match_args__ = ("title", "year")
def __init__(self, title, year, author):
self.title = title
self.year = year
self.author = author
def func(item: Book):
match item:
case Book("title", 2000, "author"): # [too-many-positional-sub-patterns]
...
| Book |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.