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 | numpy__numpy | numpy/_core/tests/test_half.py | {
"start": 515,
"end": 25260
} | class ____:
def _create_arrays_all(self):
# An array of all possible float16 values
all_f16 = np.arange(0x10000, dtype=uint16)
all_f16 = all_f16.view(float16)
# NaN value can cause an invalid FP exception if HW is being used
with np.errstate(invalid='ignore'):
al... | TestHalf |
python | weaviate__weaviate-python-client | weaviate/collections/queries/near_object/generate/async_.py | {
"start": 318,
"end": 473
} | class ____(
Generic[Properties, References],
_NearObjectGenerateExecutor[ConnectionAsync, Properties, References],
):
pass
| _NearObjectGenerateAsync |
python | networkx__networkx | networkx/utils/tests/test_mapped_queue.py | {
"start": 1064,
"end": 5344
} | class ____:
def setup_method(self):
pass
def _check_map(self, q):
assert q.position == {elt: pos for pos, elt in enumerate(q.heap)}
def _make_mapped_queue(self, h):
q = MappedQueue()
q.heap = h
q.position = {elt: pos for pos, elt in enumerate(h)}
return q
... | TestMappedQueue |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 96128,
"end": 98701
} | class ____(fixtures.MappedTest):
"""'viewonly' mappings with overlapping PK column names."""
@classmethod
def define_tables(cls, metadata):
Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
)... | ViewOnlyOverlappingNames |
python | django__django | tests/m2o_recursive/tests.py | {
"start": 73,
"end": 676
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.r = Category.objects.create(id=None, name="Root category", parent=None)
cls.c = Category.objects.create(id=None, name="Child category", parent=cls.r)
def test_m2o_recursive(self):
self.assertSequenceEqual(self.r.child_se... | ManyToOneRecursiveTests |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/visitors/base.py | {
"start": 292,
"end": 1932
} | class ____(ABC, Generic[TVisited]):
"""
Abstract visitor that defines a visiting behavior of a `QueryExpression`.
"""
def visit(self, query_expression: QueryExpression) -> TVisited:
if isinstance(query_expression, Formula):
return self._visit_formula(query_expression)
elif i... | QueryExpressionVisitor |
python | huggingface__transformers | tests/models/video_llava/test_modeling_video_llava.py | {
"start": 16492,
"end": 22969
} | class ____(unittest.TestCase):
def setUp(self):
self.processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
def tearDown(self):
cleanup(torch_device, gc_collect=True)
@slow
@require_bitsandbytes
def test_small_model_integration_test(self):
# Let' ... | VideoLlavaForConditionalGenerationIntegrationTest |
python | huggingface__transformers | src/transformers/testing_utils.py | {
"start": 111421,
"end": 149173
} | class ____(UserDict[PackedDeviceProperties, Any]):
def get_expectation(self) -> Any:
"""
Find best matching expectation based on environment device properties. We look at device_type, major and minor
versions of the drivers. Expectations are stored as a dictionary with keys of the form
... | Expectations |
python | getsentry__sentry-python | sentry_sdk/tracing_utils.py | {
"start": 18103,
"end": 40697
} | class ____:
"""
The W3C Baggage header information (see https://www.w3.org/TR/baggage/).
Before mutating a `Baggage` object, calling code must check that `mutable` is `True`.
Mutating a `Baggage` object that has `mutable` set to `False` is not allowed, but
it is the caller's responsibility to enfor... | Baggage |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/config.py | {
"start": 9383,
"end": 9569
} | class ____(graphene.ObjectType):
pipeline_name = graphene.NonNull(graphene.String)
class Meta:
name = "PipelineConfigValidationValid"
| GraphenePipelineConfigValidationValid |
python | arrow-py__arrow | arrow/locales.py | {
"start": 38481,
"end": 40237
} | class ____(SlavicBaseLocale):
names = ["ua", "uk", "uk-ua"]
past = "{0} тому"
future = "за {0}"
timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = {
"now": "зараз",
"second": "секунда",
"seconds": "{0} кілька секунд",
"minute": "хвилину",
... | UkrainianLocale |
python | sqlalchemy__sqlalchemy | examples/space_invaders/space_invaders.py | {
"start": 6740,
"end": 7030
} | class ____(EnemyGlyph):
"""Describe an enemy that's part of the "army"."""
__mapper_args__ = {"polymorphic_identity": "army"}
def glyph_for_state(self, coord, state):
if state["flip"]:
return self.alt_data
else:
return self.data
| ArmyGlyph |
python | ray-project__ray | python/ray/data/_internal/execution/operators/hash_aggregate.py | {
"start": 3769,
"end": 8579
} | class ____(HashShufflingOperatorBase):
def __init__(
self,
data_context: DataContext,
input_op: PhysicalOperator,
key_columns: Tuple[str],
aggregation_fns: Tuple[AggregateFn],
*,
num_partitions: Optional[int] = None,
aggregator_ray_remote_args_override... | HashAggregateOperator |
python | huggingface__transformers | src/transformers/models/sam2/modular_sam2.py | {
"start": 2527,
"end": 11625
} | class ____(SamImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_DEFAULT_MEAN
image_std = IMAGENET_DEFAULT_STD
size = {"height": 1024, "width": 1024}
mask_size = {"height": 256, "width": 256}
do_resize = True
do_rescale = True
do_normalize = True
do_con... | Sam2ImageProcessorFast |
python | run-llama__llama_index | llama-index-integrations/node_parser/llama-index-node-parser-topic/llama_index/node_parser/topic/base.py | {
"start": 4010,
"end": 12422
} | class ____(NodeParser):
"""Topic Based node parser."""
max_chunk_size: int = Field(
default=1000,
description="The maximum number of tokens in a chunk.",
)
window_size: int = Field(
default=5,
description="Paragraph sliding window size",
)
llm: LLM = Field(
... | TopicNodeParser |
python | doocs__leetcode | solution/1100-1199/1157.Online Majority Element In Subarray/Solution.py | {
"start": 136,
"end": 1716
} | class ____:
def __init__(self, nums):
self.nums = nums
n = len(nums)
self.tr = [Node() for _ in range(n << 2)]
self.build(1, 1, n)
def build(self, u, l, r):
self.tr[u].l, self.tr[u].r = l, r
if l == r:
self.tr[u].x = self.nums[l - 1]
self.... | SegmentTree |
python | kamyu104__LeetCode-Solutions | Python/hash-divided-string.py | {
"start": 38,
"end": 357
} | class ____(object):
def stringHash(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
result = (chr(ord('a')+reduce(lambda accu, x: (accu+x)%26, (ord(s[i+j])-ord('a') for j in xrange(k)), 0)) for i in xrange(0, len(s), k))
return "".join(result)
| Solution |
python | pandas-dev__pandas | pandas/tests/indexes/interval/test_astype.py | {
"start": 336,
"end": 2457
} | class ____:
"""Tests common to IntervalIndex with any subtype"""
def test_astype_idempotent(self, index):
result = index.astype("interval")
tm.assert_index_equal(result, index)
result = index.astype(index.dtype)
tm.assert_index_equal(result, index)
def test_astype_object(s... | AstypeTests |
python | doocs__leetcode | solution/0500-0599/0506.Relative Ranks/Solution.py | {
"start": 0,
"end": 370
} | class ____:
def findRelativeRanks(self, score: List[int]) -> List[str]:
n = len(score)
idx = list(range(n))
idx.sort(key=lambda x: -score[x])
top3 = ["Gold Medal", "Silver Medal", "Bronze Medal"]
ans = [None] * n
for i, j in enumerate(idx):
ans[j] = top3[i... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B024.py | {
"start": 2341,
"end": 2508
} | class ____(ABC): # error (not an abstract attribute)
foo: int = 2
# this doesn't actually declare a class variable, it's just an expression
| abc_set_class_variable_3 |
python | Farama-Foundation__Gymnasium | gymnasium/envs/mujoco/half_cheetah_v5.py | {
"start": 233,
"end": 16005
} | class ____(MujocoEnv, utils.EzPickle):
r"""
## Description
This environment is based on the work of P. Wawrzyński in ["A Cat-Like Robot Real-Time Learning to Run"](http://staff.elka.pw.edu.pl/~pwawrzyn/pub-s/0812_LSCLRR.pdf).
The HalfCheetah is a 2-dimensional robot consisting of 9 body parts and 8 join... | HalfCheetahEnv |
python | django__django | tests/admin_views/models.py | {
"start": 10611,
"end": 10711
} | class ____(Title):
the_recommender = models.ForeignKey(Recommender, models.CASCADE)
| Recommendation |
python | pytorch__pytorch | test/distributed/_composable/test_composability/test_2d_composability.py | {
"start": 18279,
"end": 21246
} | class ____(DTensorTestBase):
def init_model(self, device_type, model_parallel_size=2):
torch.manual_seed(0)
model = MLPModule(device_type)
torch.manual_seed(0)
twod_model = MLPModule(device_type)
model = DDP(model)
# 2-D mesh is [dp, tp]
world_size = dist.get... | Test2dFSDP1ParallelIntegration |
python | pypa__warehouse | tests/common/db/classifiers.py | {
"start": 129,
"end": 215
} | class ____(WarehouseFactory):
class Meta:
model = Classifier
| ClassifierFactory |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/partition_sets.py | {
"start": 4437,
"end": 4648
} | class ____(graphene.ObjectType):
runStatus = graphene.NonNull(GrapheneRunStatus)
count = graphene.NonNull(graphene.Int)
class Meta:
name = "PartitionStatusCounts"
| GraphenePartitionStatusCounts |
python | huggingface__transformers | src/transformers/models/glm46v/video_processing_glm46v.py | {
"start": 2491,
"end": 11541
} | class ____(BaseVideoProcessor):
resample = PILImageResampling.BICUBIC
size = {"shortest_edge": 112 * 112, "longest_edge": 28 * 28 * 2 * 30000}
max_image_size = {"longest_edge": 28 * 28 * 2 * 30000}
image_mean = OPENAI_CLIP_MEAN
image_std = OPENAI_CLIP_STD
do_resize = True
do_rescale = True
... | Glm46VVideoProcessor |
python | doocs__leetcode | lcof2/剑指 Offer II 065. 最短的单词编码/Solution2.py | {
"start": 0,
"end": 391
} | class ____:
def __init__(self):
self.children = [None] * 26
def insert(self, w):
node = self
pref = True
for c in w:
idx = ord(c) - ord("a")
if node.children[idx] is None:
node.children[idx] = Trie()
pref = False
... | Trie |
python | pytorch__pytorch | torch/testing/_internal/common_device_type.py | {
"start": 51283,
"end": 54875
} | class ____(skipIf):
def __init__(self, dep, reason):
device_type = torch._C._get_privateuse1_backend_name()
super().__init__(dep, reason, device_type=device_type)
def _has_sufficient_memory(device, size):
device_ = torch.device(device)
device_type = device_.type
if device_type in ["cud... | skipPRIVATEUSE1If |
python | Farama-Foundation__Gymnasium | gymnasium/envs/box2d/bipedal_walker.py | {
"start": 27828,
"end": 28274
} | class ____:
def __init__(self):
raise error.Error(
"Error initializing BipedalWalkerHardcore Environment.\n"
"Currently, we do not support initializing this mode of environment by calling the class directly.\n"
"To use this environment, instead create it by specifying the... | BipedalWalkerHardcore |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 96764,
"end": 97109
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("ref_id", "client_mutation_id")
ref_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="refId")
client_mutation_id = sgqlc.types.Field(String, graphql_name="client... | DeleteRefInput |
python | pytorch__pytorch | torch/_dynamo/testing.py | {
"start": 8018,
"end": 8982
} | class ____:
def __init__(self, backend: str) -> None:
self.frame_count: Union[int, CompileCounterInt] = 0
self.backend = backend
self.graphs: list[torch.fx.GraphModule] = []
self.clear()
def __call__(
self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]
... | CompileCounterWithBackend |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF033.py | {
"start": 1203,
"end": 1298
} | class ____:
def __post_init__(self, bar: int = (x := 1)) -> None:
pass
@dataclass
| Foo |
python | django__django | tests/staticfiles_tests/test_finders.py | {
"start": 288,
"end": 967
} | class ____:
"""
Base finder test mixin.
On Windows, sometimes the case of the path we ask the finders for and the
path(s) they find can differ. Compare them using os.path.normcase() to
avoid false negatives.
"""
def test_find_first(self):
src, dst = self.find_first
found = ... | TestFinders |
python | ansible__ansible | lib/ansible/utils/unsafe_proxy.py | {
"start": 937,
"end": 2166
} | class ____(str):
def __new__(cls, value):
return TrustedAsTemplate.untag(value)
def _wrap_dict(v):
return dict((wrap_var(k), wrap_var(item)) for k, item in v.items())
def _wrap_sequence(v):
"""Wraps a sequence with unsafe, not meant for strings, primarily
``tuple`` and ``list``
"""
v... | NativeJinjaUnsafeText |
python | apache__airflow | airflow-e2e-tests/tests/airflow_e2e_tests/remote_log_tests/test_remote_logging.py | {
"start": 971,
"end": 3955
} | class ____:
airflow_client = AirflowClient()
dag_id = "example_xcom_test"
task_count = 6
retry_interval_in_seconds = 1
max_retries = 5
def test_dag_unpause(self):
self.airflow_client.un_pause_dag(
TestRemoteLogging.dag_id,
)
def test_remote_logging_s3(self):
... | TestRemoteLogging |
python | django__django | tests/sitemaps_tests/urls/http.py | {
"start": 2612,
"end": 2980
} | class ____(Sitemap):
"""All items have `lastmod`."""
location = "/location/"
def items(self):
o1 = TestModel()
o1.lastmod = datetime(2013, 3, 13, 10, 0, 0)
o2 = TestModel()
o2.lastmod = datetime(2014, 3, 13, 10, 0, 0)
return [o1, o2]
def lastmod(self, obj):
... | CallableLastmodFullSitemap |
python | huggingface__transformers | src/transformers/models/gemma/modular_gemma.py | {
"start": 10253,
"end": 10592
} | class ____(LlamaPreTrainedModel):
@torch.no_grad()
def _init_weights(self, module):
PreTrainedModel._init_weights(self, module)
# We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
if "RMSNorm" in module.__class__.__name__:
init.zeros_(module.weight)... | GemmaPreTrainedModel |
python | automl__auto-sklearn | test/test_pipeline/test_create_searchspace_util_classification.py | {
"start": 821,
"end": 6534
} | class ____(unittest.TestCase):
_multiprocess_can_split_ = True
def test_get_match_array_sparse_and_dense(self):
# preproc is empty
preprocessors = OrderedDict()
preprocessors["pca"] = PCA
classifiers = OrderedDict()
classifiers["lda"] = LDA
# Sparse + dense
... | TestCreateClassificationSearchspace |
python | google__pytype | pytype/tests/test_recovery1.py | {
"start": 79,
"end": 3777
} | class ____(test_base.BaseTest):
"""Tests for recovering after errors.
The type inferencer can warn about bad code, but it should never blow up.
These tests check that we don't faceplant when we encounter difficult code.
"""
def test_bad_subtract(self):
ty = self.Infer(
"""
def f():
... | RecoveryTests |
python | celery__celery | t/integration/test_loader.py | {
"start": 104,
"end": 1352
} | class ____:
def test_autodiscovery__when_packages_exist(self, manager):
# Arrange
expected_package_name, _, module_name = __name__.rpartition('.')
unexpected_package_name = 'datetime.datetime'
# Act
manager.app.autodiscover_tasks([expected_package_name, unexpected_package_na... | test_loader |
python | sympy__sympy | sympy/functions/special/error_functions.py | {
"start": 42483,
"end": 47256
} | class ____(DefinedFunction):
r"""
The classical logarithmic integral.
Explanation
===========
For use in SymPy, this function is defined as
.. math:: \operatorname{li}(x) = \int_0^x \frac{1}{\log(t)} \mathrm{d}t \,.
Examples
========
>>> from sympy import I, oo, li
>>> from ... | li |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super1.py | {
"start": 1482,
"end": 1555
} | class ____(Generic[T]):
def __init__(self, val: T):
pass
| ClassF |
python | facebookresearch__faiss | tests/test_index_composite.py | {
"start": 2010,
"end": 7214
} | class ____(unittest.TestCase):
def do_merge_then_remove(self, ondisk):
d = 10
nb = 1000
nq = 200
nt = 200
xt, xb, xq = get_dataset_2(d, nt, nb, nq)
quantizer = faiss.IndexFlatL2(d)
index1 = faiss.IndexIVFFlat(quantizer, d, 20)
index1.train(xt)
... | TestRemove |
python | pennersr__django-allauth | allauth/mfa/base/forms.py | {
"start": 1273,
"end": 1428
} | class ____(BaseAuthenticateForm):
def save(self):
post_authentication(context.request, self.authenticator, reauthenticated=True)
| ReauthenticateForm |
python | tensorflow__tensorflow | tensorflow/python/distribute/tpu_values.py | {
"start": 14386,
"end": 16682
} | class ____(TPUVariableMixin, values.SyncOnReadVariable):
"""Holds a map from replica to variables whose values are reduced on save."""
def assign_sub(self, *args, **kwargs):
if tpu_util.enclosing_tpu_context() is None:
return values.SyncOnReadVariable.assign_sub(self, *args, **kwargs)
else:
ret... | TPUSyncOnReadVariable |
python | docker__docker-py | tests/integration/api_config_test.py | {
"start": 165,
"end": 2818
} | class ____(BaseAPIIntegrationTest):
@classmethod
def setup_class(cls):
client = cls.get_client_instance()
force_leave_swarm(client)
cls._init_swarm(client)
@classmethod
def teardown_class(cls):
client = cls.get_client_instance()
force_leave_swarm(client)
def... | ConfigAPITest |
python | doocs__leetcode | solution/1800-1899/1857.Largest Color Value in a Directed Graph/Solution.py | {
"start": 0,
"end": 929
} | class ____:
def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:
n = len(colors)
indeg = [0] * n
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
indeg[b] += 1
q = deque()
dp = [[0] * 26 for _ in range(n)]
for ... | Solution |
python | python-jsonschema__jsonschema | jsonschema/_utils.py | {
"start": 125,
"end": 923
} | class ____(MutableMapping):
"""
Dictionary which uses normalized URIs as keys.
"""
def normalize(self, uri):
return urlsplit(uri).geturl()
def __init__(self, *args, **kwargs):
self.store = dict()
self.store.update(*args, **kwargs)
def __getitem__(self, uri):
re... | URIDict |
python | cython__cython | Cython/Compiler/UFuncs.py | {
"start": 807,
"end": 1328
} | class ____:
"""
Everything related to defining an input/output argument for a ufunc
type - PyrexType
type_constant - str such as "NPY_INT8" representing numpy dtype constants
injected_typename - str representing a name that can be used to look up the type
in Cython code
... | _ArgumentInfo |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 71446,
"end": 71717
} | class ____(_ConfigCreateModel):
name: str
@field_validator("name")
def check_name(cls, v: str) -> str:
if v in ["id", "vector"]:
raise ValueError(f"Property name '{v}' is reserved and cannot be used")
return v
| _ReferencePropertyBase |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 985,
"end": 1046
} | class ____[T]: # trailing comment
pass
| TestTrailingComment3 |
python | PyCQA__isort | tests/unit/profiles/test_django.py | {
"start": 3687,
"end": 3741
} | class ____(OSError):
pass"""
)
| UnreadablePostError |
python | mozilla__bleach | tests/test_parse_shim.py | {
"start": 117,
"end": 4149
} | class ____:
scheme: str = ""
netloc: str = ""
path: str = ""
params: str = ""
query: str = ""
fragment: str = ""
# Tests from
# https://github.com/web-platform-tests/wpt/blob/master/url/resources/urltestdata.json
# commit ee566de4c5c65d7e8af8b2500f9b85a646ffeaa5
@pytest.mark.parametrize(
... | ParseResult |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 55555,
"end": 56865
} | class ____(fixtures.TestBase):
__only_on__ = "postgresql"
__sparse_driver_backend__ = True
@testing.fixture()
def scalar(self, connection):
def go(expression):
return connection.scalar(select(expression))
return go
def test_cast_name(self, scalar):
eq_(scalar(c... | RegClassTest |
python | doocs__leetcode | solution/3200-3299/3201.Find the Maximum Length of Valid Subsequence I/Solution.py | {
"start": 0,
"end": 345
} | class ____:
def maximumLength(self, nums: List[int]) -> int:
k = 2
f = [[0] * k for _ in range(k)]
ans = 0
for x in nums:
x %= k
for j in range(k):
y = (j - x + k) % k
f[x][y] = f[y][x] + 1
ans = max(ans, f[x][y]... | Solution |
python | numba__numba | numba/core/rewrites/static_getitem.py | {
"start": 5349,
"end": 6624
} | class ____(Rewrite):
"""
Rewrite IR statements of the kind `setitem(target=arr, index=$constXX, ...)`
where `$constXX` is a known constant as
`static_setitem(target=arr, index=<constant value>, ...)`.
"""
def match(self, func_ir, block, typemap, calltypes):
self.setitems = setitems = {}... | RewriteConstSetitems |
python | pallets__click | src/click/testing.py | {
"start": 2050,
"end": 2799
} | class ____:
"""Mixes `<stdout>` and `<stderr>` streams.
The result is available in the ``output`` attribute.
.. versionadded:: 8.2
"""
def __init__(self) -> None:
self.output: io.BytesIO = io.BytesIO()
self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)
self.stderr:... | StreamMixer |
python | pytorch__pytorch | torch/testing/_internal/jit_utils.py | {
"start": 2304,
"end": 3084
} | class ____:
"""
A context manager that is useful for checking that error messages highlight
the correct part of the source code.
"""
def __init__(self, test_case, exception, regex, highlight):
self.test_case = test_case
self.exception_type = exception
self.regex = regex
... | _AssertRaisesRegexWithHighlightContext |
python | tiangolo__fastapi | docs_src/sql_databases/tutorial002_an_py39.py | {
"start": 504,
"end": 2604
} | class ____(HeroBase):
name: Union[str, None] = None
age: Union[int, None] = None
secret_name: Union[str, None] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, connect_args=connect_args)
d... | HeroUpdate |
python | ansible__ansible | lib/ansible/module_utils/facts/system/service_mgr.py | {
"start": 1375,
"end": 6666
} | class ____(BaseFactCollector):
name = 'service_mgr'
_fact_ids = set() # type: t.Set[str]
required_facts = set(['platform', 'distribution'])
@staticmethod
def is_systemd_managed(module):
# tools must be installed
if module.get_bin_path('systemctl'):
# this should show i... | ServiceMgrFactCollector |
python | django__django | django/utils/safestring.py | {
"start": 653,
"end": 2178
} | class ____(str, SafeData):
"""
A str subclass that has been specifically marked as "safe" for HTML output
purposes.
"""
__slots__ = ()
def __add__(self, rhs):
"""
Concatenating a safe string with another safe bytestring or
safe string is safe. Otherwise, the result is n... | SafeString |
python | PrefectHQ__prefect | src/prefect/server/events/schemas/automations.py | {
"start": 21199,
"end": 21849
} | class ____(ORMBaseModel, AutomationCore, extra="ignore"):
def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
self.trigger._set_parent(self)
@classmethod
def model_validate(
cls: type[Self],
obj: Any,
*,
strict: bool | None = None... | Automation |
python | getsentry__sentry | tests/sentry/api/endpoints/test_rule_snooze.py | {
"start": 426,
"end": 914
} | class ____(APITestCase):
def setUp(self) -> None:
self.issue_alert_rule = Rule.objects.create(
label="test rule",
project=self.project,
owner_team_id=self.team.id,
)
self.metric_alert_rule = self.create_alert_rule(
organization=self.project.org... | BaseRuleSnoozeTest |
python | great-expectations__great_expectations | tests/integration/sql_session_manager.py | {
"start": 1329,
"end": 4264
} | class ____:
POOL_CONFIG = PoolConfig(
poolclass=QueuePool,
pool_size=2,
max_overflow=3,
pool_recycle=5400, # 1.5 hours
pool_timeout=30, # 30 seconds
pool_pre_ping=True,
)
def __init__(self):
# It's ok to use ConnectionDetails as the key since that c... | SessionSQLEngineManager |
python | allegroai__clearml | clearml/automation/optimization.py | {
"start": 11290,
"end": 39893
} | class ____(object):
"""
The base search strategy class. Inherit this class to implement your custom strategy.
"""
_tag = "optimization"
_job_class: ClearmlJob = ClearmlJob
def __init__(
self,
base_task_id: str,
hyper_parameters: Sequence[Parameter],
objective_me... | SearchStrategy |
python | PrefectHQ__prefect | src/prefect/client/schemas/responses.py | {
"start": 16508,
"end": 16678
} | class ____(PrefectBaseModel):
model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore")
id: UUID
name: str
limit: int
| MinimalConcurrencyLimitResponse |
python | huggingface__transformers | src/transformers/models/blip_2/modeling_blip_2.py | {
"start": 3338,
"end": 5399
} | 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... | Blip2ImageTextMatchingModelOutput |
python | pytorch__pytorch | torch/ao/nn/intrinsic/qat/modules/conv_fused.py | {
"start": 18484,
"end": 20301
} | class ____(nnqat.Conv1d, nni._FusedModule):
r"""A ConvReLU1d module is a fused module of Conv1d and ReLU, attached with
FakeQuantize modules for weight for
quantization aware training.
We combined the interface of :class:`~torch.nn.Conv1d` and
:class:`~torch.nn.BatchNorm1d`.
Attributes:
... | ConvReLU1d |
python | pytorch__pytorch | test/distributed/tensor/debug/test_comm_mode_features.py | {
"start": 731,
"end": 12093
} | class ____(DTensorTestBase):
# checks if parameter / sharding info is the same as ground truth
def check_same_set_of_keys(self, dict1, dict2):
"""
Used to ensure the comm_mode parameter/sharding dictionaries contain the same information produced by the
ground truth
"""
di... | TestCommModeFeatures |
python | coleifer__peewee | tests/models.py | {
"start": 148041,
"end": 150942
} | class ____(PGOnConflictTests, ModelTestCase):
@requires_postgresql
@requires_models(UKV)
def test_conflict_target_constraint(self):
u1 = UKV.create(key='k1', value='v1')
u2 = UKV.create(key='k2', value='v2')
ret = (UKV.insert(key='k1', value='v1', extra='e1')
.on_conf... | TestUpsertPostgresql |
python | sympy__sympy | sympy/functions/combinatorial/numbers.py | {
"start": 70493,
"end": 71753
} | class ____(DefinedFunction):
r"""
Calculate the Euler totient function phi(n)
``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n
that are relatively prime to n.
Examples
========
>>> from sympy.functions.combinatorial.numbers import totient
>>> totient(1)
1
... | totient |
python | huggingface__transformers | src/transformers/models/flava/modeling_flava.py | {
"start": 31794,
"end": 32379
} | class ____(nn.Module):
def __init__(self, config: FlavaPossibleConfigs):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states: torch.Tensor):
# We "pool" the model by simply taking the hidde... | FlavaPooler |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-lindorm/llama_index/vector_stores/lindorm/base.py | {
"start": 909,
"end": 27744
} | class ____:
"""
Object encapsulating an Lindorm index that has vector search enabled.
If the index does not yet exist, it is created during init.
Therefore, the underlying index is assumed to either:
1) not exist yet or 2) be created due to previous usage of this class.
Two index types are ava... | LindormVectorClient |
python | dask__dask | dask/tests/test_utils.py | {
"start": 20540,
"end": 24958
} | class ____:
pass
def test_typename_on_instances():
instance = MyType()
assert typename(instance) == typename(MyType)
def test_cached_cumsum():
a = (1, 2, 3, 4)
x = cached_cumsum(a)
y = cached_cumsum(a, initial_zero=True)
assert x == (1, 3, 6, 10)
assert y == (0, 1, 3, 6, 10)
def te... | MyType |
python | anthropics__anthropic-sdk-python | tests/lib/streaming/test_partial_json.py | {
"start": 427,
"end": 6284
} | class ____:
def test_trailing_strings_mode_header(self) -> None:
"""Test behavior differences with and without the beta header for JSON parsing."""
message = ParsedBetaMessage(
id="msg_123",
type="message",
role="assistant",
content=[
B... | TestPartialJson |
python | PyCQA__pylint | tests/functional/t/too/too_many_ancestors_ignored_parents.py | {
"start": 585,
"end": 621
} | class ____(D, E):
"""3 parents"""
| B |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/asyncpg.py | {
"start": 9015,
"end": 9083
} | class ____(sqltypes.String):
render_bind_cast = True
| AsyncpgString |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 58751,
"end": 59528
} | class ____:
def test_exp_values(self):
x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for dt in ['f', 'd', 'g']:
log2_ = 0.69314718055994530943
xf = np.array(x, dtype=dt)
yf = np.array(y, dtype=dt) * log2_
... | TestExp |
python | pytorch__pytorch | torch/_inductor/codegen/cutedsl/cutedsl_template.py | {
"start": 654,
"end": 4933
} | class ____(KernelTemplate):
"""Template for generating CuteDSL (CUTLASS Python DSL) kernels."""
kernel_type: type[Any] = CuteDSLTemplateKernel
index_counter = itertools.count()
all_templates: dict[str, "CuteDSLTemplate"] = {}
def __init__(
self,
name: str,
source: str,
... | CuteDSLTemplate |
python | pytorch__pytorch | torch/_dynamo/variables/misc.py | {
"start": 74656,
"end": 74741
} | class ____(ConstantLikeVariable):
_error_prefix = "re.Pattern"
| RegexPatternVariable |
python | huggingface__transformers | src/transformers/models/patchtsmixer/modeling_patchtsmixer.py | {
"start": 24605,
"end": 31230
} | class ____(nn.Module):
"""Pretraining head.
Args:
config (`PatchTSMixerConfig`):
Configuration.
"""
def __init__(self, config: PatchTSMixerConfig):
super().__init__()
self.dropout_layer = nn.Dropout(config.head_dropout)
self.base_pt_block = nn.Linear(config... | PatchTSMixerPretrainHead |
python | gevent__gevent | src/gevent/tests/test__socket_dns.py | {
"start": 19029,
"end": 20294
} | class ____(TestCase):
NORMALIZE_GHBA_IGNORE_ALIAS = True
def __normalize_name(self, result):
if (RESOLVER_ARES or RESOLVER_DNSPYTHON) and isinstance(result, tuple):
# The system resolver can return the FQDN, in the first result,
# when given certain configurations. But c-ares an... | TestHostname |
python | joke2k__faker | tests/providers/test_person.py | {
"start": 61553,
"end": 62068
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("ta_IN")
Faker.seed(0)
def test_gender_first_names(self):
"""simple test to verify that we are pulling gender specific names"""
name = self.fake.first_name_female()
assert name in TaINProvider.first_names_... | TestTaIN |
python | Netflix__metaflow | metaflow/exception.py | {
"start": 1275,
"end": 1841
} | class ____(Exception):
headline = "Flow failed"
def __init__(self, msg="", lineno=None, source_file=None):
self.message = msg
self.line_no = lineno
self.source_file = source_file
super(MetaflowException, self).__init__()
def __str__(self):
prefix = ""
if sel... | MetaflowException |
python | getsentry__sentry | src/sentry/dynamic_sampling/tasks/boost_low_volume_transactions.py | {
"start": 11970,
"end": 24271
} | class ____:
"""
Fetch transactions for all orgs and all projects with pagination orgs and projects with count per root project
org_ids: the orgs for which the projects & transactions should be returned
large_transactions: if True it returns transactions with the largest count
... | FetchProjectTransactionVolumes |
python | pikepdf__pikepdf | src/pikepdf/form.py | {
"start": 25864,
"end": 27311
} | class ____(AppearanceStreamGenerator):
"""Basic appearance stream generator using QPDF's default algorithm.
It is thus subject to all the same
`limitations <https://qpdf.readthedocs.io/en/stable/cli.html#option-generate-appearances>`_.
Briefly summarized, these limitations are:
* Cannot generate ... | DefaultAppearanceStreamGenerator |
python | openai__openai-python | src/openai/types/responses/file_search_tool_param.py | {
"start": 817,
"end": 1404
} | class ____(TypedDict, total=False):
hybrid_search: RankingOptionsHybridSearch
"""
Weights that control how reciprocal rank fusion balances semantic embedding
matches versus sparse keyword matches when hybrid search is enabled.
"""
ranker: Literal["auto", "default-2024-11-15"]
"""The ranker ... | RankingOptions |
python | matplotlib__matplotlib | lib/matplotlib/scale.py | {
"start": 6152,
"end": 7348
} | class ____(ScaleBase):
"""
The default linear scale.
"""
name = 'linear'
@_make_axis_parameter_optional
def __init__(self, axis):
# This method is present only to prevent inheritance of the base class'
# constructor docstring, which would otherwise end up interpolated into
... | LinearScale |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/input/vt100_parser.py | {
"start": 1077,
"end": 1927
} | class ____(Dict[str, bool]):
"""
Dictionary that maps input sequences to a boolean indicating whether there is
any key that start with this characters.
"""
def __missing__(self, prefix: str) -> bool:
# (hard coded) If this could be a prefix of a CPR response, return
# True.
... | _IsPrefixOfLongerMatchCache |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 435552,
"end": 437502
} | class ____(ValueChannelMixin, core.OrderValueDef):
"""
OrderValue schema wrapper.
Parameters
----------
value : dict, float, :class:`ExprRef`
A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient
definition <https://vega.github.io/vega-lite/docs/types.html#g... | OrderValue |
python | joke2k__faker | tests/providers/test_person.py | {
"start": 6536,
"end": 8420
} | class ____(unittest.TestCase):
"""Tests for az_AZ locale person provider"""
def setUp(self):
self.fake = Faker("az")
Faker.seed(0)
def test_first_name(self):
# General first name
name = self.fake.first_name()
assert name
self.assertIsInstance(name, str)
... | TestAzAz |
python | paramiko__paramiko | paramiko/_winapi.py | {
"start": 1454,
"end": 3634
} | class ____(builtins.WindowsError):
"""more info about errors at
http://msdn.microsoft.com/en-us/library/ms681381(VS.85).aspx"""
def __init__(self, value=None):
if value is None:
value = ctypes.windll.kernel32.GetLastError()
strerror = format_system_message(value)
args = ... | WindowsError |
python | python-markdown__markdown | tests/test_meta.py | {
"start": 74,
"end": 921
} | class ____(unittest.TestCase):
def test_get_version(self):
"""Test that _get_version formats __version_info__ as required by PEP 440."""
self.assertEqual(_get_version((1, 1, 2, 'dev', 0)), "1.1.2.dev0")
self.assertEqual(_get_version((1, 1, 2, 'alpha', 1)), "1.1.2a1")
self.assertEqu... | TestVersion |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 23876,
"end": 24003
} | class ____(MixinDefault, TestRefererMiddleware):
req_meta = {"referrer_policy": POLICY_SCRAPY_DEFAULT}
| TestRequestMetaDefault |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 101795,
"end": 102432
} | class ____(TestCase):
def setUp(self):
self.model = ModelWithSingleNoDBIndexUnique
self.history_model = self.model.history.model
def test_unique_field_index(self):
# Ending up with deferred fields (dont know why), using work around
self.assertTrue(self.model._meta.get_field("nam... | ModelWithSingleNoDBIndexUniqueTest |
python | sqlalchemy__sqlalchemy | test/orm/declarative/test_tm_future_annotations.py | {
"start": 5162,
"end": 12829
} | class ____(_MappedColumnTest):
def test_fully_qualified_mapped_name(self, decl_base):
"""test #8853, regression caused by #8759 ;)
See same test in test_abs_import_only
"""
class Foo(decl_base):
__tablename__ = "foo"
id: sqlalchemy.orm.Mapped[int] = mappe... | MappedColumnTest |
python | sqlalchemy__sqlalchemy | test/engine/test_logging.py | {
"start": 20235,
"end": 23395
} | class ____(fixtures.TestBase):
def setup_test(self):
self.existing_level = logging.getLogger("sqlalchemy.pool").level
self.buf = logging.handlers.BufferingHandler(100)
for log in [logging.getLogger("sqlalchemy.pool")]:
log.addHandler(self.buf)
def teardown_test(self):
... | PoolLoggingTest |
python | graphql-python__graphene | graphene/types/tests/test_scalar.py | {
"start": 8439,
"end": 10292
} | class ____:
def test_query(self):
"""
Test that a normal query works.
"""
result = schema.execute('{ optional { string(input: "something something") } }')
assert not result.errors
assert result.data == {"optional": {"string": "something something"}}
result = ... | TestString |
python | pallets__click | src/click/core.py | {
"start": 101764,
"end": 128873
} | class ____(Parameter):
"""Options are usually optional values on the command line and
have some extra features that arguments don't have.
All other parameters are passed onwards to the parameter constructor.
:param show_default: Show the default value for this option in its
help text. Values a... | Option |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/eventbridge.py | {
"start": 6717,
"end": 8567
} | class ____(AwsBaseOperator[EventBridgeHook]):
"""
Enable an EventBridge Rule.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:EventBridgeEnableRuleOperator`
:param name: the name of the rule to enable
:param event_bus_na... | EventBridgeEnableRuleOperator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.