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 | numba__numba | numba/tests/test_typedlist.py | {
"start": 21954,
"end": 23660
} | class ____(MemoryLeakMixin, TestCase):
def test_allocation(self):
# kwarg version
for i in range(16):
tl = List.empty_list(types.int32, allocated=i)
self.assertEqual(tl._allocated(), i)
# posarg version
for i in range(16):
tl = List.empty_list(ty... | TestAllocation |
python | kamyu104__LeetCode-Solutions | Python/number-of-1-bits.py | {
"start": 1722,
"end": 1976
} | class ____(object):
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
result = 0
while n:
n &= n - 1
result += 1
return result
# Time: O(logn) = O(32)
# Space: O(1)
| Solution3 |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/tests/test_panels.py | {
"start": 452,
"end": 2979
} | class ____(Panel):
"""Example external panel."""
def __init__(self):
"""Initialize panel."""
Panel.__init__(self)
self.setMouseTracking(True)
self.scrollable = True
def sizeHint(self):
"""Override Qt method.
Returns the widget size hint (based on the editor ... | EmojiPanel |
python | sphinx-doc__sphinx | sphinx/ext/autosummary/generate.py | {
"start": 5834,
"end": 31629
} | class ____:
def __init__(
self,
obj: Any,
*,
config: Config,
events: EventManager,
) -> None:
self.config = config
self.events = events
self.object = obj
def get_object_type(self, name: str, value: Any) -> str:
return _get_documenter(v... | ModuleScanner |
python | pytorch__pytorch | torch/distributed/tensor/_ops/_mask_buffer.py | {
"start": 140,
"end": 1532
} | class ____:
data: torch.Tensor | None = None
# refcount allows shared usage of the MaskBuffer, as long as all users have the same data
refcount: int = 0
def materialize_mask(self, mask):
if self.refcount == 0:
self.data = mask
else:
assert self.data is not None
... | MaskBuffer |
python | google__jax | jax/_src/interpreters/batching.py | {
"start": 42326,
"end": 51049
} | class ____:
def __setitem__(self, prim, batcher):
def wrapped(axis_data, vals, dims, **params):
return batcher(axis_data.size, axis_data.name, None, vals, dims, **params)
fancy_primitive_batchers[prim] = wrapped
axis_primitive_batchers = AxisPrimitiveBatchersProxy()
# Presence in this table allows fa... | AxisPrimitiveBatchersProxy |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 891718,
"end": 891926
} | class ____(VegaLiteSchema):
"""PositionDef schema wrapper."""
_schema = {"$ref": "#/definitions/PositionDef"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| PositionDef |
python | PrefectHQ__prefect | tests/cli/test_flow.py | {
"start": 402,
"end": 6462
} | class ____:
"""
These tests ensure that the `prefect flow serve` interacts with Runner
in the expected way. Behavior such as flow run
execution and cancellation are tested in test_runner.py.
"""
@pytest.fixture
async def mock_runner_start(self, monkeypatch):
mock = AsyncMock()
... | TestFlowServe |
python | numba__numba | numba/cuda/vectorizers.py | {
"start": 5276,
"end": 7246
} | class ____(UFuncMechanism):
"""
Provide CUDA specialization
"""
DEFAULT_STREAM = 0
def launch(self, func, count, stream, args):
func.forall(count, stream=stream)(*args)
def is_device_array(self, obj):
return cuda.is_cuda_array(obj)
def as_device_array(self, obj):
#... | CUDAUFuncMechanism |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 13139,
"end": 13372
} | class ____(VOTableSpecWarning):
"""
The attribute must be a valid URI as defined in `RFC 2396
<https://www.ietf.org/rfc/rfc2396.txt>`_.
"""
message_template = "'{}' is not a valid URI"
default_args = ("x",)
| W05 |
python | pypa__setuptools | setuptools/_distutils/errors.py | {
"start": 2309,
"end": 2576
} | class ____(DistutilsError):
"""We don't know how to do something on the current platform (but
we do know how to do it on some platform) -- eg. trying to compile
C files on a platform not supported by a CCompiler subclass."""
pass
| DistutilsPlatformError |
python | kamyu104__LeetCode-Solutions | Python/maximum-candies-you-can-get-from-boxes.py | {
"start": 52,
"end": 1000
} | class ____(object):
def maxCandies(self, status, candies, keys, containedBoxes, initialBoxes):
"""
:type status: List[int]
:type candies: List[int]
:type keys: List[List[int]]
:type containedBoxes: List[List[int]]
:type initialBoxes: List[int]
:rtype: int
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/unique-number-of-occurrences.py | {
"start": 420,
"end": 656
} | class ____(object):
def uniqueOccurrences(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
count = collections.Counter(arr)
return len(count) == len(set(count.itervalues()))
| Solution2 |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fragments_on_composite_types.py | {
"start": 160,
"end": 1333
} | class ____(ValidationRule):
def enter_InlineFragment(self, node, key, parent, path, ancestors):
type = self.context.get_type()
if node.type_condition and type and not is_composite_type(type):
self.context.report_error(GraphQLError(
self.inline_fragment_on_non_composite_... | FragmentsOnCompositeTypes |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis39.py | {
"start": 315,
"end": 1600
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis39.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 30524,
"end": 30776
} | class ____(GroupByApply):
@functools.cached_property
def grp_func(self):
return functools.partial(groupby_slice_transform, func=self.func)
def _fillna(group, *, what, **kwargs):
return getattr(group, what)(**kwargs)
| GroupByTransform |
python | ansible__ansible | lib/ansible/module_utils/facts/virtual/base.py | {
"start": 1820,
"end": 2465
} | class ____(BaseFactCollector):
name = 'virtual'
_fact_class = Virtual
_fact_ids = set([
'virtualization_type',
'virtualization_role',
'virtualization_tech_guest',
'virtualization_tech_host',
]) # type: t.Set[str]
def collect(self, module=None, collected_facts=None):... | VirtualCollector |
python | tensorflow__tensorflow | tensorflow/python/distribute/cross_device_ops.py | {
"start": 33893,
"end": 39352
} | class ____(CrossDeviceOps):
"""All-reduce implementation of CrossDeviceOps.
It performs all-reduce when applicable using NCCL or hierarchical copy. For
the batch API, tensors will be repacked or aggregated for more efficient
cross-device transportation.
For reduces that are not all-reduce, it falls back to
... | AllReduceCrossDeviceOps |
python | pytorch__pytorch | test/onnx/test_models.py | {
"start": 1578,
"end": 10932
} | class ____(pytorch_test_common.ExportTestCase):
opset_version = 9 # Caffe2 doesn't support the default.
keep_initializers_as_inputs = False
def exportTest(self, model, inputs, rtol=1e-2, atol=1e-7, **kwargs):
import caffe2.python.onnx.backend as backend
with torch.onnx.select_model_mode_f... | TestModels |
python | aio-libs__aiohttp | aiohttp/resolver.py | {
"start": 625,
"end": 2607
} | class ____(AbstractResolver):
"""Threaded resolver.
Uses an Executor for synchronous getaddrinfo() calls.
concurrent.futures.ThreadPoolExecutor is used by default.
"""
def __init__(self) -> None:
self._loop = asyncio.get_running_loop()
async def resolve(
self, host: str, port:... | ThreadedResolver |
python | kamyu104__LeetCode-Solutions | Python/total-distance-traveled.py | {
"start": 36,
"end": 370
} | class ____(object):
def distanceTraveled(self, mainTank, additionalTank):
"""
:type mainTank: int
:type additionalTank: int
:rtype: int
"""
USE, REFILL, DIST = 5, 1, 10
cnt = min((mainTank-REFILL)//(USE-REFILL), additionalTank)
return (mainTank+cnt*REF... | Solution |
python | jina-ai__jina | jina/clients/websocket.py | {
"start": 222,
"end": 837
} | class ____(WebSocketBaseClient, PostMixin, ProfileMixin, HealthCheckMixin):
"""A client connecting to a Gateway using WebSocket protocol.
Instantiate this class through the :meth:`jina.Client` convenience method.
EXAMPLE USAGE
.. code-block:: python
from jina import Client
from docar... | WebSocketClient |
python | Textualize__textual | src/textual/reactive.py | {
"start": 14780,
"end": 16065
} | class ____(Reactive[ReactiveType]):
"""Create a reactive attribute.
Args:
default: A default value or callable that returns a default.
layout: Perform a layout on change.
repaint: Perform a repaint on change.
init: Call watchers on initialize (post mount).
always_update:... | reactive |
python | apache__airflow | providers/common/sql/src/airflow/providers/common/sql/sensors/sql.py | {
"start": 1215,
"end": 5470
} | class ____(BaseSensorOperator):
"""
Run a SQL statement repeatedly until a criteria is met.
This will keep trying until success or failure criteria are met, or if the
first cell is not either ``0``, ``'0'``, ``''``, or ``None``. Optional
success and failure callables are called with the first cell ... | SqlSensor |
python | PyCQA__pylint | tests/functional/m/multiple_statements.py | {
"start": 928,
"end": 986
} | class ____(Exception): a='a' # [multiple-statements]
| MyError |
python | graphql-python__graphene | graphene/types/scalars.py | {
"start": 1401,
"end": 2345
} | class ____(Scalar):
"""
The `Int` scalar type represents non-fractional signed whole numeric
values. Int can represent values between -(2^53 - 1) and 2^53 - 1 since
represented in JSON as double-precision floating point numbers specified
by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point... | Int |
python | pytorch__pytorch | torchgen/_autoheuristic/train_decision.py | {
"start": 818,
"end": 22664
} | class ____(AHTrain):
def __init__(self):
super().__init__()
def debug_time(self, row, top_k_choices):
choices_feedback = json.loads(row["choice2time"])
timings = sorted(choices_feedback.items(), key=lambda x: x[1])
for choice, time in timings:
result = f"{choice} {ti... | AHTrainDecisionTree |
python | ray-project__ray | python/ray/tests/test_autoscaler.py | {
"start": 10155,
"end": 11367
} | class ____(unittest.TestCase):
def testHeartbeat(self):
lm = LoadMetrics()
lm.update("1.1.1.1", mock_node_id(), {"CPU": 2}, {"CPU": 1}, 0)
lm.mark_active("2.2.2.2")
assert "1.1.1.1" in lm.last_heartbeat_time_by_ip
assert "2.2.2.2" in lm.last_heartbeat_time_by_ip
asser... | LoadMetricsTest |
python | pytorch__pytorch | torch/_dynamo/eval_frame.py | {
"start": 59568,
"end": 65034
} | class ____(torch.fx.Transformer):
def __init__(
self,
m: torch.fx.GraphModule,
flat_args: list[Any],
matched_input_elements_positions: list[int],
flat_results: Sequence[Any],
matched_output_elements_positions: list[int],
example_fake_inputs: list[torch.Tensor]... | FlattenInputOutputSignature |
python | huggingface__transformers | src/transformers/integrations/executorch.py | {
"start": 1034,
"end": 6637
} | class ____:
"""
A wrapper class for exporting Vision-Language Models (VLMs) like SmolVLM2 for ExecuTorch.
This class handles the export of three main components:
1. Vision encoder (processes images to visual features)
2. Connector/projector (maps visual features to text embedding space)
... | TorchExportableModuleForVLM |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 18907,
"end": 20055
} | class ____(PointEvent):
''' Announce a pan event on a Bokeh plot.
Attributes:
delta_x (float) : the amount of scroll in the x direction
delta_y (float) : the amount of scroll in the y direction
direction (float) : the direction of scroll (1 or -1)
sx (float) : x-coordinate of th... | Pan |
python | django__django | tests/csrf_tests/views.py | {
"start": 955,
"end": 2604
} | class ____(MiddlewareMixin):
def process_response(self, request, response):
rotate_token(request)
return response
csrf_rotating_token = decorator_from_middleware(_CsrfCookieRotator)
@csrf_protect
def protected_view(request):
return HttpResponse("OK")
@ensure_csrf_cookie
def ensure_csrf_coo... | _CsrfCookieRotator |
python | ray-project__ray | python/ray/serve/tests/test_config_files/use_custom_autoscaling_policy.py | {
"start": 204,
"end": 352
} | class ____:
def __call__(self):
return "hello_from_custom_autoscaling_policy"
app = CustomAutoscalingPolicy.bind()
| CustomAutoscalingPolicy |
python | spyder-ide__spyder | spyder/utils/syntaxhighlighters.py | {
"start": 81258,
"end": 83832
} | class ____(RegexLexer):
"""
A lexer for logs generated by the Python builtin 'logging' library.
Taken from
https://bitbucket.org/birkenfeld/pygments-main/pull-requests/451/add-python-logging-lexer
"""
name = 'Python Logging'
aliases = ['pylog', 'pythonlogging']
filenames = ['*.log']
... | PythonLoggingLexer |
python | apache__airflow | providers/google/src/airflow/providers/google/suite/hooks/sheets.py | {
"start": 1167,
"end": 17026
} | class ____(GoogleBaseHook):
"""
Interact with Google Sheets via Google Cloud connection.
Reading and writing cells in Google Sheet: https://developers.google.com/sheets/api/guides/values
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param api_version: API Version
... | GSheetsHook |
python | mozilla__bleach | bleach/_vendor/html5lib/treebuilders/etree_lxml.py | {
"start": 1208,
"end": 6614
} | class ____(object):
def __init__(self):
self._elementTree = None
self._childNodes = []
def appendChild(self, element):
last = self._elementTree.getroot()
for last in self._elementTree.getroot().itersiblings():
pass
last.addnext(element._element)
def _ge... | Document |
python | numba__numba | numba/core/types/containers.py | {
"start": 9539,
"end": 9937
} | class ____(_StarArgTupleMixin, Tuple):
"""To distinguish from Tuple() used as argument to a `*args`.
"""
def __new__(cls, types):
_HeterogeneousTuple.is_types_iterable(types)
if types and all(t == types[0] for t in types[1:]):
return StarArgUniTuple(dtype=types[0], count=len(ty... | StarArgTuple |
python | scrapy__scrapy | tests/CrawlerProcess/asyncio_enabled_reactor_different_loop.py | {
"start": 291,
"end": 666
} | class ____(scrapy.Spider):
name = "no_request"
async def start(self):
return
yield
process = CrawlerProcess(
settings={
"TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor",
"ASYNCIO_EVENT_LOOP": "uvloop.Loop",
}
)
d = process.crawl(NoRequestsSpi... | NoRequestsSpider |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/_immutabledict_cy.py | {
"start": 1904,
"end": 3104
} | class ____(Dict[_KT, _VT]):
# NOTE: this method is required in 3.9 and speeds up the use case
# ImmutableDictBase[str,int](a_dict) significantly
@classmethod
def __class_getitem__( # type: ignore[override]
cls, key: Any
) -> type[Self]:
return cls
def __delitem__(self, key: Any... | ImmutableDictBase |
python | openai__openai-python | src/openai/lib/streaming/chat/_events.py | {
"start": 1800,
"end": 1935
} | class ____(BaseModel):
type: Literal["logprobs.content.done"]
content: List[ChatCompletionTokenLogprob]
| LogprobsContentDoneEvent |
python | django__django | tests/schema/test_logging.py | {
"start": 68,
"end": 740
} | class ____(TestCase):
def test_extra_args(self):
editor = connection.schema_editor(collect_sql=True)
sql = "SELECT * FROM foo WHERE id in (%s, %s)"
params = [42, 1337]
with self.assertLogs("django.db.backends.schema", "DEBUG") as cm:
editor.execute(sql, params)
if... | SchemaLoggerTests |
python | dagster-io__dagster | python_modules/libraries/dagster-gcp/dagster_gcp/gcs/file_manager.py | {
"start": 285,
"end": 1034
} | class ____(FileHandle):
"""A reference to a file on GCS."""
def __init__(self, gcs_bucket: str, gcs_key: str):
self._gcs_bucket = check.str_param(gcs_bucket, "gcs_bucket")
self._gcs_key = check.str_param(gcs_key, "gcs_key")
@property
def gcs_bucket(self) -> str:
"""str: The nam... | GCSFileHandle |
python | scrapy__scrapy | scrapy/utils/curl.py | {
"start": 316,
"end": 679
} | class ____(argparse.Action):
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: str | Sequence[Any] | None,
option_string: str | None = None,
) -> None:
value = str(values)
value = value.removeprefix("$")
se... | DataAction |
python | pandas-dev__pandas | pandas/tests/test_nanops.py | {
"start": 3633,
"end": 27464
} | class ____:
def setup_method(self):
nanops._USE_BOTTLENECK = False
arr_shape = (11, 7)
self.arr_float = np.random.default_rng(2).standard_normal(arr_shape)
self.arr_float1 = np.random.default_rng(2).standard_normal(arr_shape)
self.arr_complex = self.arr_float + self.arr_flo... | TestnanopsDataFrame |
python | aimacode__aima-python | knowledge.py | {
"start": 6738,
"end": 13291
} | class ____(FolKB):
"""Hold the kb and other necessary elements required by FOIL."""
def __init__(self, clauses=None):
self.const_syms = set()
self.pred_syms = set()
super().__init__(clauses)
def tell(self, sentence):
if is_definite_clause(sentence):
self.clauses... | FOILContainer |
python | PrefectHQ__prefect | tests/server/models/test_orm.py | {
"start": 2559,
"end": 2820
} | class ____:
async def test_repr(self, db, session, flow):
assert repr(flow) == f"Flow(id={flow.id})"
assert repr(db.Flow()) == "Flow(id=None)"
flow_id = uuid4()
assert repr(db.Flow(id=flow_id)) == f"Flow(id={flow_id})"
| TestBase |
python | apache__airflow | airflow-core/src/airflow/cli/commands/info_command.py | {
"start": 1785,
"end": 1986
} | class ____(Anonymizer):
"""Do nothing."""
def _identity(self, value) -> str:
return value
process_path = process_username = process_url = _identity
del _identity
| NullAnonymizer |
python | apache__airflow | providers/databricks/tests/unit/databricks/hooks/test_databricks.py | {
"start": 86000,
"end": 87645
} | class ____:
"""
Tests for DatabricksHook using async methods when auth is done with Service
Principal Oauth token.
"""
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id=D... | TestDatabricksHookAsyncSpToken |
python | sympy__sympy | sympy/physics/quantum/grover.py | {
"start": 6055,
"end": 10452
} | class ____(Gate):
"""General n qubit W Gate in Grover's algorithm.
The gate performs the operation ``2|phi><phi| - 1`` on some qubits.
``|phi> = (tensor product of n Hadamards)*(|0> with n qubits)``
Parameters
==========
nqubits : int
The number of qubits to operate on
"""
g... | WGate |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_gridlines05.py | {
"start": 315,
"end": 1664
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_gridlines05.xlsx")
def test_create_file(self):
"""Test XlsxWriter gridlines."""
workbook = Workbook(self.got_filename)
... | TestCompareXLSXFiles |
python | pandas-dev__pandas | pandas/tests/scalar/timestamp/test_arithmetic.py | {
"start": 10855,
"end": 11286
} | class ____(datetime):
pass
@pytest.mark.parametrize(
"lh,rh",
[
(SubDatetime(2000, 1, 1), Timedelta(hours=1)),
(Timedelta(hours=1), SubDatetime(2000, 1, 1)),
],
)
def test_dt_subclass_add_timedelta(lh, rh):
# GH#25851
# ensure that subclassed datetime works for
# Timedelta ... | SubDatetime |
python | py-pdf__pypdf | pypdf/constants.py | {
"start": 20643,
"end": 22239
} | class ____(IntFlag):
NONE = 0
XOBJECT_IMAGES = auto()
INLINE_IMAGES = auto()
DRAWING_IMAGES = auto()
ALL = XOBJECT_IMAGES | INLINE_IMAGES | DRAWING_IMAGES
IMAGES = ALL # for consistency with ObjectDeletionFlag
_INLINE_IMAGE_VALUE_MAPPING = {
"/G": "/DeviceGray",
"/RGB": "/DeviceRGB",
... | ImageType |
python | tornadoweb__tornado | tornado/test/httpclient_test.py | {
"start": 2691,
"end": 3033
} | class ____(RequestHandler):
def get(self):
self.set_status(304)
self.set_header("Content-Length", 42)
def _clear_representation_headers(self):
# Tornado strips content-length from 304 responses, but here we
# want to simulate servers that include the headers anyway.
pass... | ContentLength304Handler |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF008.py | {
"start": 835,
"end": 1147
} | class ____:
mutable_default: 'list[int]' = []
immutable_annotation: 'typing.Sequence[int]' = []
without_annotation = []
correct_code: 'list[int]' = KNOWINGLY_MUTABLE_DEFAULT
perfectly_fine: 'list[int]' = field(default_factory=list)
class_variable: 'typing.ClassVar[list[int]]'= []
| AWithQuotes |
python | realpython__materials | python-built-in-functions/point_v2.py | {
"start": 0,
"end": 507
} | class ____:
def __init__(self, x, y):
self.x = x
self.y = y
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = self.validate(value)
@property
def y(self):
return self._y
@y.setter
def y(self, value):
self.... | Point |
python | huggingface__transformers | src/transformers/models/gemma3n/modeling_gemma3n.py | {
"start": 74868,
"end": 75862
} | class ____(PreTrainedModel):
config: Gemma3nConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Gemma3nTextDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = ... | Gemma3nPreTrainedModel |
python | doocs__leetcode | solution/1200-1299/1272.Remove Interval/Solution.py | {
"start": 0,
"end": 441
} | class ____:
def removeInterval(
self, intervals: List[List[int]], toBeRemoved: List[int]
) -> List[List[int]]:
x, y = toBeRemoved
ans = []
for a, b in intervals:
if a >= y or b <= x:
ans.append([a, b])
else:
if a < x:
... | Solution |
python | google__pytype | pytype/tests/test_errors2.py | {
"start": 20636,
"end": 22551
} | class ____(test_base.BaseTest):
"""Test for name errors on the attributes of partially defined classes.
For code like:
class C:
x = 0
class D:
print(x) # name error!
unlike the similar examples in ClassAttributeNameErrorTest, using 'C.x' does
not work because 'C' has not yet been fully... | PartiallyDefinedClassNameErrorTest |
python | getsentry__sentry | src/sentry/deletions/models/scheduleddeletion.py | {
"start": 5709,
"end": 6509
} | class ____(BaseScheduledDeletion):
"""
This model schedules deletions to be processed in region and monolith silo modes. As new region silo test coverage
increases, new scheduled deletions will begin to occur in this table. Monolith (current saas) will continue
processing them alongside the original s... | RegionScheduledDeletion |
python | getsentry__sentry | tests/sentry/tasks/test_web_vitals_issue_detection.py | {
"start": 508,
"end": 26367
} | class ____(TestCase, SnubaTestCase, SpanTestCase):
def setUp(self):
super().setUp()
self.ten_mins_ago = before_now(minutes=10)
@contextmanager
def mock_seer_ack(self):
with (
patch(
"sentry.tasks.web_vitals_issue_detection.get_seer_org_acknowledgement"
... | WebVitalsIssueDetectionDataTest |
python | eth-brownie__brownie | brownie/network/rpc/__init__.py | {
"start": 1194,
"end": 8598
} | class ____(metaclass=_Singleton):
def __init__(self) -> None:
self.process: Union[psutil.Popen, psutil.Process] = None
self.backend: Any = ganache
atexit.register(self._at_exit)
def _at_exit(self) -> None:
if not self.is_active():
return
if self.process.paren... | Rpc |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 56999,
"end": 57354
} | class ____(BaseModel):
usage: Optional["Usage"] = Field(default=None, description="")
time: Optional[float] = Field(default=None, description="Time spent to process this request")
status: Optional[str] = Field(default=None, description="")
result: Optional[List[List["ScoredPoint"]]] = Field(default=None... | InlineResponse20017 |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 26210,
"end": 26802
} | class ____(PrefectBaseModel):
"""Filter by `WorkQueue.name`."""
any_: Optional[List[str]] = Field(
default=None,
description="A list of work queue names to include",
examples=[["wq-1", "wq-2"]],
)
startswith_: Optional[List[str]] = Field(
default=None,
descripti... | WorkQueueFilterName |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 69902,
"end": 70181
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("direction",)
direction = sgqlc.types.Field(
sgqlc.types.non_null(OrderDirection), graphql_name="direction"
)
| ContributionOrder |
python | Farama-Foundation__Gymnasium | gymnasium/envs/classic_control/cartpole.py | {
"start": 491,
"end": 13958
} | class ____(gym.Env[np.ndarray, Union[int, np.ndarray]]):
"""
## Description
This environment corresponds to the version of the cart-pole problem described by Barto, Sutton, and Anderson in
["Neuronlike Adaptive Elements That Can Solve Difficult Learning Control Problem"](https://ieeexplore.ieee.org/doc... | CartPoleEnv |
python | pola-rs__polars | py-polars/src/polars/io/partition.py | {
"start": 17067,
"end": 17495
} | class ____:
"""
Holds sink options that are generic over file / target type.
For internal use. Most of the options will parse into `UnifiedSinkArgs`.
"""
mkdir: bool
maintain_order: bool
sync_on_close: SyncOnCloseMethod | None = None
# Cloud
storage_options: list[tuple[str, str]] ... | _SinkOptions |
python | pyca__cryptography | src/cryptography/hazmat/primitives/serialization/ssh.py | {
"start": 38374,
"end": 53700
} | class ____:
def __init__(
self,
_public_key: SSHCertPublicKeyTypes | None = None,
_serial: int | None = None,
_type: SSHCertificateType | None = None,
_key_id: bytes | None = None,
_valid_principals: list[bytes] = [],
_valid_for_all_principals: bool = False,
... | SSHCertificateBuilder |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/stateful.py | {
"start": 23344,
"end": 25950
} | class ____(SearchStrategy[Ex]):
"""A collection of values for use in stateful testing.
Bundles are a kind of strategy where values can be added by rules,
and (like any strategy) used as inputs to future rules.
The ``name`` argument they are passed is the they are referred to
internally by the stat... | Bundle |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_numerictypes.py | {
"start": 4638,
"end": 5779
} | class ____(TestCase):
# gh-9799
numeric_types = [
np.byte,
np.short,
np.intc,
np.int_, # , np.longlong, NB: torch does not properly have longlong
np.ubyte,
np.half,
np.single,
np.double,
np.csingle,
np.cdouble,
]
def test... | TestScalarTypeNames |
python | kamyu104__LeetCode-Solutions | Python/lexicographically-smallest-string-after-substring-operation.py | {
"start": 38,
"end": 505
} | class ____(object):
def smallestString(self, s):
"""
:type s: str
:rtype: str
"""
result = list(s)
i = next((i for i in xrange(len(s)) if s[i] != 'a'), len(s))
if i == len(s):
result[-1] = 'z'
else:
for i in xrange(i, len(s)):
... | Solution |
python | getsentry__sentry | src/sentry/hybridcloud/models/outbox.py | {
"start": 19781,
"end": 20894
} | class ____(threading.local):
flushing_enabled: bool | None = None
_outbox_context = OutboxContext()
@contextlib.contextmanager
def outbox_context(
inner: Atomic | None = None, flush: bool | None = None
) -> Generator[Atomic | None]:
# If we don't specify our flush, use the outer specified override
i... | OutboxContext |
python | tiangolo__fastapi | docs_src/security/tutorial002_py310.py | {
"start": 193,
"end": 711
} | class ____(BaseModel):
username: str
email: str | None = None
full_name: str | None = None
disabled: bool | None = None
def fake_decode_token(token):
return User(
username=token + "fakedecoded", email="john@example.com", full_name="John Doe"
)
async def get_current_user(token: str = ... | User |
python | kamyu104__LeetCode-Solutions | Python/isomorphic-strings.py | {
"start": 86,
"end": 607
} | class ____(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
s2t, t2s = {}, {}
for p, w in izip(s, t):
if w not in s2t and p not in t2s:
s2t[... | Solution |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 92846,
"end": 94406
} | class ____(BiffRecord):
"""
In BIFF8 the record stores a list with indexes to SUPBOOK
records (list of REF structures, 6.100). See 5.10.3 for
details about external references in BIFF8.
Record EXTERNSHEET, BIFF8:
Offset Size Contents
0 2 Number of followi... | ExternSheetRecord |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 14218,
"end": 14519
} | class ____(_VectorizerConfigCreate):
vectorizer: Union[Vectorizers, _EnumLikeStr] = Field(
default=Vectorizers.TEXT2VEC_NVIDIA, frozen=True, exclude=True
)
model: Optional[str]
baseURL: Optional[str]
truncate: Optional[bool]
vectorizeClassName: bool
| _Text2VecNvidiaConfig |
python | getsentry__sentry | src/sentry/relay/config/experimental.py | {
"start": 1261,
"end": 3006
} | class ____(Protocol):
def __call__(self, timeout: TimeChecker, *args, **kwargs) -> Any:
pass
#: Timeout for an experimental feature build.
_FEATURE_BUILD_TIMEOUT = timedelta(seconds=20)
def add_experimental_config(
config: MutableMapping[str, Any],
key: str,
function: ExperimentalConfigBuild... | ExperimentalConfigBuilder |
python | Lightning-AI__lightning | src/lightning/pytorch/callbacks/model_summary.py | {
"start": 1309,
"end": 4052
} | class ____(Callback):
r"""Generates a summary of all layers in a :class:`~lightning.pytorch.core.LightningModule`.
Args:
max_depth: The maximum depth of layer nesting that the summary will include. A value of 0 turns the
layer summary off.
**summarize_kwargs: Additional arguments to... | ModelSummary |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_length.py | {
"start": 390,
"end": 561
} | class ____:
def __len__(self):
return -42 # [invalid-length-return]
# TODO: Once Ruff has better type checking
def return_int():
return "3"
| LengthNegative |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 19457,
"end": 25011
} | class ____(testing.AssertsCompiledSQL):
def _assert_collection_integrity(self, coll):
eq_(coll._colset, {c for k, c, _ in coll._collection})
d = {}
for k, col, _ in coll._collection:
d.setdefault(k, (k, col))
d.update(
{idx: (k, col) for idx, (k, col, _) in en... | ColumnCollectionCommon |
python | django__django | django/contrib/gis/forms/fields.py | {
"start": 4472,
"end": 4535
} | class ____(GeometryField):
geom_type = "POLYGON"
| PolygonField |
python | apache__airflow | providers/celery/src/airflow/providers/celery/executors/celery_executor_utils.py | {
"start": 11692,
"end": 16257
} | class ____(LoggingMixin):
"""
Gets status for many Celery tasks using the best method available.
If BaseKeyValueStoreBackend is used as result backend, the mget method is used.
If DatabaseBackend is used as result backend, the SELECT ...WHERE task_id IN (...) query is used
Otherwise, multiprocessin... | BulkStateFetcher |
python | pandas-dev__pandas | pandas/tests/indexes/base_class/test_constructors.py | {
"start": 147,
"end": 2397
} | class ____:
# Tests for the Index constructor, specifically for cases that do
# not return a subclass
@pytest.mark.parametrize("value", [1, np.int64(1)])
def test_constructor_corner(self, value):
# corner case
msg = (
r"Index\(\.\.\.\) must be called with a collection of so... | TestIndexConstructor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictClosed3.py | {
"start": 2703,
"end": 2839
} | class ____(TypedDict, extra_items=str):
pass
# This should generate an error because added fields
# cannot be ReadOnly.
| ParentNonOpen7 |
python | mlflow__mlflow | mlflow/utils/search_logged_model_utils.py | {
"start": 860,
"end": 2076
} | class ____:
type: EntityType
key: str
IDENTIFIER_RE = re.compile(r"^([a-z]+)\.(.+)$")
def __repr__(self) -> str:
return f"{self.type.value}.{self.key}"
@classmethod
def from_str(cls, s: str) -> "Entity":
if m := Entity.IDENTIFIER_RE.match(s):
return cls(
... | Entity |
python | EpistasisLab__tpot | tpot/search_spaces/pipelines/wrapper.py | {
"start": 1758,
"end": 5024
} | class ____(SklearnIndividual):
def __init__(
self,
method: type,
space: ConfigurationSpace,
estimator_search_space: SearchSpace,
hyperparameter_parser: callable = None,
wrapped_param_name: str = None,
rng=None) -> None:
s... | WrapperPipelineIndividual |
python | graphql-python__graphene | examples/complex_example.py | {
"start": 290,
"end": 478
} | class ____(graphene.ObjectType):
address = graphene.Field(Address, geo=GeoInput(required=True))
def resolve_address(root, info, geo):
return Address(latlng=geo.latlng)
| Query |
python | kamyu104__LeetCode-Solutions | Python/finding-3-digit-even-numbers.py | {
"start": 901,
"end": 1446
} | class ____(object):
def findEvenNumbers(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
result, cnt = [], collections.Counter(digits)
for i in xrange(1, 10):
for j in xrange(10):
for k in xrange(0, 10, 2):
... | Solution2 |
python | doocs__leetcode | solution/1500-1599/1545.Find Kth Bit in Nth Binary String/Solution.py | {
"start": 0,
"end": 375
} | class ____:
def findKthBit(self, n: int, k: int) -> str:
def dfs(n: int, k: int) -> int:
if k == 1:
return 0
if (k & (k - 1)) == 0:
return 1
m = 1 << n
if k * 2 < m - 1:
return dfs(n - 1, k)
return df... | Solution |
python | pytorch__pytorch | test/onnx/test_op_consistency.py | {
"start": 10573,
"end": 13374
} | class ____(onnx_test_common._TestONNXRuntime):
"""Test output consistency between exported ONNX models and PyTorch eager mode.
This is a parameterized test suite.
"""
opset_version = -1
@common_device_type.ops(
[op for op in OPS_DB if op.name in TESTED_OPS],
allowed_dtypes=onnx_te... | TestOnnxModelOutputConsistency |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_training.py | {
"start": 8616,
"end": 10913
} | class ____(FSDPTestMultiThread):
@property
def world_size(self) -> int:
return 2
@skip_if_lt_x_gpu(1)
@wrapSwapTensorsTest(True)
def test_to_float64_after_init(self):
"""Tests that the user can cast the module to float64 after init."""
# NOTE: Test fp64 instead of a lower pr... | TestFullyShardCastAfterInit |
python | numpy__numpy | numpy/testing/tests/test_utils.py | {
"start": 16307,
"end": 25777
} | class ____(_GenericTest):
def _assert_func(self, *args, **kwargs):
assert_array_almost_equal(*args, **kwargs)
def test_closeness(self):
# Note that in the course of time we ended up with
# `abs(x - y) < 1.5 * 10**(-decimal)`
# instead of the previously documented
# ... | TestArrayAlmostEqual |
python | google__pytype | pytype/file_utils_test.py | {
"start": 3143,
"end": 3897
} | class ____(unittest.TestCase):
"""Tests for file_utils.expand_path(s?)."""
def test_expand_one_path(self):
full_path = path_utils.join(path_utils.getcwd(), "foo.py")
self.assertEqual(file_utils.expand_path("foo.py"), full_path)
def test_expand_two_paths(self):
full_path1 = path_utils.join(path_utils... | TestPathExpansion |
python | hynek__structlog | tests/processors/test_renderers.py | {
"start": 10666,
"end": 14688
} | class ____:
def test_disallows_non_utc_unix_timestamps(self):
"""
A asking for a UNIX timestamp with a timezone that's not UTC raises a
ValueError.
"""
with pytest.raises(ValueError, match="UNIX timestamps are always UTC"):
TimeStamper(utc=False)
def test_ins... | TestTimeStamper |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1596904,
"end": 1597099
} | class ____(VegaLiteSchema):
"""WindowOnlyOp schema wrapper."""
_schema = {"$ref": "#/definitions/WindowOnlyOp"}
def __init__(self, *args):
super().__init__(*args)
| WindowOnlyOp |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/file_asset.py | {
"start": 1730,
"end": 2062
} | class ____(ValueError):
def __init__(self, unknown_groups: set[str]):
message = (
"Regex has the following group(s) which do not match "
f"batch parameters: {', '.join(unknown_groups)}"
)
super().__init__(message)
self.unknown_groups = unknown_groups
| RegexUnknownGroupsError |
python | huggingface__transformers | src/transformers/models/evolla/modeling_evolla.py | {
"start": 7954,
"end": 10803
} | class ____(nn.Module):
"""
Rotary position embeddings based on those in
[RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer). Query and keys are transformed by rotation
matrices which depend on their relative positions.
"""
inv_freq: torch.Tensor # fix linting for `register_... | EvollaSaProtRotaryEmbedding |
python | pytorch__pytorch | torch/_inductor/autoheuristic/autoheuristic_utils.py | {
"start": 186,
"end": 607
} | class ____:
"""
The context, that AutoHeuristic stores, is a list of features. AutoHeuristic needs to know whether a feature is
categorical (i.e., not a continuous variable) to learn a machine learning model.
"""
def __init__(self, name: str, value: Value, is_categorical: bool = False) -> None:
... | AHFeature |
python | sqlalchemy__sqlalchemy | test/sql/test_defaults.py | {
"start": 4132,
"end": 11689
} | class ____(fixtures.TestBase):
def test_bad_arg_signature(self):
ex_msg = (
"ColumnDefault Python function takes zero "
"or one positional arguments"
)
def fn1(x, y):
pass
def fn2(x, y, z=3):
pass
class fn3:
def _... | DefaultObjectTest |
python | python__mypy | mypy/test/testdiff.py | {
"start": 576,
"end": 2510
} | class ____(DataSuite):
files = ["diff.test"]
def run_case(self, testcase: DataDrivenTestCase) -> None:
first_src = "\n".join(testcase.input)
files_dict = dict(testcase.files)
second_src = files_dict["tmp/next.py"]
options = parse_options(first_src, testcase, 1)
if option... | ASTDiffSuite |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 819348,
"end": 857902
} | class ____(VegaLiteSchema):
"""
OverlayMarkDef schema wrapper.
Parameters
----------
align : dict, :class:`Align`, :class:`ExprRef`, Literal['left', 'center', 'right']
The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule).
One of ``"left"``, ``"right"``... | OverlayMarkDef |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.