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__airflow | providers/redis/tests/integration/redis/operators/test_redis_publish.py | {
"start": 1166,
"end": 2257
} | class ____:
def setup_method(self):
args = {"owner": "airflow", "start_date": DEFAULT_DATE}
self.dag = DAG("test_redis_dag_id", schedule=None, default_args=args)
self.mock_context = MagicMock()
self.channel = "test"
def test_execute_hello(self):
operator = RedisPublish... | TestRedisPublishOperator |
python | pytorch__pytorch | torch/profiler/_memory_profiler.py | {
"start": 14826,
"end": 15104
} | class ____:
input_version: Optional[int] = None
mutated: Optional[bool] = False
@property
def is_allocation(self) -> bool:
return self.input_version is None
@property
def is_deletion(self) -> bool:
return self.mutated is None
| DataFlowEdge |
python | django__django | django/contrib/sitemaps/__init__.py | {
"start": 206,
"end": 5990
} | class ____:
# This limit is defined by Google. See the index documentation at
# https://www.sitemaps.org/protocol.html#index.
limit = 50000
# If protocol is None, the URLs in the sitemap will use the protocol
# with which the sitemap was requested.
protocol = None
# Enables generating URLs... | Sitemap |
python | tornadoweb__tornado | tornado/util.py | {
"start": 1405,
"end": 1761
} | class ____(Dict[str, Any]):
"""Makes a dictionary behave like an object, with attribute-style access."""
def __getattr__(self, name: str) -> Any:
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name: str, value: Any) -> None:... | ObjectDict |
python | pypa__warehouse | tests/unit/admin/views/test_prohibited_email_domains.py | {
"start": 5278,
"end": 7376
} | class ____:
def test_no_domain_name(self, db_request):
db_request.method = "POST"
db_request.route_path = lambda a: "/admin/prohibited_email_domains/remove/"
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.POST = ... | TestProhibitedEmailDomainsRemove |
python | getsentry__sentry | tests/sentry/notifications/notification_action/test_issue_alert_registry_handlers.py | {
"start": 18716,
"end": 19960
} | class ____(BaseWorkflowTest):
def setUp(self) -> None:
super().setUp()
self.detector = self.create_detector(project=self.project)
self.handler: TicketingIssueAlertHandler
def _test_build_rule_action_blob(self, expected, action_type: Action.Type):
action_data = pop_keys_from_data... | TestTicketingIssueAlertHandlerBase |
python | apache__airflow | airflow-core/src/airflow/plugins_manager.py | {
"start": 4644,
"end": 24288
} | class ____:
"""Class used to define AirflowPlugin."""
name: str | None = None
source: AirflowPluginSource | None = None
macros: list[Any] = []
admin_views: list[Any] = []
flask_blueprints: list[Any] = []
fastapi_apps: list[Any] = []
fastapi_root_middlewares: list[Any] = []
external_... | AirflowPlugin |
python | walkccc__LeetCode | solutions/3544. Subtree Inversion Sum/3544.py | {
"start": 0,
"end": 970
} | class ____:
def subtreeInversionSum(
self,
edges: list[list[int]],
nums: list[int],
k: int
) -> int:
n = len(edges) + 1
parent = [-1] * n
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
@functools.lru_cache(None)
d... | Solution |
python | huggingface__transformers | src/transformers/models/evolla/modeling_evolla.py | {
"start": 27512,
"end": 27820
} | class ____(ModelOutput):
sequence_compressor_output: Optional[torch.FloatTensor] = None
last_hidden_state: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
| EvollaProteinEncoderModelOutput |
python | huggingface__transformers | src/transformers/models/mobilevitv2/modeling_mobilevitv2.py | {
"start": 2174,
"end": 4386
} | class ____(nn.Module):
def __init__(
self,
config: MobileViTV2Config,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
groups: int = 1,
bias: bool = False,
dilation: int = 1,
use_normalization: bool = True,
... | MobileViTV2ConvLayer |
python | matplotlib__matplotlib | galleries/users_explain/text/annotations.py | {
"start": 12228,
"end": 34164
} | class ____:
"""A simple box."""
def __init__(self, pad=0.3):
"""
The arguments must be floats and have default values.
Parameters
----------
pad : float
amount of padding
"""
self.pad = pad
super().__init__()
def __call__(self, x... | MyStyle |
python | pandas-dev__pandas | pandas/tests/generic/test_frame.py | {
"start": 255,
"end": 5215
} | class ____:
@pytest.mark.parametrize("func", ["_set_axis_name", "rename_axis"])
def test_set_axis_name(self, func):
df = DataFrame([[1, 2], [3, 4]])
result = methodcaller(func, "foo")(df)
assert df.index.name is None
assert result.index.name == "foo"
result = methodcall... | TestDataFrame |
python | ansible__ansible | test/units/parsing/test_dataloader.py | {
"start": 5258,
"end": 5991
} | class ____(unittest.TestCase):
def setUp(self):
self._loader = DataLoader()
def test_all_slash(self):
self.assertEqual(self._loader.path_dwim_relative('/', '/', '/'), '/')
def test_path_endswith_role(self):
self.assertEqual(self._loader.path_dwim_relative(path='foo/bar/tasks/', di... | TestPathDwimRelativeDataLoader |
python | ray-project__ray | doc/source/serve/doc_code/http_guide/streaming_example.py | {
"start": 1385,
"end": 2282
} | class ____:
async def generate_forever(self) -> AsyncGenerator[str, None]:
try:
i = 0
while True:
yield str(i)
i += 1
await asyncio.sleep(0.1)
except asyncio.CancelledError:
print("Cancelled! Exiting.")
def __ca... | StreamingResponder |
python | allegroai__clearml | clearml/utilities/requests_toolbelt/multipart/encoder.py | {
"start": 14987,
"end": 16697
} | class ____(object):
def __init__(self, headers, body):
self.headers = headers
self.body = body
self.headers_unread = True
self.len = len(self.headers) + total_len(self.body)
@classmethod
def from_field(cls, field, encoding):
"""Create a part from a Request Field gene... | Part |
python | kamyu104__LeetCode-Solutions | Python/design-browser-history.py | {
"start": 103,
"end": 926
} | class ____(object):
def __init__(self, homepage):
"""
:type homepage: str
"""
self.__history = [homepage]
self.__curr = 0
def visit(self, url):
"""
:type url: str
:rtype: None
"""
while len(self.__history) > self.__curr+1:... | BrowserHistory |
python | pdm-project__pdm | src/pdm/models/serializers.py | {
"start": 850,
"end": 1390
} | class ____:
UnpackValueError = json.JSONDecodeError
@staticmethod
def packb(data: dict, use_bin_type: bool = True) -> bytes:
return json.dumps(data, cls=Encoder).encode()
@staticmethod
def loads(data: bytes, raw: bool = False) -> Any:
return json.loads(data, object_hook=Encoder.obj... | JSONMsgPack |
python | huggingface__transformers | src/transformers/models/upernet/modeling_upernet.py | {
"start": 1096,
"end": 2212
} | class ____(nn.Module):
"""
A convolutional block that bundles conv/norm/activation layers. This block simplifies the usage of convolution
layers, which are commonly used with a norm layer (e.g., BatchNorm) and activation layer (e.g., ReLU).
"""
def __init__(
self,
in_channels: int,
... | UperNetConvModule |
python | kamyu104__LeetCode-Solutions | Python/number-of-spaces-cleaning-robot-cleaned.py | {
"start": 33,
"end": 638
} | class ____(object):
def numberOfCleanRooms(self, room):
"""
:type room: List[List[int]]
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
result = r = c = d = 0
while not room[r][c]&(1<<(d+1)):
result += (room[r][c]>>1) == 0
... | Solution |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/urlfetch/snippets/main.py | {
"start": 1438,
"end": 2036
} | class ____(webapp2.RequestHandler):
"""Demonstrates an HTTP query using urlfetch."""
def get(self):
# [START gae_urlfetch_snippets_urlfetch_get]
url = "http://www.google.com/humans.txt"
try:
result = urlfetch.fetch(url)
if result.status_code == 200:
... | UrlFetchHandler |
python | pytorch__pytorch | test/test_mobile_optimizer.py | {
"start": 783,
"end": 26755
} | class ____(TestCase):
@skipIfNoXNNPACK
def test_optimize_for_mobile(self):
batch_size = 2
input_channels_per_group = 6
height = 16
width = 16
output_channels_per_group = 6
groups = 4
kernel_h = kernel_w = 3
stride_h = stride_w = 1
pad_h = ... | TestOptimizer |
python | psf__black | tests/data/cases/comments9.py | {
"start": 4634,
"end": 5279
} | class ____:
# First method has no empty lines between bare class def.
# More comments.
def first_method(self):
pass
# Regression test for https://github.com/psf/black/issues/3454.
def foo():
pass
# Trailing comment that belongs to this function
@decorator1
@decorator2 # fmt: skip
def ba... | MyClass |
python | realpython__materials | python-import/finders_and_loaders/debug_importer.py | {
"start": 34,
"end": 215
} | class ____:
@classmethod
def find_spec(cls, name, path, target=None):
print(f"Importing {name!r}")
return None
sys.meta_path.insert(0, DebugFinder)
| DebugFinder |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/tf_trt_integration_test_base.py | {
"start": 4243,
"end": 49631
} | class ____(test_util.TensorFlowTestCase):
"""Class to test Tensorflow-TensorRT integration."""
@property
def trt_incompatible_op(self):
return math_ops.erfc
@property
def trt_incompatible_binary_op(self):
return math_ops.igamma
@property
def precision_modes(self):
return ["FP32", "FP16", "I... | TfTrtIntegrationTestBase |
python | eventlet__eventlet | eventlet/greenpool.py | {
"start": 7355,
"end": 9322
} | class ____:
"""GreenPile is an abstraction representing a bunch of I/O-related tasks.
Construct a GreenPile with an existing GreenPool object. The GreenPile will
then use that pool's concurrency as it processes its jobs. There can be
many GreenPiles associated with a single GreenPool.
A GreenPil... | GreenPile |
python | kamyu104__LeetCode-Solutions | Python/maximum-ice-cream-bars.py | {
"start": 33,
"end": 357
} | class ____(object):
def maxIceCream(self, costs, coins):
"""
:type costs: List[int]
:type coins: int
:rtype: int
"""
costs.sort()
for i, c in enumerate(costs):
coins -= c
if coins < 0:
return i
return len(costs)
| Solution |
python | getsentry__sentry | src/sentry/similarity/features.py | {
"start": 1215,
"end": 8436
} | class ____:
def __init__(
self,
index,
encoder,
aliases,
features,
expected_extraction_errors,
expected_encoding_errors,
):
self.index = index
self.encoder = encoder
self.aliases = aliases
self.features = features
se... | FeatureSet |
python | doocs__leetcode | solution/0100-0199/0140.Word Break II/Solution.py | {
"start": 607,
"end": 1115
} | class ____:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
def dfs(s):
if not s:
return [[]]
res = []
for i in range(1, len(s) + 1):
if trie.search(s[:i]):
for v in dfs(s[i:]):
res... | Solution |
python | Pylons__pyramid | src/pyramid/response.py | {
"start": 2813,
"end": 6421
} | class ____:
"""Decorator activated via a :term:`scan` which treats the function
being decorated as a :term:`response adapter` for the set of types or
interfaces passed as ``*types_or_ifaces`` to the decorator constructor.
For example, if you scan the following response adapter:
.. code-block:: pyt... | response_adapter |
python | django__django | django/contrib/gis/db/models/fields.py | {
"start": 12248,
"end": 12603
} | class ____(Field):
"Used as a return value from an extent aggregate"
description = _("Extent Aggregate Field")
def get_internal_type(self):
return "ExtentField"
def select_format(self, compiler, sql, params):
select = compiler.connection.ops.select_extent
return select % sql i... | ExtentField |
python | doocs__leetcode | lcci/17.16.The Masseuse/Solution.py | {
"start": 0,
"end": 165
} | class ____:
def massage(self, nums: List[int]) -> int:
f = g = 0
for x in nums:
f, g = g + x, max(f, g)
return max(f, g)
| Solution |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 44756,
"end": 45239
} | class ____(TestCase):
# testing for this:
# File "/home/denis/work/gevent/gevent/pywsgi.py", line 70, in _do_read
# if length and length > self.content_length - self.position:
# TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'
validator = None
def application(self, environ,... | TestInputN |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/query/query_transform/base.py | {
"start": 977,
"end": 2390
} | class ____(PromptMixin, DispatcherSpanMixin):
"""
Base class for query transform.
A query transform augments a raw query string with associated transformations
to improve index querying.
The query transformation is performed before the query is sent to the index.
"""
def _get_prompt_modu... | BaseQueryTransform |
python | scipy__scipy | scipy/signal/tests/test_spectral.py | {
"start": 33916,
"end": 34476
} | class ____:
def test_identical_input(self):
x = np.random.randn(20)
y = np.copy(x) # So `y is x` -> False
f = np.linspace(0, 0.5, 6)
C = np.ones(6)
f1, C1 = coherence(x, y, nperseg=10)
assert_allclose(f, f1)
assert_allclose(C, C1)
def test_phase_shifte... | TestCoherence |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 70878,
"end": 77084
} | class ____(Constraint):
"""
Represent and decide various kinds of equality constraints between input sources.
A "source pair" is a pair of input sources for dynamic dimensions that
are specified equal. We represent `source_pairs` in a union-find forest
so that we can efficiently check whether two s... | EqualityConstraint |
python | django__django | tests/model_forms/tests.py | {
"start": 3805,
"end": 3956
} | class ____(forms.ModelForm):
class Meta:
model = CustomFieldForExclusionModel
fields = ["name", "markup"]
| CustomFieldForExclusionForm |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 152577,
"end": 154445
} | class ____(Response):
"""
Response of projects.update endpoint.
:param updated: Number of projects updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "projects"
_action = "update"
_version = "2.20"
_schema = ... | UpdateResponse |
python | numpy__numpy | numpy/_core/tests/test_overrides.py | {
"start": 10724,
"end": 16015
} | class ____:
def test_one_arg(self):
MyArray, implements = _new_duck_type_and_implements()
@implements(dispatched_one_arg)
def _(array):
return 'myarray'
assert_equal(dispatched_one_arg(1), 'original')
assert_equal(dispatched_one_arg(MyArray()), 'myarray')
... | TestArrayFunctionImplementation |
python | ZoranPandovski__al-go-rithms | data_structures/Linked_list/Python/merge_two_sorted_lists.py | {
"start": 720,
"end": 835
} | class ____:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
| ListNode |
python | dagster-io__dagster | python_modules/libraries/dagster-databricks/dagster_databricks/components/databricks_asset_bundle/configs.py | {
"start": 7860,
"end": 9535
} | class ____(DatabricksBaseTask[jobs.SparkPythonTask]):
@property
def task_type(self) -> str:
return "spark_python"
@property
def task_config_metadata(self) -> Mapping[str, Any]:
task_config_metadata = {}
python_config = self.task_config["spark_python_task"]
task_config_me... | DatabricksSparkPythonTask |
python | falconry__falcon | tests/test_hello.py | {
"start": 203,
"end": 500
} | class ____:
def __init__(self, file_like, block_size=8192):
self.file_like = file_like
self.block_size = block_size
def __getitem__(self, key):
data = self.file_like.read(self.block_size)
if data:
return data
raise IndexError
| FileWrapper |
python | pypa__virtualenv | src/virtualenv/activation/powershell/__init__.py | {
"start": 106,
"end": 823
} | class ____(ViaTemplateActivator):
def templates(self):
yield "activate.ps1"
@staticmethod
def quote(string):
"""
This should satisfy PowerShell quoting rules [1], unless the quoted
string is passed directly to Windows native commands [2].
[1]: https://learn.microsof... | PowerShellActivator |
python | doocs__leetcode | solution/3500-3599/3555.Smallest Subarray to Sort in Every Sliding Window/Solution.py | {
"start": 0,
"end": 602
} | class ____:
def minSubarraySort(self, nums: List[int], k: int) -> List[int]:
def f(i: int, j: int) -> int:
mi, mx = inf, -inf
l = r = -1
for k in range(i, j + 1):
if mx > nums[k]:
r = k
else:
mx = num... | Solution |
python | getsentry__sentry | src/sentry/sentry_apps/services/app/model.py | {
"start": 2109,
"end": 2346
} | class ____(RpcModel):
"""
A `SentryAppService` (a notification service) wrapped up and serializable via the
rpc interface.
"""
title: str = ""
slug: str = ""
service_type: str = "sentry_app"
| RpcSentryAppService |
python | getsentry__sentry | src/sentry/api/endpoints/project_servicehook_stats.py | {
"start": 509,
"end": 1511
} | class ____(ProjectEndpoint, StatsMixin):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
}
def get(self, request: Request, project, hook_id) -> Response:
try:
hook = ServiceHook.objects.get(project_id=project.id, guid=hook_id)
except... | ProjectServiceHookStatsEndpoint |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_projects_tasks.py | {
"start": 530,
"end": 1938
} | class ____(TestCase):
def setUp(self):
self.project = get(Project)
self.internal_version = get(Version, project=self.project)
self.external_version = get(Version, project=self.project, type=EXTERNAL)
self.external_build = get(
Build, project=self.project, version=self.ext... | SendBuildStatusTests |
python | huggingface__transformers | src/transformers/models/perception_lm/modeling_perception_lm.py | {
"start": 7209,
"end": 14457
} | class ____(PerceptionLMPreTrainedModel):
_checkpoint_conversion_mapping = {}
def __init__(self, config: PerceptionLMConfig):
super().__init__(config)
self.vision_tower = AutoModel.from_config(config.vision_config)
self.multi_modal_projector = PerceptionLMMultiModalProjector(config)
... | PerceptionLMModel |
python | kamyu104__LeetCode-Solutions | Python/zigzag-iterator.py | {
"start": 50,
"end": 602
} | class ____(object):
def __init__(self, v1, v2):
"""
Initialize your q structure here.
:type v1: List[int]
:type v2: List[int]
"""
self.q = collections.deque([(len(v), iter(v)) for v in (v1, v2) if v])
def next(self):
"""
:rtype: int
"""
... | ZigzagIterator |
python | Textualize__textual | docs/examples/styles/box_sizing.py | {
"start": 65,
"end": 336
} | class ____(App):
CSS_PATH = "box_sizing.tcss"
def compose(self):
yield Static("I'm using border-box!", id="static1")
yield Static("I'm using content-box!", id="static2")
if __name__ == "__main__":
app = BoxSizingApp()
app.run()
| BoxSizingApp |
python | facebookresearch__faiss | tests/test_binary_io.py | {
"start": 3029,
"end": 3911
} | class ____(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
d = 32
nt = 200
nb = 1500
nq = 500
(self.xt, self.xb, self.xq) = make_binary_dataset(d, nb, nt, nq)
def test_binary_from_float(self):
d... | TestBinaryFromFloat |
python | automl__auto-sklearn | autosklearn/estimators.py | {
"start": 63301,
"end": 66805
} | class ____(AutoSklearnEstimator, RegressorMixin):
"""
This class implements the regression task.
"""
def fit(self, X, y, X_test=None, y_test=None, feat_type=None, dataset_name=None):
"""Fit *Auto-sklearn* to given training set (X, y).
Fit both optimizes the machine learning models and... | AutoSklearnRegressor |
python | run-llama__llama_index | llama-index-core/tests/node_parser/test_node_parser.py | {
"start": 176,
"end": 1379
} | class ____(NodeParser):
def _parse_nodes(
self, nodes: Sequence[BaseNode], show_progress: bool = False, **kwargs: Any
) -> List[BaseNode]:
return super()._parse_nodes(nodes, show_progress, **kwargs)
def test__postprocess_parsed_nodes_include_metadata():
np = _TestNodeParser()
nodes = ... | _TestNodeParser |
python | dagster-io__dagster | python_modules/libraries/dagster-gcp/dagster_gcp/bigquery/io_manager.py | {
"start": 6928,
"end": 13192
} | class ____(ConfigurableIOManagerFactory):
"""Base class for an I/O manager definition that reads inputs from and writes outputs to BigQuery.
Examples:
.. code-block:: python
from dagster_gcp import BigQueryIOManager
from dagster_bigquery_pandas import BigQueryPandasTypeHandler
... | BigQueryIOManager |
python | apache__airflow | providers/elasticsearch/tests/unit/elasticsearch/log/test_es_response.py | {
"start": 1494,
"end": 2547
} | class ____:
def test_initialization(self):
test_list = [1, 2, 3]
attr_list = AttributeList(test_list)
assert attr_list._l_ == test_list
test_tuple = (1, 2, 3)
attr_list = AttributeList(test_tuple)
assert attr_list._l_ == list(test_tuple)
def test_index_access(se... | TestAttributeList |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 27791,
"end": 28958
} | class ____(Response):
"""
Response of queues.delete endpoint.
:param deleted: Number of queues deleted (0 or 1)
:type deleted: int
"""
_service = "queues"
_action = "delete"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"deleted": {
... | DeleteResponse |
python | Netflix__metaflow | metaflow/plugins/airflow/airflow_utils.py | {
"start": 23779,
"end": 28905
} | class ____(object):
def __init__(self, file_path=None, graph_structure=None, metadata=None, **kwargs):
self._dag_instantiation_params = AirflowDAGArgs(**kwargs)
self._file_path = file_path
self._metadata = metadata
tree = lambda: defaultdict(tree)
self.states = tree()
... | Workflow |
python | kamyu104__LeetCode-Solutions | Python/fizz-buzz-multithreaded.py | {
"start": 48,
"end": 2007
} | class ____(object):
def __init__(self, n):
self.__n = n
self.__curr = 0
self.__cv = threading.Condition()
# printFizz() outputs "fizz"
def fizz(self, printFizz):
"""
:type printFizz: method
:rtype: void
"""
for i in xrange(1, self.__n+1):
... | FizzBuzz |
python | dask__distributed | distributed/spans.py | {
"start": 960,
"end": 2991
} | class ____(TypedDict):
collections: list[dict]
@contextmanager
def span(*tags: str) -> Iterator[str]:
"""Tag group of tasks to be part of a certain group, called a span.
This context manager can be nested, thus creating sub-spans. If you close and
re-open a span context manager with the same tag, you... | SpanMetadata |
python | python-markdown__markdown | markdown/blockprocessors.py | {
"start": 23336,
"end": 24365
} | class ____(BlockProcessor):
""" Process blocks that are empty or start with an empty line. """
def test(self, parent: etree.Element, block: str) -> bool:
return not block or block.startswith('\n')
def run(self, parent: etree.Element, blocks: list[str]) -> None:
block = blocks.pop(0)
... | EmptyBlockProcessor |
python | ansible__ansible | lib/ansible/module_utils/facts/hardware/dragonfly.py | {
"start": 834,
"end": 1037
} | class ____(HardwareCollector):
# Note: This uses the freebsd fact class, there is no dragonfly hardware fact class
_fact_class = FreeBSDHardware
_platform = 'DragonFly'
| DragonFlyHardwareCollector |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_v2_test.py | {
"start": 2594,
"end": 3200
} | class ____(feature_column_v2_types.FeatureColumn):
"""A base FeatureColumn useful to avoid boiler-plate in tests.
Provides dummy implementations for abstract methods that raise ValueError in
order to avoid re-defining all abstract methods for each test sub-class.
"""
@property
def parents(self):
raise... | BaseFeatureColumnForTests |
python | numba__numba | numba/tests/npyufunc/ufuncbuilding_usecases.py | {
"start": 609,
"end": 976
} | class ____:
pass
def guadd_obj(a, b, c):
Dummy() # to force object mode
x, y = c.shape
for i in range(x):
for j in range(y):
c[i, j] = a[i, j] + b[i, j]
def guadd_scalar_obj(a, b, c):
Dummy() # to force object mode
x, y = c.shape
for i in range(x):
for j in ... | Dummy |
python | rapidsai__cudf | python/cudf/cudf/pandas/fast_slow_proxy.py | {
"start": 14791,
"end": 16041
} | class ____(type):
"""
Metaclass used to dynamically find class attributes and
classmethods of fast-slow proxy types.
"""
_fsproxy_slow_dir: list
_fsproxy_slow_type: type
_fsproxy_fast_type: type
@property
def _fsproxy_slow(self) -> type:
return self._fsproxy_slow_type
... | _FastSlowProxyMeta |
python | jpadilla__pyjwt | jwt/exceptions.py | {
"start": 200,
"end": 327
} | class ____(InvalidTokenError):
"""Raised when a token cannot be decoded because it failed validation"""
pass
| DecodeError |
python | neetcode-gh__leetcode | python/0002-add-two-numbers.py | {
"start": 151,
"end": 725
} | class ____:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode()
cur = dummy
carry = 0
while l1 or l2 or carry:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0
# new digit
val = v1 + v2 + carry
... | Solution |
python | kubernetes-client__python | kubernetes/client/models/v1_resource_claim_list.py | {
"start": 383,
"end": 7002
} | 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... | V1ResourceClaimList |
python | optuna__optuna | optuna/terminator/erroreval.py | {
"start": 353,
"end": 638
} | class ____(metaclass=abc.ABCMeta):
"""Base class for error evaluators."""
@abc.abstractmethod
def evaluate(
self,
trials: list[FrozenTrial],
study_direction: StudyDirection,
) -> float:
pass
@experimental_class("3.2.0")
| BaseErrorEvaluator |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-huggingface-api/llama_index/embeddings/huggingface_api/pooling.py | {
"start": 130,
"end": 2244
} | class ____(str, Enum):
"""Enum of possible pooling choices with pooling behaviors."""
CLS = "cls"
MEAN = "mean"
LAST = "last" # last token pooling
def __call__(self, array: np.ndarray) -> np.ndarray:
if self == self.CLS:
return self.cls_pooling(array)
elif self == self... | Pooling |
python | numpy__numpy | numpy/ma/core.py | {
"start": 82068,
"end": 217422
} | class ____(ndarray):
"""
An array class with possibly masked values.
Masked values of True exclude the corresponding element from any
computation.
Construction::
x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True,
ndmin=0, fill_value=None, keep_mask=... | MaskedArray |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_C.py | {
"start": 11521,
"end": 13073
} | class ____(Benchmark):
r"""
Cross-in-Tray objective function.
This class defines the Cross-in-Tray [1]_ global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{CrossInTray}}(x) = - 0.0001 \left(\left|{e^{\left|{100
- \frac{\sqr... | CrossInTray |
python | pypa__pip | src/pip/_vendor/rich/_log_render.py | {
"start": 308,
"end": 3225
} | class ____:
def __init__(
self,
show_time: bool = True,
show_level: bool = False,
show_path: bool = True,
time_format: Union[str, FormatTimeCallable] = "[%x %X]",
omit_repeated_times: bool = True,
level_width: Optional[int] = 8,
) -> None:
self.sho... | LogRender |
python | keon__algorithms | algorithms/strings/rabin_karp.py | {
"start": 76,
"end": 1557
} | class ____:
def __init__(self, text, size_word):
self.text = text
self.hash = 0
self.size_word = size_word
for i in range(0, size_word):
#ord maps the character to a number
#subtract out the ASCII value of "a" to start the indexing at zero
self.ha... | RollingHash |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 31271,
"end": 32704
} | class ____(BaseModel):
"""Add a new value to be redacted in task logs."""
# This is needed since calls to `mask_secret` in the Task process will otherwise only add the mask value
# to the child process, but the redaction happens in the parent.
# We cannot use `string | Iterable | dict here` (would be m... | MaskSecret |
python | readthedocs__readthedocs.org | readthedocs/search/api/v2/serializers.py | {
"start": 1567,
"end": 1750
} | class ____(serializers.Serializer):
title = serializers.SerializerMethodField()
def get_title(self, obj):
return list(getattr(obj, "title", []))
| PageHighlightSerializer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 91609,
"end": 92308
} | class ____(
SingletonConstant, roles.ConstExprRole[bool], ColumnElement[bool]
):
"""Represent the ``false`` keyword, or equivalent, in a SQL statement.
:class:`.False_` is accessed as a constant via the
:func:`.false` function.
"""
__visit_name__ = "false"
_traverse_internals: _TraverseIn... | False_ |
python | pytorch__pytorch | test/cpp/aoti_inference/compile_model.py | {
"start": 186,
"end": 353
} | class ____(torch.nn.Module):
def __init__(self, data):
super().__init__()
for key in data:
setattr(self, key, data[key])
| TensorSerializer |
python | huggingface__transformers | tests/models/glm46v/test_video_processing_glm46v.py | {
"start": 1229,
"end": 5451
} | class ____:
def __init__(
self,
parent,
batch_size=5,
num_frames=8,
num_channels=3,
min_resolution=30,
max_resolution=80,
temporal_patch_size=2,
patch_size=14,
merge_size=2,
do_resize=True,
size=None,
do_normaliz... | Glm46VVideoProcessingTester |
python | run-llama__llama_index | llama-index-instrumentation/src/llama_index_instrumentation/__init__.py | {
"start": 1116,
"end": 3138
} | class ____(ABC):
"""
Apply the `dispatcher.span` decorator to implementations of abstract methods, as well
as any methods previously decorated (in any base class) that are being overridden by
a subclass. For example, if class `A` has abstract method `f`, and class `B` inherits
from `A` and provides ... | DispatcherSpanMixin |
python | django__django | tests/expressions/tests.py | {
"start": 64497,
"end": 72238
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.n = Number.objects.create(integer=42, float=15.5)
cls.n1 = Number.objects.create(integer=-42, float=-15.5)
def test_lefthand_addition(self):
# LH Addition of floats and integers
Number.objects.filter(pk=self.n.pk... | ExpressionOperatorTests |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 20344,
"end": 20645
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneMessageEvent, GrapheneStepEvent)
name = "AssetCheckEvaluationPlannedEvent"
assetKey = graphene.NonNull(GrapheneAssetKey)
checkName = graphene.NonNull(graphene.String)
| GrapheneAssetCheckEvaluationPlannedEvent |
python | spack__spack | lib/spack/spack/ci/common.py | {
"start": 13629,
"end": 16976
} | class ____:
"""Turn a list of specs into a simple directed graph, that doesn't keep track
of edge types."""
@classmethod
def key(cls, spec: spack.spec.Spec) -> str:
return spec.dag_hash()
def __init__(self, specs: List[spack.spec.Spec]) -> None:
# Build dictionary of nodes
... | PipelineDag |
python | mlflow__mlflow | mlflow/utils/autologging_utils/safety.py | {
"start": 35969,
"end": 36131
} | class ____:
def __init__(self, integration, id_):
self.integration = integration
self.id = id_
self.state = "running"
| AutologgingSession |
python | scrapy__scrapy | scrapy/contracts/__init__.py | {
"start": 3324,
"end": 7681
} | class ____:
contracts: dict[str, type[Contract]] = {}
def __init__(self, contracts: Iterable[type[Contract]]):
for contract in contracts:
self.contracts[contract.name] = contract
def tested_methods_from_spidercls(self, spidercls: type[Spider]) -> list[str]:
is_method = re.compi... | ContractsManager |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 20127,
"end": 22922
} | class ____:
def test_pdf_no_overflow_warning(self):
# The argument is large enough that x**2 will overflow to
# infinity and 1/(1 + x**2) will be 0. This should not
# trigger a warning.
p = stats.cauchy.pdf(1e200)
assert p == 0.0
# Reference values were computed with m... | TestCauchy |
python | sqlalchemy__sqlalchemy | test/orm/test_query.py | {
"start": 184142,
"end": 186256
} | class ____(QueryTest, AssertsCompiledSQL):
__dialect__ = "default"
def test_hints(self):
User = self.classes.User
from sqlalchemy.dialects import mysql
dialect = mysql.dialect()
sess = fixture_session()
self.assert_compile(
sess.query(User).with_hint(
... | HintsTest |
python | prabhupant__python-ds | data_structures/linked_list/remove_nth_node_from_end.py | {
"start": 0,
"end": 616
} | class ____():
def __init__(self, val):
self.val = val
self.next = None
def remove(head, n):
res = head
slow = head
fast = head
for i in range(n+1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return... | Node |
python | sphinx-doc__sphinx | sphinx/domains/python/__init__.py | {
"start": 11462,
"end": 13482
} | class ____(PyObject):
"""Description of an attribute."""
option_spec = PyObject.option_spec.copy()
option_spec.update({
'abstract': directives.flag,
'abstractmethod': directives.flag,
'classmethod': directives.flag,
'type': directives.unchanged,
})
def handle_signat... | PyProperty |
python | dagster-io__dagster | python_modules/dagster/dagster/_daemon/auto_run_reexecution/event_log_consumer.py | {
"start": 988,
"end": 9305
} | class ____(IntervalDaemon):
def __init__(
self,
interval_seconds: int = _INTERVAL_SECONDS,
event_log_fetch_limit: int = _EVENT_LOG_FETCH_LIMIT,
):
super().__init__(interval_seconds=interval_seconds)
self._event_log_fetch_limit = event_log_fetch_limit
@classmethod
... | EventLogConsumerDaemon |
python | anthropics__anthropic-sdk-python | src/anthropic/types/completion_create_params.py | {
"start": 3936,
"end": 4839
} | class ____(CompletionCreateParamsBase):
stream: Required[Literal[True]]
"""Whether to incrementally stream the response using server-sent events.
See [streaming](https://docs.claude.com/en/api/streaming) for details.
"""
CompletionRequestStreamingMetadata = MetadataParam
"""This is deprecated, `Metad... | CompletionCreateParamsStreaming |
python | django__django | tests/postgres_tests/test_search.py | {
"start": 642,
"end": 3625
} | class ____:
@classmethod
def setUpTestData(cls):
cls.robin = Scene.objects.create(
scene="Scene 10", setting="The dark forest of Ewing"
)
cls.minstrel = Character.objects.create(name="Minstrel")
verses = [
(
"Bravely bold Sir Robin, rode fo... | GrailTestData |
python | doocs__leetcode | solution/2100-2199/2139.Minimum Moves to Reach Target Score/Solution2.py | {
"start": 0,
"end": 339
} | class ____:
def minMoves(self, target: int, maxDoubles: int) -> int:
ans = 0
while maxDoubles and target > 1:
ans += 1
if target % 2 == 1:
target -= 1
else:
maxDoubles -= 1
target >>= 1
ans += target - 1
... | Solution |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 112321,
"end": 112442
} | class ____:
xlNext = 1 # from enum XlSearchDirection
xlPrevious = 2 # from enum XlSearchDirection
| SearchDirection |
python | matplotlib__matplotlib | lib/matplotlib/colors.py | {
"start": 120683,
"end": 121111
} | class ____(Normalize):
"""
Dummy replacement for `Normalize`, for the case where we want to use
indices directly in a `~matplotlib.cm.ScalarMappable`.
"""
def __call__(self, value, clip=None):
if np.iterable(value):
return np.ma.array(value)
return value
def inverse(... | NoNorm |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 1247,
"end": 1409
} | class ____(Web3Exception, TypeError):
"""
A web3.py exception wrapper for `TypeError`, for better control over
exception handling.
"""
| Web3TypeError |
python | python-openxml__python-docx | tests/oxml/test_table.py | {
"start": 1444,
"end": 13640
} | class ____:
"""Unit-test suite for `docx.oxml.table.CT_Tc` objects."""
@pytest.mark.parametrize(
("tr_cxml", "tc_idx", "expected_value"),
[
("w:tr/(w:tc/w:p,w:tc/w:p)", 0, 0),
("w:tr/(w:tc/w:p,w:tc/w:p)", 1, 1),
("w:tr/(w:trPr/w:gridBefore{w:val=2},w:tc/w:p,w... | DescribeCT_Tc |
python | MongoEngine__mongoengine | tests/test_dereference.py | {
"start": 134,
"end": 39067
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.db = connect(db="mongoenginetest")
@classmethod
def tearDownClass(cls):
cls.db.drop_database("mongoenginetest")
def test_list_item_dereference(self):
"""Ensure that DBRef items in ListFields are dereferenc... | FieldTest |
python | doocs__leetcode | solution/2100-2199/2169.Count Operations to Obtain Zero/Solution.py | {
"start": 0,
"end": 266
} | class ____:
def countOperations(self, num1: int, num2: int) -> int:
ans = 0
while num1 and num2:
if num1 >= num2:
num1 -= num2
else:
num2 -= num1
ans += 1
return ans
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 737,
"end": 778
} | class ____(Class3[T_co]): ...
| Class3_Child1 |
python | readthedocs__readthedocs.org | readthedocs/doc_builder/backends/mkdocs.py | {
"start": 2337,
"end": 2427
} | class ____(BaseMkdocs):
builder = "build"
build_dir = "_readthedocs/html"
| MkdocsHTML |
python | pallets__itsdangerous | src/itsdangerous/exc.py | {
"start": 1619,
"end": 1788
} | class ____(BadTimeSignature):
"""Raised if a signature timestamp is older than ``max_age``. This
is a subclass of :exc:`BadTimeSignature`.
"""
| SignatureExpired |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.