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 | pypa__setuptools | setuptools/command/editable_wheel.py | {
"start": 3557,
"end": 15765
} | class ____(Command):
"""Build 'editable' wheel for development.
This command is private and reserved for internal use of setuptools,
users should rely on ``setuptools.build_meta`` APIs.
"""
description = "DO NOT CALL DIRECTLY, INTERNAL ONLY: create PEP 660 editable wheel"
user_options = [
... | editable_wheel |
python | gevent__gevent | src/gevent/events.py | {
"start": 10698,
"end": 10910
} | class ____(BaseException):
"""
Subscribers to will-patch events can raise instances
of this class to tell gevent not to patch that particular item.
"""
@implementer(IGeventWillPatchEvent)
| DoNotPatch |
python | getsentry__sentry | src/sentry/workflow_engine/handlers/condition/issue_priority_greater_or_equal_handler.py | {
"start": 325,
"end": 708
} | class ____(DataConditionHandler[WorkflowEventData]):
group = DataConditionHandler.Group.ACTION_FILTER
subgroup = DataConditionHandler.Subgroup.ISSUE_ATTRIBUTES
@staticmethod
def evaluate_value(event_data: WorkflowEventData, comparison: Any) -> bool:
group = event_data.group
return group... | IssuePriorityGreaterOrEqualConditionHandler |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI036.py | {
"start": 225,
"end": 341
} | class ____:
def __exit__(self, *args: object) -> None: ...
async def __aexit__(self, *args) -> str: ...
| GoodOne |
python | networkx__networkx | networkx/exception.py | {
"start": 645,
"end": 1382
} | class ____(NetworkXException):
"""Raised when a null graph is provided as input to an algorithm
that cannot use it.
The null graph is sometimes considered a pointless concept [1]_,
thus the name of the exception.
Notes
-----
Null graphs and empty graphs are often used interchangeably but t... | NetworkXPointlessConcept |
python | huggingface__transformers | src/transformers/models/oneformer/modeling_oneformer.py | {
"start": 70960,
"end": 72289
} | class ____(nn.Module):
def __init__(self, config: OneFormerConfig):
"""
Pixel Level Module proposed in [Masked-attention Mask Transformer for Universal Image
Segmentation](https://huggingface.co/papers/2112.01527). It runs the input image through a backbone and a pixel
decoder, gener... | OneFormerPixelLevelModule |
python | pytorch__pytorch | torchgen/gen_aoti_c_shim.py | {
"start": 19717,
"end": 28140
} | class ____:
inductor_fallback_ops: dict[str, dict[str, list[str]]]
func_group_mapping: dict[OperatorName, NativeFunctionsGroup]
dispatch_key: DispatchKey | None
backend_indices: dict[DispatchKey, BackendIndex]
header: bool # True to generate .h and False to generate .cpp
extend_aoti_c_shim: boo... | ShimGenerator |
python | jazzband__django-redis | django_redis/util.py | {
"start": 0,
"end": 266
} | class ____(str):
"""
A stub string class that we can use to check if a key was created already.
"""
def original_key(self) -> str:
return self.rsplit(":", 1)[1]
def default_reverse_key(key: str) -> str:
return key.split(":", 2)[2]
| CacheKey |
python | langchain-ai__langchain | libs/langchain/langchain_classic/callbacks/streaming_aiter.py | {
"start": 349,
"end": 2667
} | class ____(AsyncCallbackHandler):
"""Callback handler that returns an async iterator."""
queue: asyncio.Queue[str]
done: asyncio.Event
@property
def always_verbose(self) -> bool:
"""Always verbose."""
return True
def __init__(self) -> None:
"""Instantiate AsyncIterato... | AsyncIteratorCallbackHandler |
python | PyCQA__pylint | doc/data/messages/d/duplicate-code/good/fruit.py | {
"start": 0,
"end": 504
} | class ____:
def __init__(self):
self.remaining_bites = 3
def take_bite(self):
if self.remaining_bites > 0:
print(f"You take a bite of the {self.__class__.__name__.lower()}.")
self.remaining_bites -= 1
else:
print(f"The {self.__class__.__name__.lower()... | Fruit |
python | walkccc__LeetCode | solutions/233. Number of Digit One/233.py | {
"start": 0,
"end": 361
} | class ____:
def countDigitOne(self, n: int) -> int:
ans = 0
pow10 = 1
while pow10 <= n:
divisor = pow10 * 10
quotient = n // divisor
remainder = n % divisor
if quotient > 0:
ans += quotient * pow10
if remainder >= pow10:
ans += min(remainder - pow10 + 1, pow1... | Solution |
python | doocs__leetcode | lcof2/剑指 Offer II 102. 加减的目标值/Solution2.py | {
"start": 0,
"end": 541
} | class ____:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
s = sum(nums)
if s - target < 0 or (s - target) % 2 != 0:
return 0
target = (s - target) // 2 + 1
n = len(nums) + 1
dp = [[0] * target for _ in range(n)]
dp[0][0] = 1
for... | Solution |
python | django__django | django/template/defaulttags.py | {
"start": 10370,
"end": 11203
} | class ____(Node):
def __init__(self, conditions_nodelists):
self.conditions_nodelists = conditions_nodelists
def __repr__(self):
return "<%s>" % self.__class__.__name__
def __iter__(self):
for _, nodelist in self.conditions_nodelists:
yield from nodelist
@property
... | IfNode |
python | huggingface__transformers | src/transformers/models/evolla/modeling_evolla.py | {
"start": 25331,
"end": 25750
} | class ____(nn.Module):
def __init__(self, dim, mult=4):
super().__init__()
inner_dim = int(dim * mult)
self.norm = nn.LayerNorm(dim)
self.fc1 = nn.Linear(dim, inner_dim, bias=False)
self.activation = nn.GELU()
self.fc2 = nn.Linear(inner_dim, dim, bias=False)
def... | EvollaFeedForward |
python | keras-team__keras | integration_tests/torch_workflow_test.py | {
"start": 126,
"end": 310
} | class ____(torch.nn.Module):
def __init__(self):
super().__init__()
self.fc1 = layers.Dense(1)
def forward(self, x):
x = self.fc1(x)
return x
| Net |
python | dask__dask | dask/tests/test_task_spec.py | {
"start": 12047,
"end": 12321
} | class ____(namedtuple("NewArgsNamedTuple", "ab, c")):
"""Namedtuple with a custom constructor."""
def __new__(cls, a, b, c):
return super().__new__(cls, f"{a}-{b}", c)
def __getnewargs__(self):
return *self.ab.split("-"), self.c
| NewArgsNamedTuple |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/unit_tests/common.py | {
"start": 808,
"end": 1494
} | class ____:
def __init__(self, credentials, **kwargs):
self.config = credentials
self.customer_ids = ["1"]
def get_type(self, type):
return MockSearchRequest()
def get_service(self, service):
if service == "GoogleAdsFieldService":
return MockGoogleAdsFieldServic... | MockGoogleAdsClient |
python | wandb__wandb | wandb/vendor/pygments/lexers/scripting.py | {
"start": 56252,
"end": 64859
} | class ____(RegexLexer):
"""
Easytrieve Plus is a programming language for extracting, filtering and
converting sequential data. Furthermore it can layout data for reports.
It is mainly used on mainframe platforms and can access several of the
mainframe's native file formats. It is somewhat comparabl... | EasytrieveLexer |
python | numba__numba | numba/core/rewrites/ir_print.py | {
"start": 2047,
"end": 2969
} | class ____(Rewrite):
"""
Detect and store constant arguments to print() nodes.
"""
def match(self, func_ir, block, typemap, calltypes):
self.consts = consts = {}
self.block = block
for inst in block.find_insts(ir.Print):
if inst.consts:
# Already rewr... | DetectConstPrintArguments |
python | fluentpython__example-code-2e | 24-class-metaprog/bulkfood/bulkfood_v6.py | {
"start": 1812,
"end": 2156
} | class ____:
description = model.NonBlank()
weight = model.Quantity()
price = model.Quantity()
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
#... | LineItem |
python | langchain-ai__langchain | libs/standard-tests/tests/unit_tests/test_in_memory_vectorstore.py | {
"start": 614,
"end": 1198
} | class ____(VectorStoreIntegrationTests):
@pytest.fixture
def vectorstore(self) -> VectorStore:
embeddings = self.get_embeddings()
return WithoutGetByIdsVectorStore(embedding=embeddings)
@property
def has_get_by_ids(self) -> bool:
return False
def test_get_by_ids_fails(self,... | TestWithoutGetByIdVectorStore |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/checkpoint_options.py | {
"start": 978,
"end": 6217
} | class ____(object):
"""Options for constructing a Checkpoint.
Used as the `options` argument to either `tf.train.Checkpoint.save()` or
`tf.train.Checkpoint.restore()` methods to adjust how variables are
saved/restored.
Example: Run IO ops on "localhost" while saving a checkpoint:
```
step = tf.Variable... | CheckpointOptions |
python | google__jax | tests/traceback_test.py | {
"start": 1095,
"end": 4920
} | class ____(absltest.TestCase):
def testNoTracebacksIfDisabled(self):
with tracebacks(enabled=False):
self.assertEqual(None, Traceback.get_traceback())
buffer = jnp.array(7, np.int32)
self.assertEqual(None, buffer.traceback)
e = jax.jit(lambda x: x + 1).lower(1).compile().runtime_executab... | TracebackTest |
python | doocs__leetcode | solution/3400-3499/3488.Closest Equal Element Queries/Solution.py | {
"start": 0,
"end": 635
} | class ____:
def solveQueries(self, nums: List[int], queries: List[int]) -> List[int]:
n = len(nums)
m = n << 1
d = [m] * m
left = {}
for i in range(m):
x = nums[i % n]
if x in left:
d[i] = min(d[i], i - left[x])
left[x] = i
... | Solution |
python | django-extensions__django-extensions | django_extensions/management/commands/runscript.py | {
"start": 376,
"end": 622
} | class ____:
NONE = "none"
EACH = "each"
ROOT = "root"
def check_is_directory(value):
if value is None or not os.path.isdir(value):
raise ArgumentTypeError("%s is not a directory!" % value)
return value
| DirPolicyChoices |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_area01.py | {
"start": 315,
"end": 1400
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_area01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | getsentry__sentry | src/sentry/integrations/gitlab/integration.py | {
"start": 13489,
"end": 14261
} | class ____:
def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase:
if "completed_installation_guide" in request.GET:
return pipeline.next_step()
return render_to_response(
template="sentry/integrations/gitlab-config.html",
con... | InstallationGuideView |
python | PrefectHQ__prefect | src/prefect/server/services/task_run_recorder.py | {
"start": 7966,
"end": 10011
} | class ____(RunInEphemeralServers, Service):
"""Constructs task runs and states from client-emitted events"""
consumer_task: asyncio.Task[None] | None = None
metrics_task: asyncio.Task[None] | None = None
@classmethod
def service_settings(cls) -> ServicesBaseSetting:
return get_current_sett... | TaskRunRecorder |
python | automl__auto-sklearn | test/test_pipeline/components/feature_preprocessing/test_densifier.py | {
"start": 189,
"end": 669
} | class ____(PreprocessingTestCase):
def test_default_configuration(self):
transformation, original = _test_preprocessing(Densifier, make_sparse=True)
self.assertIsInstance(transformation, np.ndarray)
self.assertEqual(transformation.shape, original.shape)
self.assertIsInstance(transfor... | DensifierComponentTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-astra/destination_astra/astra_client.py | {
"start": 144,
"end": 5991
} | class ____:
def __init__(
self,
astra_endpoint: str,
astra_application_token: str,
keyspace_name: str,
embedding_dim: int,
similarity_function: str,
):
self.astra_endpoint = astra_endpoint
self.astra_application_token = astra_application_token
... | AstraClient |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-alibabacloud-opensearch/llama_index/vector_stores/alibabacloud_opensearch/base.py | {
"start": 5487,
"end": 14566
} | class ____(BasePydanticVectorStore):
"""
The AlibabaCloud OpenSearch Vector Store.
In this vector store we store the text, its embedding and its metadata
in a OpenSearch table.
In order to use this you need to have a instance and configure a table.
See the following documentation for details:
... | AlibabaCloudOpenSearchStore |
python | numba__numba | numba/core/typing/enumdecl.py | {
"start": 1467,
"end": 1503
} | class ____(EnumCompare):
pass
| EnumNe |
python | aimacode__aima-python | reinforcement_learning.py | {
"start": 7554,
"end": 11380
} | class ____:
"""
[Figure 21.8]
An exploratory Q-learning agent. It avoids having to learn the transition
model because the Q-value of a state can be related directly to those of
its neighbors.
import sys
from mdp import sequential_decision_environment
north = (0, 1)
south = (0,-1... | QLearningAgent |
python | ray-project__ray | release/ray_release/test.py | {
"start": 4240,
"end": 25820
} | class ____(dict):
"""A class represents a test to run on buildkite"""
KEY_GITHUB_ISSUE_NUMBER = "github_issue_number"
KEY_BISECT_BUILD_NUMBER = "bisect_build_number"
KEY_BISECT_BLAMED_COMMIT = "bisect_blamed_commit"
# a test is high impact if it catches regressions frequently
KEY_IS_HIGH_IMPACT... | Test |
python | pytorch__pytorch | benchmarks/gpt_fast/benchmark.py | {
"start": 370,
"end": 10670
} | class ____(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, dtype):
super().__init__()
self.layers = nn.ModuleList(
[
nn.Linear(input_dim, hidden_dim, dtype=dtype),
nn.LayerNorm(hidden_dim, dtype=dtype),
nn.Linear(hidden_di... | SimpleMLP |
python | ijl__orjson | test/test_dataclass.py | {
"start": 1082,
"end": 1175
} | class ____:
c: int
b: int
a: int
d: Optional[dict]
@dataclass
| UnsortedDataclass |
python | gevent__gevent | src/greentest/3.14/test_urllib2.py | {
"start": 11804,
"end": 11898
} | class ____(dict):
def getheaders(self, name):
return list(self.values())
| MockHeaders |
python | python-pillow__Pillow | src/PIL/ImageFilter.py | {
"start": 7622,
"end": 7853
} | class ____(BuiltinFilter):
name = "Blur"
# fmt: off
filterargs = (5, 5), 16, 0, (
1, 1, 1, 1, 1,
1, 0, 0, 0, 1,
1, 0, 0, 0, 1,
1, 0, 0, 0, 1,
1, 1, 1, 1, 1,
)
# fmt: on
| BLUR |
python | pytorch__pytorch | torch/ao/pruning/_experimental/data_sparsifier/benchmarks/dlrm_utils.py | {
"start": 284,
"end": 5463
} | class ____(DLRM_Net):
"""The SparseDLRM model is a wrapper around the DLRM_Net model that tries
to use torch.sparse tensors for the features obtained after the ```interact_features()```
call. The idea is to do a simple torch.mm() with the weight matrix of the first linear
layer of the top layer.
"""... | SparseDLRM |
python | huggingface__transformers | src/transformers/models/llama4/modeling_llama4.py | {
"start": 6901,
"end": 13078
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
# Ignore copy
def __init__(self, config: Llama4TextConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_emb... | Llama4TextRotaryEmbedding |
python | getsentry__sentry | src/sentry/auth/store.py | {
"start": 206,
"end": 670
} | class ____(PipelineSessionStore):
redis_namespace = "auth"
@property
def session_key(self) -> str:
return "auth_key"
flow = redis_property("flow")
referrer = redis_property("referrer")
def mark_session(self) -> None:
super().mark_session()
self.request.session.modified... | AuthHelperSessionStore |
python | scikit-learn__scikit-learn | sklearn/utils/_testing.py | {
"start": 11963,
"end": 39220
} | class ____:
"""
Parameters
----------
data
mmap_mode : str, default='r'
"""
def __init__(self, data, mmap_mode="r"):
self.mmap_mode = mmap_mode
self.data = data
def __enter__(self):
data_read_only, self.temp_folder = create_memmap_backed_data(
self.d... | TempMemmap |
python | kamyu104__LeetCode-Solutions | Python/lfu-cache.py | {
"start": 2766,
"end": 4615
} | class ____(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.__capa = capacity
self.__size = 0
self.__min_freq = float("inf")
self.__freq_to_nodes = collections.defaultdict(LinkedList)
self.__key_to_node = {}
def get(self, k... | LFUCache2 |
python | PrefectHQ__prefect | src/prefect/deployments/runner.py | {
"start": 3237,
"end": 3358
} | class ____(RuntimeError):
"""
Raised when an error occurs while applying a deployment.
"""
| DeploymentApplyError |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/strings_ops/unsorted_segment_join_op_test.py | {
"start": 1080,
"end": 1376
} | class ____(test.TestCase):
"""Test case with Python3-compatible string comparator."""
def assertAllEqualUnicode(self, truth, actual):
self.assertAllEqual(
np.array(truth).astype('U'),
np.array(actual).astype('U'))
@test_util.run_all_in_graph_and_eager_modes
| UnicodeTestCase |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 16013,
"end": 16145
} | class ____(_TestDSTIVBase):
def setup_method(self):
self.rdt = int
self.dec = 5
self.type = 4
| TestDSTIVInt |
python | huggingface__transformers | tests/utils/test_tokenization_utils.py | {
"start": 10007,
"end": 12019
} | class ____(unittest.TestCase):
def test_trie(self):
trie = Trie()
trie.add("Hello 友達")
self.assertEqual(trie.data, {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}})
trie.add("Hello")
self.assertEqual(trie.data, {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {... | TrieTest |
python | huggingface__transformers | src/transformers/models/convbert/modeling_convbert.py | {
"start": 26659,
"end": 30113
} | class ____(ConvBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.embeddings = ConvBertEmbeddings(config)
if config.embedding_size != config.hidden_size:
self.embeddings_project = nn.Linear(config.embedding_size, config.hidden_size)
self.enc... | ConvBertModel |
python | coleifer__peewee | tests/regressions.py | {
"start": 35008,
"end": 35113
} | class ____(TestModel):
page = ForeignKeyField(Page, backref='items')
content = TextField()
| PageItem |
python | great-expectations__great_expectations | great_expectations/core/batch.py | {
"start": 2753,
"end": 9274
} | class ____(SerializableDictDot):
"""Precisely identifies a set of data from a data source.
More concretely, a BatchDefinition includes all the information required to precisely
identify a set of data from the external data source that should be
translated into a Batch. One or more BatchDefinitions shou... | LegacyBatchDefinition |
python | catalyst-team__catalyst | catalyst/contrib/losses/recsys.py | {
"start": 11901,
"end": 16665
} | class ____(PairwiseLoss):
"""Roc-star loss function.
Smooth approximation for ROC-AUC. It has been proposed in
`Roc-star\: An objective function for ROC-AUC that actually works`_.
.. _Roc-star\: An objective function for ROC-AUC that actually works:
https://github.com/iridiumblue/roc-star
... | RocStarLoss |
python | Textualize__textual | src/textual/widgets/_markdown.py | {
"start": 12013,
"end": 12318
} | class ____(MarkdownHeader):
"""An H3 Markdown header."""
LEVEL = 3
DEFAULT_CSS = """
MarkdownH3 {
color: $markdown-h3-color;
background: $markdown-h3-background;
text-style: $markdown-h3-text-style;
margin: 1 0;
width: auto;
}
"""
| MarkdownH3 |
python | getsentry__sentry | src/sentry/sentry_metrics/consumers/indexer/parallel.py | {
"start": 2751,
"end": 7529
} | class ____(ProcessingStrategyFactory[KafkaPayload]):
"""
Builds an indexer consumer based on the multi process transform Arroyo step.
Multi processing happens in batches, the parallel step batches messages, then
it dispatches them to a process. This is meant to avoid lock contention that
would happ... | MetricsConsumerStrategyFactory |
python | pytorch__pytorch | functorch/dim/__init__.py | {
"start": 30471,
"end": 32974
} | class ____(_Tensor):
_level: int
_name: str
_size: int
_range: Optional[torch.Tensor]
_batchtensor: Optional[torch.Tensor]
def __init__(self, name: str, s: int = -1) -> None:
global _n_dims_created
self._name = name
self._size = s
self._level = _n_dims_created
... | Dim |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyflakes/F811_18.py | {
"start": 306,
"end": 420
} | class ____(unittest.TestCase):
def test_send_defaults(self):
transport.Transport()
| TestTransportMethodArgs |
python | pennersr__django-allauth | allauth/account/views.py | {
"start": 30248,
"end": 30479
} | class ____(TemplateView):
template_name = "account/account_inactive." + app_settings.TEMPLATE_EXTENSION
account_inactive = AccountInactiveView.as_view()
@method_decorator(login_not_required, name="dispatch")
| AccountInactiveView |
python | getsentry__sentry | src/sentry/workflow_engine/utils/dictpath.py | {
"start": 1124,
"end": 1957
} | class ____[T]:
def __init__(self, exc: ValueError) -> None:
self._exc = exc
def failed(self) -> bool:
return True
def get(self, fallback: T | None = None) -> T:
if fallback is not None:
return fallback
raise self._exc
def get_or_none(self) -> T | None:
... | _FailedResultImpl |
python | wandb__wandb | wandb/integration/keras/callbacks/metrics_logger.py | {
"start": 304,
"end": 4919
} | class ____(callbacks.Callback):
"""Logger that sends system metrics to W&B.
`WandbMetricsLogger` automatically logs the `logs` dictionary that callback methods
take as argument to wandb.
This callback automatically logs the following to a W&B run page:
* system (CPU/GPU/TPU) metrics,
* train a... | WandbMetricsLogger |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/fmt_skip/match.py | {
"start": 576,
"end": 1937
} | class ____:
x: int
y: int
def location(point):
match point:
case Point(x=0, y =0 ) : # fmt: skip
print("Origin is the point's location.")
case Point(x=0, y=y):
print(f"Y={y} and the point is on the y-axis.")
case Point(x=x, y=0):
print(f"X={x} an... | Point |
python | dask__distributed | distributed/dashboard/components/shared.py | {
"start": 4922,
"end": 11068
} | class ____(DashboardComponent):
"""Time plots of the current resource usage on the cluster
This is two plots, one for CPU and Memory and another for Network I/O
"""
def __init__(self, server, doc=None, **kwargs):
if doc is not None:
self.doc = weakref.ref(doc)
try:
... | ProfileTimePlot |
python | walkccc__LeetCode | solutions/170. Two Sum III - Data structure design/170.py | {
"start": 0,
"end": 393
} | class ____:
def __init__(self):
self.count = collections.Counter()
def add(self, number: int) -> None:
self.count[number] += 1
def find(self, value: int) -> bool:
for key, freq in self.count.items():
remain = value - key
if key == remain and freq > 1:
return True
if key != ... | TwoSum |
python | numba__numba | numba/core/typed_passes.py | {
"start": 8402,
"end": 9636
} | class ____(FunctionPass):
_name = "nopython_rewrites"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
Perform any intermediate representation rewrites after type
inference.
"""
# a bunch of these passes are either making assump... | NopythonRewrites |
python | huggingface__transformers | src/transformers/models/seed_oss/modeling_seed_oss.py | {
"start": 12681,
"end": 15700
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: SeedOssConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self... | SeedOssRotaryEmbedding |
python | pandas-dev__pandas | pandas/tests/indexing/test_iloc.py | {
"start": 1606,
"end": 45367
} | class ____:
"""Tests Independent Of Base Class"""
@pytest.mark.parametrize(
"key",
[
slice(None),
slice(3),
range(3),
[0, 1, 2],
Index(range(3)),
np.asarray([0, 1, 2]),
],
)
def test_iloc_setitem_fullcol_cat... | TestiLocBaseIndependent |
python | django__django | tests/admin_checks/tests.py | {
"start": 1706,
"end": 35360
} | class ____(SimpleTestCase):
databases = "__all__"
def test_checks_are_performed(self):
admin.site.register(Song, MyAdmin)
try:
errors = checks.run_checks()
expected = ["error!"]
self.assertEqual(errors, expected)
finally:
admin.site.unregi... | SystemChecksTestCase |
python | gevent__gevent | src/greentest/3.14/test_socketserver.py | {
"start": 11304,
"end": 11856
} | class ____(socketserver.TCPServer):
def __init__(self, exception):
self.exception = exception
super().__init__((HOST, 0), BadHandler)
with socket.create_connection(self.server_address):
pass
try:
self.handle_request()
finally:
self.server_c... | BaseErrorTestServer |
python | pypa__warehouse | tests/unit/metrics/test_event_handlers.py | {
"start": 2349,
"end": 3930
} | class ____:
def test_without_view_duration(self, pyramid_request, metrics):
before_render_start = datetime.datetime.now(datetime.UTC)
pyramid_request.timings = {}
pyramid_request.matched_route = None
with freezegun.freeze_time(before_render_start):
on_before_render({"re... | TestOnBeforeRender |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 72885,
"end": 83503
} | class ____(CodeGen, Generic[CSEVariableType]):
newvar_prefix: str = ""
suffix: str = ""
overrides: Optional[Callable[[], OpsHandler[Any]]] = None
def __init__(
self, args: Optional[KernelArgs] = None, increase_kernel_count: bool = True
) -> None:
super().__init__()
if increa... | Kernel |
python | pytest-dev__pytest | src/_pytest/stepwise.py | {
"start": 2922,
"end": 7689
} | class ____:
def __init__(self, config: Config) -> None:
self.config = config
self.session: Session | None = None
self.report_status: list[str] = []
assert config.cache is not None
self.cache: Cache = config.cache
self.skip: bool = config.getoption("stepwise_skip")
... | StepwisePlugin |
python | huggingface__transformers | src/transformers/models/clvp/modeling_clvp.py | {
"start": 61403,
"end": 84918
} | class ____(ClvpPreTrainedModel, GenerationMixin):
config: ClvpConfig
def __init__(self, config: ClvpConfig):
super().__init__(config)
if not isinstance(config.text_config, ClvpEncoderConfig):
raise TypeError(
"config.text_config is expected to be of type `ClvpEncode... | ClvpModelForConditionalGeneration |
python | doocs__leetcode | solution/1600-1699/1678.Goal Parser Interpretation/Solution2.py | {
"start": 0,
"end": 296
} | class ____:
def interpret(self, command: str) -> str:
ans = []
for i, c in enumerate(command):
if c == 'G':
ans.append(c)
elif c == '(':
ans.append('o' if command[i + 1] == ')' else 'al')
return ''.join(ans)
| Solution |
python | apache__airflow | providers/edge3/src/airflow/providers/edge3/worker_api/datamodels_ui.py | {
"start": 2623,
"end": 2795
} | class ____(BaseModel):
"""Request body for queue operations."""
queue_name: Annotated[str, Field(description="Name of the queue to add or remove.")]
| QueueUpdateRequest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol19.py | {
"start": 625,
"end": 710
} | class ____:
x: int
c1: ProtoC = ConcreteC1(0)
c2: ProtoC = ConcreteC2(0)
| ConcreteC2 |
python | huggingface__transformers | src/transformers/models/bloom/modeling_bloom.py | {
"start": 5933,
"end": 6323
} | class ____(torch.autograd.Function):
@staticmethod
def forward(ctx, input: torch.Tensor) -> torch.Tensor:
ctx.save_for_backward(input)
return bloom_gelu_forward(input)
@staticmethod
def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
input = ctx.saved_tensors
t... | GeLUFunction |
python | pytorch__pytorch | torch/nn/modules/dropout.py | {
"start": 5974,
"end": 7678
} | class ____(_DropoutNd):
r"""Randomly zero out entire channels.
A channel is a 3D feature map,
e.g., the :math:`j`-th channel of the :math:`i`-th sample in the
batched input is a 3D tensor :math:`\text{input}[i, j]`.
Each channel will be zeroed out independently on every forward call with
proba... | Dropout3d |
python | getsentry__sentry | src/sentry/incidents/endpoints/team_alerts_triggered.py | {
"start": 3082,
"end": 4832
} | class ____(AlertRuleSerializer):
def __init__(self, start, end):
super().__init__()
self.start = start
self.end = end
def get_attrs(self, item_list, user, **kwargs):
result = super().get_attrs(item_list, user, **kwargs)
qs = (
AlertRule.objects.filter(
... | TriggeredAlertRuleSerializer |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 12570,
"end": 13463
} | class ____(GroupbyAggregationBase):
"""Logical groupby aggregation class
This class lowers itself to concrete implementations for decomposable
or holistic aggregations.
"""
@functools.cached_property
def _meta(self):
return self._lower()._meta
@functools.cached_property
def _i... | GroupbyAggregation |
python | scipy__scipy | scipy/optimize/tests/test__basinhopping.py | {
"start": 14152,
"end": 17628
} | class ____:
def setup_method(self):
self.T = 2.
self.met = Metropolis(self.T)
self.res_new = OptimizeResult(success=True, fun=0.)
self.res_old = OptimizeResult(success=True, fun=1.)
def test_boolean_return(self):
# the return must be a bool, else an error will be raised ... | Test_Metropolis |
python | pennersr__django-allauth | allauth/socialaccount/providers/twitter/provider.py | {
"start": 1106,
"end": 1794
} | class ____(OAuthProvider):
id = "twitter"
name = "X"
account_class = TwitterAccount
oauth_adapter_class = TwitterOAuthAdapter
def get_auth_url(self, request, action):
if action == AuthAction.REAUTHENTICATE:
url = "https://api.x.com/oauth/authorize"
else:
url ... | TwitterProvider |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/errors.py | {
"start": 9834,
"end": 10019
} | class ____(OAuth2Error):
"""
The authenticated client is not authorized to use this authorization
grant type.
"""
error = 'unauthorized_client'
| UnauthorizedClientError |
python | tensorflow__tensorflow | tensorflow/python/framework/convert_to_constants.py | {
"start": 23100,
"end": 23465
} | class ____(_FunctionCaller):
"""Specialization of _Node to PartitionedCall-like operations."""
def __init__(self, node, function, enclosing_graph):
super(_PartitionedCall, self).__init__(
node,
function,
enclosing_graph,
first_function_input=0,
type_attribute="Tin",
... | _PartitionedCall |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/fixed_length_record_dataset_test.py | {
"start": 2544,
"end": 8240
} | class ____(FixedLengthRecordDatasetTestBase,
parameterized.TestCase):
def _test(self, compression_type=None):
test_filenames = self._createFiles(compression_type=compression_type)
def dataset_fn(filenames, num_epochs, batch_size=None):
repeat_dataset = readers.FixedL... | FixedLengthRecordDatasetTest |
python | getsentry__sentry | tests/sentry/api/test_authentication.py | {
"start": 4097,
"end": 9791
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.auth = JWTClientSecretAuthentication()
self.org = self.create_organization(owner=self.user)
self.sentry_app = self.create_sentry_app(name="foo", organization=self.org)
self.installation = self.create_sentry_... | TestJWTClientSecretAuthentication |
python | ansible__ansible | test/units/module_utils/facts/test_facts.py | {
"start": 2442,
"end": 2629
} | class ____(BaseTestFactsPlatform):
platform_id = 'Linux'
fact_class = hardware.linux.LinuxHardware
collector_class = hardware.linux.LinuxHardwareCollector
| TestLinuxFactsPlatform |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/inputs.py | {
"start": 11021,
"end": 12359
} | class ____(graphene.InputObjectType):
selector = graphene.NonNull(
GrapheneJobOrPipelineSelector,
description="""Defines the job / pipeline and solid subset that should be executed.
All subsequent executions in the same run group (for example, a single-step
re-execution) are scoped t... | GrapheneExecutionParams |
python | sympy__sympy | sympy/tensor/tensor.py | {
"start": 67687,
"end": 83091
} | class ____(Expr, ABC):
"""
Abstract base class for tensor expressions
Notes
=====
A tensor expression is an expression formed by tensors;
currently the sums of tensors are distributed.
A ``TensExpr`` can be a ``TensAdd`` or a ``TensMul``.
``TensMul`` objects are formed by products of... | TensExpr |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataprep.py | {
"start": 1833,
"end": 2352
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dataprep.GoogleDataprepHook")
def test_execute(self, hook_mock):
op = DataprepGetJobsForJobGroupOperator(
dataprep_conn_id=DATAPREP_CONN_ID, job_group_id=JOB_ID, task_id=TASK_ID
)
op.execute(context={})
... | TestDataprepGetJobsForJobGroupOperator |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 484454,
"end": 485729
} | class ____(DataSource):
"""
InlineData schema wrapper.
Parameters
----------
values : str, dict, Sequence[str], Sequence[bool], Sequence[dict], Sequence[float], :class:`InlineDataset`
The full data set, included inline. This can be an array of objects or primitive
values, an object,... | InlineData |
python | wandb__wandb | wandb/sdk/lib/fsm.py | {
"start": 3045,
"end": 5044
} | class ____(Generic[T_FsmInputs, T_FsmContext]):
_state_dict: Dict[Type[FsmState], FsmState]
_table: FsmTableWithContext[T_FsmInputs, T_FsmContext]
_state: FsmState[T_FsmInputs, T_FsmContext]
_states: Sequence[FsmState]
def __init__(
self,
states: Sequence[FsmState],
table: F... | FsmWithContext |
python | google__pytype | pytype/rewrite/abstract/functions.py | {
"start": 2145,
"end": 3126
} | class ____(Generic[_FrameT]):
"""Arguments to one function call."""
posargs: tuple[_Var, ...] = ()
kwargs: Mapping[str, _Var] = datatypes.EMPTY_MAP
starargs: _Var | None = None
starstarargs: _Var | None = None
frame: _FrameT | None = None
def get_concrete_starargs(self) -> tuple[Any, ...]:
"""Returns... | Args |
python | getsentry__sentry | tests/sentry/testutils/pytest/mocking/test_mocking.py | {
"start": 2521,
"end": 4587
} | class ____(TestCase):
def test_no_args_no_kwargs_matching(self) -> None:
describe_dogs = MagicMock()
# Call the function more than once to show it's not just the total number of calls being
# counted, and call it with something else second, to show it's not just looking at the most
#... | MockCallCountingTest |
python | realpython__materials | wordcount/tests/realpython/models.py | {
"start": 572,
"end": 718
} | class ____(Enum):
PASSED = "passed"
FAILED = "failed"
SKIPPED = "skipped"
TIMED_OUT = "timed_out"
@dataclass(frozen=True)
| TestStatus |
python | getsentry__sentry | tests/sentry/tasks/test_activity.py | {
"start": 411,
"end": 852
} | class ____(PluginTestCase):
plugin = BasicPreprocessorPlugin
@mock.patch("sentry.tasks.activity.send_activity_notifications")
def test_simple(self, mock_func: mock.MagicMock) -> None:
group = self.create_group()
Activity.objects.create_group_activity(
group, ActivityType.ASSIGNE... | ActivityNotificationsTest |
python | miyuchina__mistletoe | test/test_contrib/test_github_wiki.py | {
"start": 209,
"end": 1175
} | class ____(TestCase):
def setUp(self):
token._root_node = Document([])
self.renderer = GithubWikiRenderer()
self.renderer.__enter__()
self.addCleanup(self.renderer.__exit__, None, None, None)
def test_parse(self):
MockRawText = mock.Mock()
RawText = span_token._t... | TestGithubWiki |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_build_storage.py | {
"start": 340,
"end": 8490
} | class ____(TestCase):
def setUp(self):
self.test_media_dir = tempfile.mkdtemp()
self.storage = BuildMediaFileSystemStorage(location=self.test_media_dir)
def tearDown(self):
shutil.rmtree(self.test_media_dir, ignore_errors=True)
def assertFileTree(self, source, tree):
"""
... | TestBuildMediaStorage |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_connector/data_connector.py | {
"start": 435,
"end": 7678
} | class ____(ABC):
"""The abstract base class for all Data Connectors.
Data Connectors produce identifying information, called Batch Specs, that Execution Engines
can use to get individual batches of data. They add flexibility in how to obtain data
such as with time-based partitioning, downsampling, or o... | DataConnector |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_union.py | {
"start": 18359,
"end": 29125
} | class ____(int):
pass
@pytest.mark.parametrize('reverse', [False, True])
@pytest.mark.parametrize(
'core_schema_left,core_schema_right,input_value,expected_value',
[
(core_schema.int_schema(), core_schema.bool_schema(), True, True),
(core_schema.int_schema(), core_schema.bool_schema(), 1, ... | IntSubclass |
python | huggingface__transformers | tests/models/jamba/test_modeling_jamba.py | {
"start": 1599,
"end": 3711
} | class ____(ConfigTester):
def _create_attn_config(self, attn_layer_offset: int, attn_layer_period: int):
_input_dict = self.inputs_dict.copy()
_input_dict["attn_layer_offset"] = attn_layer_offset
_input_dict["attn_layer_period"] = attn_layer_period
return self.config_class(**_input_d... | JambaConfigTester |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_meta.py | {
"start": 2777,
"end": 4035
} | class ____(nn.Module):
def __init__(self, device):
super().__init__()
self.lin1 = MyLinear(2, 2, bias=False, device=device)
self.lin1 = wrap(self.lin1)
self.lin2 = MyLinear(2, 2, bias=False, device=device)
self.l3 = MyModel(device=device)
self.l3 = wrap(self.l3)
... | NestedModel |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/vector_store/base.py | {
"start": 1093,
"end": 18173
} | class ____(BaseIndex[IndexDict]):
"""
Vector Store Index.
Args:
use_async (bool): Whether to use asynchronous calls. Defaults to False.
show_progress (bool): Whether to show tqdm progress bars. Defaults to False.
store_nodes_override (bool): set to True to always store Node objects ... | VectorStoreIndex |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.