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 | jmcnamara__XlsxWriter | xlsxwriter/styles.py | {
"start": 329,
"end": 553
} | class ____(Enum):
"""
Enum to distinguish the type of cell xf format since style and the default
(the first format) are handled slightly differently.
"""
USER = 1
STYLE = 2
DEFAULT = 3
| XFormatType |
python | tornadoweb__tornado | demos/chat/chatdemo.py | {
"start": 2569,
"end": 4112
} | class ____(tornado.web.RequestHandler):
"""Long-polling request for new messages.
Waits until new messages are available before returning anything.
"""
async def post(self):
cursor = self.get_argument("cursor", None)
messages = global_message_buffer.get_messages_since(cursor)
w... | MessageUpdatesHandler |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 28386,
"end": 30655
} | class ____(AttributeSet):
# List from
# https://releases.llvm.org/14.0.0/docs/LangRef.html#parameter-attributes
_known = MappingProxyType({
# True (emit type),
# False (emit name only)
'byref': True,
'byval': True,
'elementtype': True,
'immarg': False,
... | ArgumentAttributes |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip.py | {
"start": 5697,
"end": 7025
} | class ____(ModelOutput):
r"""
itm_score (`torch.FloatTensor`):
The image-text similarity scores.
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss from the text decoder.
image_embeds (`torch.FloatTensor` of shape `(batch_si... | BlipImageTextMatchingModelOutput |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/evaluate_value_result.py | {
"start": 318,
"end": 1390
} | class ____(Generic[T]):
success: bool
value: Optional[T]
errors: Optional[Sequence[EvaluationError]]
@staticmethod
def for_error(error: EvaluationError) -> "EvaluateValueResult[Any]":
return EvaluateValueResult(success=False, value=None, errors=[error])
@staticmethod
def for_errors... | EvaluateValueResult |
python | getsentry__sentry | tests/sentry/relocation/tasks/test_transfer.py | {
"start": 3629,
"end": 5419
} | class ____(TestCase):
@patch("sentry.relocation.tasks.transfer.process_relocation_transfer_region")
def test_no_records(self, mock_process: MagicMock) -> None:
find_relocation_transfer_region()
assert not mock_process.delay.called
@patch("sentry.relocation.tasks.transfer.process_relocation_... | FindRelocationTransferRegionTest |
python | kamyu104__LeetCode-Solutions | Python/next-greater-element-i.py | {
"start": 37,
"end": 494
} | class ____(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
stk, lookup = [], {}
for num in nums:
while stk and num > stk[-1]:
lookup[stk.pop()] = num
... | Solution |
python | walkccc__LeetCode | solutions/2233. Maximum Product After K Increments/2233.py | {
"start": 0,
"end": 358
} | class ____:
def maximumProduct(self, nums: list[int], k: int) -> int:
MOD = 1_000_000_007
ans = 1
minHeap = nums.copy()
heapq.heapify(minHeap)
for _ in range(k):
minNum = heapq.heappop(minHeap)
heapq.heappush(minHeap, minNum + 1)
while minHeap:
ans *= heapq.heappop(minHeap)... | Solution |
python | getsentry__sentry | src/sentry/api/serializers/models/project_transaction_threshold.py | {
"start": 248,
"end": 744
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
return {
"id": str(obj.id),
"threshold": str(obj.threshold),
"metric": TRANSACTION_METRICS[obj.metric],
"projectId": str(obj.project_id),
"editedBy": str(obj.edited_by_id),
... | ProjectTransactionThresholdSerializer |
python | pytorch__pytorch | torch/nn/utils/rnn.py | {
"start": 753,
"end": 23409
} | class ____(PackedSequence_):
r"""Holds the data and list of :attr:`batch_sizes` of a packed sequence.
All RNN modules accept packed sequences as inputs.
Note:
Instances of this class should never be created manually. They are meant
to be instantiated by functions like :func:`pack_padded_se... | PackedSequence |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink04.py | {
"start": 315,
"end": 2424
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Wor... | TestCompareXLSXFiles |
python | Textualize__textual | docs/examples/styles/scrollbar_gutter.py | {
"start": 385,
"end": 595
} | class ____(App):
CSS_PATH = "scrollbar_gutter.tcss"
def compose(self):
yield Static(TEXT, id="text-box")
if __name__ == "__main__":
app = ScrollbarGutterApp()
app.run()
| ScrollbarGutterApp |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 27825,
"end": 30025
} | class ____(APITestCase):
@cached_property
def path_2fa(self):
return reverse("sentry-account-settings-security")
def enable_org_2fa(self, organization):
organization.flags.require_2fa = True
organization.save()
def api_enable_org_2fa(self, organization, user):
self.logi... | TwoFactorAPITestCase |
python | tensorflow__tensorflow | tensorflow/python/ops/math_grad_test.py | {
"start": 6437,
"end": 8458
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testProdGradient(self):
inputs = constant_op.constant([[1., 2.], [3., 4.]],
dtype=dtypes.float32)
outputs = math_ops.reduce_prod(inputs)
with self.cached_session():
error = gradient_checker.compute_gradi... | ProdGradientTest |
python | nryoung__algorithms | tests/test_sorting.py | {
"start": 778,
"end": 1027
} | class ____(SortingAlgorithmTestCase):
"""
Tests Bubble sort on a small range from 0-9
"""
def test_bubblesort(self):
self.output = bubble_sort.sort(self.input)
self.assertEqual(self.correct, self.output)
| TestBubbleSort |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_outline05.py | {
"start": 315,
"end": 3105
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("outline05.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.re... | TestCompareXLSXFiles |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 7099,
"end": 7798
} | class ____(StringIORewind):
params = [None, "custom", "iso8601", "ymd"]
param_names = ["format"]
def setup(self, format):
rng = date_range("1/1/2000", periods=1000)
formats = {
None: None,
"custom": "%m/%d/%Y %H:%M:%S.%f",
"iso8601": "%Y-%m-%d %H:%M:%S",
... | ReadCSVDInferDatetimeFormat |
python | xlwings__xlwings | tests/test_shape.py | {
"start": 9670,
"end": 10600
} | class ____(TestBase):
def test_add_properties(self):
sht = self.wb1.sheets[0]
sht.range("A1").value = [["one", "two"], [1.1, 2.2]]
self.assertEqual(len(sht.charts), 0)
chart = sht.charts.add()
self.assertEqual(len(sht.charts), 1)
chart.name = "My Chart"
char... | TestCharts |
python | apache__airflow | providers/openlineage/tests/unit/openlineage/extractors/test_base.py | {
"start": 2081,
"end": 2167
} | class ____(JobFacet):
finished: bool = field(default=False)
@define
| CompleteRunFacet |
python | pypa__warehouse | tests/unit/oidc/models/test_activestate.py | {
"start": 1748,
"end": 12803
} | class ____:
def test_publisher_name(self):
publisher = ActiveStatePublisher()
assert publisher.publisher_name == "ActiveState"
def test_publisher_base_url(self):
org_name = "fakeorg"
project_name = "fakeproject"
publisher = ActiveStatePublisher(
organization... | TestActiveStatePublisher |
python | ethereum__web3.py | ens/exceptions.py | {
"start": 1645,
"end": 1745
} | class ____(ENSException):
"""
Raised if you bid less than the minimum amount
"""
| BidTooLow |
python | sympy__sympy | sympy/parsing/latex/lark/transformer.py | {
"start": 467,
"end": 25754
} | class ____(Transformer):
"""Returns a SymPy expression that is generated by traversing the ``lark.Tree``
passed to the ``.transform()`` function.
Notes
=====
**This class is never supposed to be used directly.**
In order to tweak the behavior of this class, it has to be subclassed and then af... | TransformToSymPyExpr |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 21963,
"end": 22165
} | class ____(InetTestBase):
"""Base class for UDPLITE-over-IPv4 tests."""
def newSocket(self):
return socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE)
| UDPLITETestBase |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 2058,
"end": 2335
} | class ____(Message):
message = 'syntax error in doctest'
def __init__(self, filename, loc, position=None):
Message.__init__(self, filename, loc)
if position:
(self.lineno, self.col) = position
self.message_args = ()
| DoctestSyntaxError |
python | django__django | tests/admin_filters/tests.py | {
"start": 6540,
"end": 6840
} | class ____(ModelAdmin):
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
list_filter = ("year",)
def get_queryset(self, request):
return super().get_queryset(request).filter(author=self.user)
| BookAdminWithCustomQueryset |
python | tiangolo__fastapi | docs_src/cookie_param_models/tutorial002_an_py310.py | {
"start": 116,
"end": 383
} | class ____(BaseModel):
model_config = {"extra": "forbid"}
session_id: str
fatebook_tracker: str | None = None
googall_tracker: str | None = None
@app.get("/items/")
async def read_items(cookies: Annotated[Cookies, Cookie()]):
return cookies
| Cookies |
python | astropy__astropy | astropy/cosmology/_src/flrw/base.py | {
"start": 43290,
"end": 46477
} | class ____(FlatCosmologyMixin):
"""Mixin class for flat FLRW cosmologies.
Do NOT instantiate directly. Must precede the base class in the
multiple-inheritance so that this mixin's ``__init__`` proceeds the
base class'. Note that all instances of ``FlatFLRWMixin`` are flat, but
not all flat cosmolog... | FlatFLRWMixin |
python | encode__django-rest-framework | rest_framework/permissions.py | {
"start": 3586,
"end": 3882
} | class ____(BasePermission):
"""
Allow any access.
This isn't strictly required, since you could use an empty
permission_classes list, but it's useful because it makes the intention
more explicit.
"""
def has_permission(self, request, view):
return True
| AllowAny |
python | pydata__xarray | asv_bench/benchmarks/coding.py | {
"start": 126,
"end": 520
} | class ____:
def setup(self, calendar):
self.units = "days since 2000-01-01"
self.dtype = np.dtype("int64")
self.times = xr.date_range(
"2000", freq="D", periods=10000, calendar=calendar
).values
def time_encode_cf_datetime(self, calendar):
xr.coding.times.enc... | EncodeCFDatetime |
python | gevent__gevent | src/greentest/3.11/test_subprocess.py | {
"start": 71246,
"end": 80531
} | class ____(BaseTestCase):
def run_python(self, code, **kwargs):
"""Run Python code in a subprocess using subprocess.run"""
argv = [sys.executable, "-c", code]
return subprocess.run(argv, **kwargs)
def test_returncode(self):
# call() function with sequence argument
cp = s... | RunFuncTestCase |
python | viewflow__viewflow | viewflow/workflow/fields.py | {
"start": 4698,
"end": 5144
} | class ____(models.CharField):
def __init__(self, *args, **kwargs):
kwargs.setdefault("max_length", 150)
super(TokenField, self).__init__(*args, **kwargs)
def from_db_value(self, value, expression, connection):
if value is None:
return value
return Token(value)
d... | TokenField |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_to_be_line_miles_distance_between.py | {
"start": 2130,
"end": 6841
} | class ____(ColumnMapExpectation):
"""Expect the distance of each Linestring in the column to be between two values in miles."""
# These examples will be shown in the public gallery, and also executed as unit tests for your Expectation
examples = [
{
"data": {
"linestring... | ExpectColumnValuesToBeLineMilesDistanceBetween |
python | django__django | tests/admin_widgets/test_autocomplete_widget.py | {
"start": 1020,
"end": 1267
} | class ____(forms.Form):
band = ModelChoiceField(
queryset=Album.objects.all(),
widget=AutocompleteSelect(
Album._meta.get_field("band").remote_field, admin.site
),
required=True,
)
| RequiredBandForm |
python | google__pytype | pytype/preprocess.py | {
"start": 94,
"end": 1281
} | class ____(ast.NodeVisitor):
"""Collect line numbers of annotations to augment."""
def __init__(self):
self.annotation_lines = []
self.in_function = False
def visit_AnnAssign(self, node):
if self.in_function and node.value is None:
self.annotation_lines.append(node.end_lineno - 1) # change to... | CollectAnnotationLines |
python | PyCQA__pylint | tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.py | {
"start": 8254,
"end": 8516
} | class ____:
"""test_finds_property_return_type_sphinx
Example of a property having return documentation in
a Sphinx style docstring
"""
@property
def foo(self):
"""docstring ...
:type: int
"""
return 10
| Foo |
python | cherrypy__cherrypy | cherrypy/lib/gctools.py | {
"start": 4778,
"end": 8551
} | class ____(object):
"""A CherryPy page handler for testing reference leaks."""
classes = [
(
_cprequest.Request,
2,
2,
'Should be 1 in this request thread and 1 in the main thread.',
),
(
_cprequest.Response,
2,
... | GCRoot |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-valid-strings-to-form-target-i.py | {
"start": 3786,
"end": 5174
} | class ____(object):
def minValidStrings(self, words, target):
"""
:type words: List[str]
:type target: str
:rtype: int
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
w... | Solution3 |
python | plotly__plotly.py | plotly/graph_objs/scattermap/marker/colorbar/_title.py | {
"start": 233,
"end": 4042
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattermap.marker.colorbar"
_path_str = "scattermap.marker.colorbar.title"
_valid_props = {"font", "side", "text"}
@property
def font(self):
"""
Sets this color bar's title font.
The 'font' property is an instance of ... | Title |
python | huggingface__transformers | tests/models/modernbert/test_modeling_modernbert.py | {
"start": 22372,
"end": 29266
} | class ____(unittest.TestCase):
@slow
def test_inference_masked_lm(self):
if version.parse(torch.__version__) < version.parse("2.4.0"):
self.skipTest(reason="This test requires torch >= 2.4 to run.")
model = ModernBertForMaskedLM.from_pretrained(
"answerdotai/ModernBERT-b... | ModernBertModelIntegrationTest |
python | kamyu104__LeetCode-Solutions | Python/last-day-where-you-can-still-cross.py | {
"start": 865,
"end": 1937
} | class ____(object):
def latestDayToCross(self, row, col, cells):
"""
:type row: int
:type col: int
:type cells: List[List[int]]
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def index(n, i, j):
return i*n+j
start,... | Solution |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/masked_select.py | {
"start": 160,
"end": 2670
} | class ____(Operator):
"""Operator for selecting elements from a tensor based on a mask."""
def __init__(self):
super().__init__("masked_select")
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "torch.masked_select"
def can_pro... | MaskedSelectOperator |
python | allegroai__clearml | clearml/automation/auto_scaler.py | {
"start": 1361,
"end": 1489
} | class ____(str, Enum):
STARTING = "starting"
READY = "ready"
RUNNING = "running"
STOPPED = "stopped"
@attr.s
| State |
python | ray-project__ray | rllib/core/models/catalog.py | {
"start": 1071,
"end": 27260
} | class ____:
"""Describes the sub-module-architectures to be used in RLModules.
RLlib's native RLModules get their Models from a Catalog object.
By default, that Catalog builds the configs it has as attributes.
This component was build to be hackable and extensible. You can inject custom
components ... | Catalog |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core/config.py | {
"start": 6812,
"end": 9315
} | class ____:
cli: "DgCliConfig"
project: Optional["DgProjectConfig"] = None
workspace: Optional["DgWorkspaceConfig"] = None
@classmethod
def default(cls) -> Self:
return cls(DgCliConfig.default())
# Note that this function takes an argument called `container_workspace_file_config` inste... | DgConfig |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-commcare/source_commcare/source.py | {
"start": 4609,
"end": 7778
} | class ____(IncrementalStream):
"""
docs: https://www.commcarehq.org/a/[domain]/api/[version]/case/
"""
cursor_field = "indexed_on"
primary_key = "id"
def __init__(self, start_date, app_id, schema, **kwargs):
super().__init__(**kwargs)
self._cursor_value = datetime.strptime(star... | Case |
python | coleifer__peewee | tests/db_tests.py | {
"start": 33002,
"end": 33406
} | class ____(ModelTestCase):
database = get_in_memory_db()
requires = [User]
def test_exception_wrapper(self):
exc = None
try:
User.create(username=None)
except IntegrityError as e:
exc = e
if exc is None: raise Exception('expected integrity error not ... | TestExceptionWrapper |
python | django__django | tests/null_fk_ordering/models.py | {
"start": 288,
"end": 362
} | class ____(models.Model):
name = models.CharField(max_length=150)
| Author |
python | openai__openai-python | src/openai/types/responses/response_mcp_call_in_progress_event.py | {
"start": 207,
"end": 638
} | class ____(BaseModel):
item_id: str
"""The unique identifier of the MCP tool call item being processed."""
output_index: int
"""The index of the output item in the response's output array."""
sequence_number: int
"""The sequence number of this event."""
type: Literal["response.mcp_call.in... | ResponseMcpCallInProgressEvent |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/metrics_test.py | {
"start": 169487,
"end": 171485
} | class ____(test.TestCase):
def setUp(self):
np.random.seed(1)
ops.reset_default_graph()
@test_util.run_deprecated_v1
def testVars(self):
metrics.false_positives(
labels=(0, 1, 0, 1),
predictions=(0, 0, 1, 1))
_assert_metric_variables(self, ('false_positives/count:0',))
@test_u... | FalsePositivesTest |
python | spyder-ide__spyder | spyder/plugins/debugger/widgets/framesbrowser.py | {
"start": 1024,
"end": 1144
} | class ____:
Debug = 'debug'
DebugWait = 'debugwait'
Inspect = 'inspect'
Error = 'error'
| FramesBrowserState |
python | numba__numba | numba/tests/test_listobject.py | {
"start": 36699,
"end": 38574
} | class ____(MemoryLeakMixin, TestCase):
"""Test list equal and not equal. """
def test_list_empty_equal(self):
@njit
def foo():
t = listobject.new_list(int32)
o = listobject.new_list(int32)
return t == o, t != o
self.assertEqual(foo(), (True, False))
... | TestEqualNotEqual |
python | huggingface__transformers | src/transformers/models/zamba2/modeling_zamba2.py | {
"start": 49862,
"end": 53359
} | class ____(nn.Module):
def __init__(self, config: Zamba2Config, block_id: Optional[int] = None, layer_idx: Optional[int] = None):
super().__init__()
self.block_id = block_id
num_gs = len(config.hybrid_layer_ids)
self.self_attn = Zamba2Attention(config, layer_idx=-1, num_fwd_mem_block... | Zamba2AttentionDecoderLayer |
python | Lightning-AI__lightning | tests/tests_pytorch/strategies/test_model_parallel_integration.py | {
"start": 3755,
"end": 4034
} | class ____(TemplateModel):
def configure_model(self):
parallelize = _parallelize_feed_forward_tp
if self._compile:
parallelize = _parallelize_with_compile(parallelize)
parallelize(self.model, device_mesh=self.device_mesh)
| TensorParallelModel |
python | mlflow__mlflow | mlflow/utils/gorilla.py | {
"start": 4837,
"end": 24049
} | class ____:
"""Describe all the information required to apply a patch.
Attributes
----------
destination : obj
Patch destination.
name : str
Name of the attribute at the destination.
obj : obj
Attribute value.
settings : gorilla.Settings or None
Settings. If ... | Patch |
python | ray-project__ray | rllib/evaluation/env_runner_v2.py | {
"start": 4634,
"end": 7313
} | class ____(defaultdict):
def __missing__(self, env_id):
ret = self[env_id] = self.default_factory(env_id)
return ret
@OldAPIStack
def _build_multi_agent_batch(
episode_id: int,
batch_builder: _PolicyCollectorGroup,
large_batch_threshold: int,
multiple_episodes_in_batch: bool,
) -> ... | _NewDefaultDict |
python | kamyu104__LeetCode-Solutions | Python/find-all-duplicates-in-an-array.py | {
"start": 974,
"end": 1193
} | class ____(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return [elem for elem, count in Counter(nums).items() if count == 2]
| Solution3 |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_button06.py | {
"start": 315,
"end": 852
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("button05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_file... | TestCompareXLSXFiles |
python | django__django | django/contrib/gis/geos/error.py | {
"start": 0,
"end": 105
} | class ____(Exception):
"The base GEOS exception, indicates a GEOS-related error."
pass
| GEOSException |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_excel2003_style01.py | {
"start": 315,
"end": 785
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("excel2003_style01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self... | TestCompareXLSXFiles |
python | django__django | tests/generic_views/test_dates.py | {
"start": 531,
"end": 1479
} | class ____:
@classmethod
def setUpTestData(cls):
cls.artist1 = Artist.objects.create(name="Rene Magritte")
cls.author1 = Author.objects.create(
name="Roberto Bolaño", slug="roberto-bolano"
)
cls.author2 = Author.objects.create(
name="Scott Rosenberg", slug... | TestDataMixin |
python | astropy__astropy | astropy/units/tests/test_logarithmic.py | {
"start": 36704,
"end": 36981
} | class ____:
# TODO: add tests for all supported functions!
@log_quantity_parametrization
def test_ptp(self, mag):
res = np.ptp(mag)
assert np.all(res.value == np.ptp(mag._function_view).value)
assert res.unit == u.mag()
| TestLogQuantityFunctions |
python | kamyu104__LeetCode-Solutions | Python/maximum-elegance-of-a-k-length-subsequence.py | {
"start": 3321,
"end": 4106
} | class ____(object):
def findMaximumElegance(self, items, k):
"""
:type items: List[List[int]]
:type k: int
:rtype: int
"""
items.sort(reverse=True)
result = curr = 0
lookup = set()
stk = []
for i in xrange(k):
if items[i][1]... | Solution3 |
python | gevent__gevent | src/greentest/3.14/test_urllib2_localnet.py | {
"start": 15430,
"end": 24739
} | class ____(unittest.TestCase):
"""Tests urllib.request.urlopen using the network.
These tests are not exhaustive. Assuming that testing using files does a
good job overall of some of the basic interface features. There are no
tests exercising the optional 'data' and 'proxies' arguments. No tests
... | TestUrlopen |
python | django__django | tests/migrations/migrations_test_apps/mutate_state_b/migrations/0002_add_field.py | {
"start": 43,
"end": 451
} | class ____(migrations.Migration):
dependencies = [
("mutate_state_b", "0001_initial"),
]
operations = [
migrations.SeparateDatabaseAndState(
[],
[
migrations.AddField(
model_name="B",
name="added",
... | Migration |
python | doocs__leetcode | solution/1900-1999/1910.Remove All Occurrences of a Substring/Solution.py | {
"start": 0,
"end": 156
} | class ____:
def removeOccurrences(self, s: str, part: str) -> str:
while part in s:
s = s.replace(part, '', 1)
return s
| Solution |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/qembedding_bag_lookups_test.py | {
"start": 2127,
"end": 5942
} | class ____(op_bench.TorchBenchmarkBase):
def init(
self,
num_embeddings: int,
embedding_dim: int,
num_offsets: int,
enable_per_sample_weights: bool,
include_last_offset: bool,
is_pruned_weights: bool,
use_32bit_indices: bool,
use_32bit_offsets:... | EmbedddingBag4BitRowwiseOffsetsTest |
python | scipy__scipy | scipy/io/arff/tests/test_arffread.py | {
"start": 1499,
"end": 2866
} | class ____:
def test1(self):
# Parsing trivial file with nothing.
self._test(test4)
def test2(self):
# Parsing trivial file with some comments in the data section.
self._test(test5)
def test3(self):
# Parsing trivial file with nominal attribute of 1 character.
... | TestData |
python | pydantic__pydantic | pydantic-core/tests/validators/test_int.py | {
"start": 18164,
"end": 19265
} | class ____(int):
pass
def test_int_subclass() -> None:
v = SchemaValidator(cs.int_schema())
v_lax = v.validate_python(IntSubclass(1))
assert v_lax == 1
assert type(v_lax) == int
v_strict = v.validate_python(IntSubclass(1), strict=True)
assert v_strict == 1
assert type(v_strict) == int
... | IntSubclass |
python | Netflix__metaflow | metaflow/plugins/events_decorator.py | {
"start": 11145,
"end": 22704
} | class ____(FlowDecorator):
"""
Specifies the flow(s) that this flow depends on.
```
@trigger_on_finish(flow='FooFlow')
```
or
```
@trigger_on_finish(flows=['FooFlow', 'BarFlow'])
```
This decorator respects the @project decorator and triggers the flow
when upstream runs with... | TriggerOnFinishDecorator |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 67424,
"end": 69364
} | class ____(rv_continuous):
r"""An exponentiated Weibull continuous random variable.
%(before_notes)s
See Also
--------
weibull_min, numpy.random.Generator.weibull
Notes
-----
The probability density function for `exponweib` is:
.. math::
f(x, a, c) = a c [1-\exp(-x^c)]^{... | exponweib_gen |
python | pandas-dev__pandas | asv_bench/benchmarks/index_object.py | {
"start": 3193,
"end": 4163
} | class ____:
def setup(self):
N = 10_000
self.range_idx = RangeIndex(0, 100)
self.int_idx = self.range_idx.astype(int)
self.obj_idx = self.int_idx.astype(str)
self.range_idxs = []
self.int_idxs = []
self.object_idxs = []
for i in range(1, N):
... | IndexAppend |
python | pytest-dev__pytest-xdist | testing/acceptance_test.py | {
"start": 45354,
"end": 51545
} | class ____:
def test_by_module(self, pytester: pytest.Pytester) -> None:
test_file = """
import pytest
class TestA:
@pytest.mark.xdist_group(name="xdist_group")
@pytest.mark.parametrize('i', range(5))
def test(self, i):
... | TestGroupScope |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/spec_cache.py | {
"start": 712,
"end": 2282
} | class ____:
docker_repository: str
docker_image_tag: str
spec_cache_path: str
registry: Registries
def __str__(self) -> str:
return self.spec_cache_path
def get_spec_file_name(registry: Registries) -> str:
return SPEC_FILE_NAMES[registry]
def get_registry_from_spec_cache_path(spec_c... | CachedSpec |
python | pytorch__pytorch | torch/distributed/checkpoint/metadata.py | {
"start": 3785,
"end": 4427
} | class ____:
"""This class represents the metadata of the checkpoint."""
# Keys are the same from the `state_dict` used.
state_dict_metadata: dict[str, STORAGE_TYPES]
# It is the responsibility of the planner and storage plugins to ensure
# backward compatibility of the planner_data and storage_data... | Metadata |
python | pytorch__pytorch | torch/fx/graph.py | {
"start": 42002,
"end": 43846
} | class ____(_PyTreeCodeGen):
def __init__(
self,
pytree_info: _PyTreeInfo,
in_shuffle_graph: "GraphModule",
out_shuffle_graph: "GraphModule",
tree_leaf_names: list[str],
root: Optional[torch.nn.Module],
):
super().__init__(pytree_info)
self.in_shuff... | _ExportCodeGen |
python | kamyu104__LeetCode-Solutions | Python/card-flipping-game.py | {
"start": 48,
"end": 488
} | class ____(object):
def flipgame(self, fronts, backs):
"""
:type fronts: List[int]
:type backs: List[int]
:rtype: int
"""
same = {n for i, n in enumerate(fronts) if n == backs[i]}
result = float("inf")
for n in itertools.chain(fronts, backs):
... | Solution |
python | networkx__networkx | networkx/classes/tests/test_graphviews.py | {
"start": 1471,
"end": 2790
} | class ____:
def setup_method(self):
self.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
self.G.add_edge(4, 5)
self.rv = nx.reverse_view(self.G)
def test_pickle(self):
import pickle
rv = self.rv
prv = pickle.loads(pickle.dumps(rv, -1))
assert rv._no... | TestMultiReverseView |
python | getsentry__sentry | tests/sentry/sentry_apps/services/test_hook_service.py | {
"start": 13712,
"end": 22149
} | class ____(TestCase):
def setUp(self) -> None:
self.user = self.create_user()
self.org = self.create_organization(owner=self.user, region="us")
self.project = self.create_project(name="foo", organization=self.org)
self.sentry_app = self.create_sentry_app(
organization_id=... | TestHookServiceBulkCreate |
python | doocs__leetcode | solution/3000-3099/3021.Alice and Bob Playing Flower Game/Solution2.py | {
"start": 0,
"end": 93
} | class ____:
def flowerGame(self, n: int, m: int) -> int:
return (n * m) // 2
| Solution |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 171306,
"end": 173965
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[3, 3, 3]"):
l_x_ = L_x_
y: "f32[3]" = torch.randn(3)
_saved_tensors_hooks_disable = torch._C._autograd._saved_tensors_hooks_disable("torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. Please open an issue ... | GraphModule |
python | huggingface__transformers | src/transformers/models/dinat/modeling_dinat.py | {
"start": 22219,
"end": 22409
} | class ____(PreTrainedModel):
config: DinatConfig
base_model_prefix = "dinat"
main_input_name = "pixel_values"
input_modalities = ("image",)
@auto_docstring
| DinatPreTrainedModel |
python | PrefectHQ__prefect | src/prefect/server/services/base.py | {
"start": 4813,
"end": 11979
} | class ____(Service, abc.ABC):
"""
Loop services are relatively lightweight maintenance routines that need to run
periodically.
This class makes it straightforward to design and integrate them. Users only need to
define the `run_once` coroutine to describe the behavior of the service on each
loo... | LoopService |
python | conda__conda | conda/common/configuration.py | {
"start": 3011,
"end": 3302
} | class ____(ConfigurationError):
def __init__(self, parameter_name, parameter_value, source, msg=None, **kwargs):
self.parameter_name = parameter_name
self.parameter_value = parameter_value
self.source = source
super().__init__(msg, **kwargs)
| ValidationError |
python | pypa__pip | src/pip/_internal/resolution/resolvelib/requirements.py | {
"start": 395,
"end": 1513
} | class ____(Requirement):
def __init__(self, candidate: Candidate) -> None:
self.candidate = candidate
def __str__(self) -> str:
return str(self.candidate)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.candidate!r})"
def __hash__(self) -> int:
retu... | ExplicitRequirement |
python | huggingface__transformers | src/transformers/models/trocr/modeling_trocr.py | {
"start": 28636,
"end": 29046
} | class ____(TrOCRPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.decoder = TrOCRDecoder(config)
def forward(self, *args, **kwargs):
return self.decoder(*args, **kwargs)
@auto_docstring(
custom_intro="""
The TrOCR Decoder with a language modeling head... | TrOCRDecoderWrapper |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/nltk.py | {
"start": 230,
"end": 1973
} | class ____(TextSplitter):
"""Splitting text using NLTK package."""
def __init__(
self,
separator: str = "\n\n",
language: str = "english",
*,
use_span_tokenize: bool = False,
**kwargs: Any,
) -> None:
"""Initialize the NLTK splitter."""
super(... | NLTKTextSplitter |
python | joblib__joblib | joblib/externals/loky/backend/synchronize.py | {
"start": 1654,
"end": 4268
} | class ____:
_rand = tempfile._RandomNameSequence()
def __init__(self, kind, value, maxvalue, name=None):
# unlink_now is only used on win32 or when we are using fork.
unlink_now = False
if name is None:
# Try to find an unused name for the SemLock instance.
for ... | SemLock |
python | bokeh__bokeh | src/bokeh/models/annotations/dimensional.py | {
"start": 4462,
"end": 4762
} | class ____(Metric):
""" Metric units of length measurement.
"""
# explicit __init__ to support Init signatures
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
base_unit = Override(default="m")
exclude = Override(default=["dm", "hm"])
| MetricLength |
python | getsentry__sentry | src/sentry/preprod/analytics.py | {
"start": 2195,
"end": 2468
} | class ____(analytics.Event):
organization_id: int
project_id: int
user_id: int | None = None
head_artifact_id: str
base_artifact_id: str
@analytics.eventclass("preprod_artifact.api.size_analysis_compare.post")
| PreprodArtifactApiSizeAnalysisCompareGetEvent |
python | getlogbook__logbook | src/logbook/queues.py | {
"start": 7979,
"end": 9097
} | class ____:
"""A helper class used by queue subscribers to control the background
thread. This is usually created and started in one go by
:meth:`~logbook.queues.ZeroMQSubscriber.dispatch_in_background` or
a comparable function.
"""
def __init__(self, subscriber, setup=None):
self.setu... | ThreadController |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/mutable.py | {
"start": 3868,
"end": 9443
} | class ____ associates a listener that will detect all future mappings
of this type, applying event listening instrumentation to the mapped
attribute. Such as, with classical table metadata::
from sqlalchemy import Table, Column, Integer
my_data = Table(
"my_data",
metadata,
Column("id"... | and |
python | getsentry__sentry | src/sentry/utils/snuba.py | {
"start": 13678,
"end": 13788
} | class ____(SnubaError):
"""
Exception raised when a query failed to execute.
"""
| QueryExecutionError |
python | pytorch__pytorch | torch/distributed/pipelining/schedules.py | {
"start": 102479,
"end": 107909
} | class ____(_PipelineScheduleRuntime):
"""
The Interleaved 1F1B schedule.
See https://arxiv.org/pdf/2104.04473 for details.
Will perform one forward and one backward on the microbatches in steady
state and supports multiple stages per rank. When microbatches are ready for
multiple local stages, I... | ScheduleInterleaved1F1B |
python | joke2k__faker | faker/providers/passport/ru_RU/__init__.py | {
"start": 412,
"end": 892
} | class ____(BaseProvider):
passport_number_formats: ElementsType = (
"## ## ######",
"#### ######",
)
def passport_owner(self, gender: SexLiteral = "M") -> Tuple[str, str]:
generator_string = GENDER_TO_GENERATOR[gender]
last_name, first_name, middle_name = self.generator.pars... | Provider |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 21893,
"end": 22318
} | class ____(Pix2SkyProjection, Cylindrical):
r"""
Plate carrée projection - pixel to sky.
Corresponds to the ``CAR`` projection in FITS WCS.
.. math::
\phi &= x \\
\theta &= y
"""
@staticmethod
def evaluate(x, y):
# The intermediate variables are only used here for ... | Pix2Sky_PlateCarree |
python | numpy__numpy | tools/swig/test/testVector.py | {
"start": 11428,
"end": 11695
} | class ____(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "ushort"
self.typeCode = "H"
######################################################################
| ushortTestCase |
python | scikit-learn__scikit-learn | sklearn/model_selection/_plot.py | {
"start": 19725,
"end": 34606
} | class ____(_BaseCurveDisplay):
"""Validation Curve visualization.
It is recommended to use
:meth:`~sklearn.model_selection.ValidationCurveDisplay.from_estimator` to
create a :class:`~sklearn.model_selection.ValidationCurveDisplay` instance.
All parameters are stored as attributes.
Read more in... | ValidationCurveDisplay |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/partitions_schedules_sensors/partitioned_config_test.py | {
"start": 1525,
"end": 2663
} | class ____(dg.Config):
start: str
end: str
@op
def process_data(context: dg.OpExecutionContext, config: ProcessDataConfig):
s = config.start
e = config.end
context.log.info(f"processing data for {s} - {e}")
@job(config=my_offset_partitioned_config)
def do_more_stuff_partitioned():
process_da... | ProcessDataConfig |
python | huggingface__transformers | tests/models/gemma2/test_modeling_gemma2.py | {
"start": 1706,
"end": 1907
} | class ____(CausalLMModelTest, unittest.TestCase):
_is_stateful = True
model_split_percents = [0.5, 0.6]
model_tester_class = Gemma2ModelTester
@slow
@require_torch_accelerator
| Gemma2ModelTest |
python | ansible__ansible | test/units/plugins/cache/test_cache.py | {
"start": 4620,
"end": 5454
} | class ____(TestJsonFileCache):
cache_prefix = 'special_'
def test_keys(self):
# For caches with a prefix only files that match the prefix are
# considered. The prefix is removed from the key name.
cache_writer = self.get_cache('')
cache_writer["no_prefix"] = dict(a=1)
ca... | TestJsonFileCachePrefix |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.