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 | huggingface__transformers | src/transformers/models/speech_to_text/tokenization_speech_to_text.py | {
"start": 1319,
"end": 11500
} | class ____(PreTrainedTokenizer):
"""
Construct an Speech2Text tokenizer.
This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to
the superclass for more information regarding such methods.
Args:
vocab_file (`str`):
Fil... | Speech2TextTokenizer |
python | lxml__lxml | src/lxml/tests/test_etree.py | {
"start": 197325,
"end": 201950
} | class ____(HelperTestCase):
def test_write(self):
tree = self.parse(b'<a><b/></a>')
f = BytesIO()
tree.write(f)
s = f.getvalue()
self.assertEqual(b'<a><b/></a>',
s)
def test_write_doctype(self):
tree = self.parse(b'<a><b/></a>')
... | ETreeWriteTestCase |
python | jina-ai__jina | tests/integration/docarray_v2/docker/executor2/executor.py | {
"start": 367,
"end": 1272
} | class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._indexer = InMemoryExactNNIndex[MyDoc]()
@requests(on='/index')
def index(self, docs: DocList[MyDoc], **kwargs) -> DocList[MyDoc]:
self._indexer.index(docs)
return docs
@re... | Indexer |
python | huggingface__transformers | tests/models/llava/test_image_processing_llava.py | {
"start": 3732,
"end": 10397
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = LlavaImageProcessor if is_vision_available() else None
fast_image_processing_class = LlavaImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester... | LlavaImageProcessingTest |
python | huggingface__transformers | src/transformers/models/audioflamingo3/processing_audioflamingo3.py | {
"start": 1187,
"end": 1643
} | class ____(ProcessingKwargs, total=False):
_defaults = {
"text_kwargs": {
"padding": True,
},
"audio_kwargs": {
"sampling_rate": 16000,
"chunk_length": 30.0,
"return_attention_mask": True,
"padding": "max_length",
},
... | AudioFlamingo3ProcessorKwargs |
python | bokeh__bokeh | src/bokeh/resources.py | {
"start": 7590,
"end": 7713
} | class ____(Protocol):
@staticmethod
def __call__(components: list[str], kind: Kind) -> Hashes: ...
@dataclass
| HashesFn |
python | django__django | tests/admin_docs/views.py | {
"start": 489,
"end": 635
} | class ____(View):
"""
This is a view for :model:`myapp.Company`
"""
def get(self, request):
return HttpResponse()
| CompanyView |
python | dask__distributed | distributed/comm/registry.py | {
"start": 375,
"end": 2430
} | class ____(ABC):
"""
A communication backend, selected by a given URI scheme (e.g. 'tcp').
"""
# I/O
@abstractmethod
def get_connector(self):
"""
Get a connector object usable for connecting to addresses.
"""
@abstractmethod
def get_listener(self, loc, handle_c... | Backend |
python | doocs__leetcode | solution/3400-3499/3427.Sum of Variable Length Subarrays/Solution.py | {
"start": 0,
"end": 189
} | class ____:
def subarraySum(self, nums: List[int]) -> int:
s = list(accumulate(nums, initial=0))
return sum(s[i + 1] - s[max(0, i - x)] for i, x in enumerate(nums))
| Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 642178,
"end": 642797
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("branch", "git_url", "name", "path", "subproject_commit_oid")
branch = sgqlc.types.Field(String, graphql_name="branch")
git_url = sgqlc.types.Field(sgqlc.types.non_null(URI), ... | Submodule |
python | psf__black | tests/data/cases/line_ranges_fmt_off_decorator.py | {
"start": 266,
"end": 774
} | class ____:
# fmt: off
@decorator ( )
# fmt: on
def method():
print ( "str" )
@decor(
a=1,
# fmt: off
b=(2, 3),
# fmt: on
)
def func():
pass
# output
# flags: --line-ranges=12-12 --line-ranges=21-21
# NOTE: If you need to modify th... | MyClass |
python | ansible__ansible | lib/ansible/_internal/_wrapt.py | {
"start": 3448,
"end": 3921
} | class ____(type):
def __new__(cls, name, bases, dictionary):
# Copy our special properties into the class so that they
# always take precedence over attributes of the same name added
# during construction of a derived class. This is to save
# duplicating the implementation for them i... | _ObjectProxyMetaType |
python | huggingface__transformers | src/transformers/models/roformer/modeling_roformer.py | {
"start": 44361,
"end": 47693
} | class ____(RoFormerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.roformer = RoFormerModel(config)
self.classifier = RoFormerClassificationHead(config)
# Initialize weights and apply final processing
se... | RoFormerForSequenceClassification |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/data.py | {
"start": 7968,
"end": 9975
} | class ____:
"""There are many properties of spans that we calculate by
essentially rerunning the test case multiple times based on the
calls which we record in SpanProperty.
This class defines a visitor, subclasses of which can be used
to calculate these properties.
"""
def __init__(self, ... | SpanProperty |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_outline02.py | {
"start": 315,
"end": 3023
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("outline02.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.re... | TestCompareXLSXFiles |
python | astropy__astropy | astropy/units/tests/test_quantity_decorator.py | {
"start": 8812,
"end": 12358
} | class ____:
@pytest.mark.parametrize(
"annot",
[u.m, u.Quantity[u.m], u.Quantity[u.m, "more"]],
) # Note: parametrization is done even if test class is skipped
def test_single_annotation_unit(self, annot):
"""Try a variety of valid annotations."""
@u.quantity_input
... | TestTypeAnnotations |
python | matplotlib__matplotlib | doc/sphinxext/math_symbol_table.py | {
"start": 4291,
"end": 5476
} | class ____(Directive):
has_content = False
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
option_spec = {}
def run(self):
return run(self.state_machine)
def setup(app):
app.add_directive("math_symbol_table", MathSymbolTableDirective)
metadata ... | MathSymbolTableDirective |
python | google__pytype | pytype/pytd/visitors.py | {
"start": 68573,
"end": 71033
} | class ____(Visitor):
"""Visitor for verifying that Literal[object] contains an enum.
Other valid Literal types are checked by the parser, e.g. to make sure no
`float` values are used in Literals. Checking that an object in a Literal is
an enum member is more complex, so it gets its own visitor.
Because this... | VerifyLiterals |
python | astropy__astropy | astropy/modeling/tests/test_fitters.py | {
"start": 13511,
"end": 24416
} | class ____:
"""Tests non-linear least squares fitting and the SLSQP algorithm."""
def setup_class(self):
self.initial_values = [100, 5, 1]
self.xdata = np.arange(0, 10, 0.1)
sigma = 4.0 * np.ones_like(self.xdata)
with NumpyRNGContext(_RANDOM_SEED):
yerror = np.rand... | TestNonLinearFitters |
python | scipy__scipy | scipy/stats/tests/test_qmc.py | {
"start": 30482,
"end": 33423
} | class ____(QMCEngineTests):
qmce = qmc.Sobol
can_scramble = True
# theoretical values from Joe Kuo2010
unscramble_nd = np.array([[0., 0.],
[0.5, 0.5],
[0.75, 0.25],
[0.25, 0.75],
[0.37... | TestSobol |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIn2.py | {
"start": 85,
"end": 585
} | class ____(enum.Enum):
A = enum.auto()
B = enum.auto()
C = enum.auto()
def func1(x: MyEnum):
if x is MyEnum.C:
return
elif x in (MyEnum.A, MyEnum.B):
reveal_type(x, expected_text="Literal[MyEnum.A, MyEnum.B]")
else:
reveal_type(x, expected_text="Never")
def func2(x: M... | MyEnum |
python | kamyu104__LeetCode-Solutions | Python/longest-valid-parentheses.py | {
"start": 723,
"end": 1272
} | class ____(object):
# @param s, a string
# @return an integer
def longestValidParentheses(self, s):
longest, last, indices = 0, -1, []
for i in xrange(len(s)):
if s[i] == '(':
indices.append(i)
elif not indices:
last = i
els... | Solution2 |
python | PyCQA__pylint | doc/data/messages/t/too-few-public-methods/bad.py | {
"start": 0,
"end": 272
} | class ____: # [too-few-public-methods]
def __init__(self, name: str, fruit_of_residence: Fruit):
self.name = name
self.fruit_of_residence = fruit_of_residence
def bore(self):
print(f"{self.name} is boring into {self.fruit_of_residence}")
| Worm |
python | docker__docker-py | tests/integration/api_container_test.py | {
"start": 52024,
"end": 53066
} | class ____(BaseAPIIntegrationTest):
def test_pause_unpause(self):
container = self.client.create_container(TEST_IMG, ['sleep', '9999'])
id = container['Id']
self.tmp_containers.append(id)
self.client.start(container)
self.client.pause(id)
container_info = self.client.... | PauseTest |
python | scipy__scipy | scipy/sparse/_coo.py | {
"start": 70441,
"end": 74632
} | class ____(spmatrix, _coo_base):
"""
A sparse matrix in COOrdinate format.
Also known as the 'ijv' or 'triplet' format.
This can be instantiated in several ways:
coo_matrix(D)
where D is a 2-D ndarray
coo_matrix(S)
with another sparse array or matrix S (equival... | coo_matrix |
python | scipy__scipy | scipy/stats/_warnings_errors.py | {
"start": 606,
"end": 927
} | class ____(DegenerateDataWarning):
"""Warns when all values in data are nearly equal."""
def __init__(self, msg=None):
if msg is None:
msg = ("All values in data are nearly equal; "
"results may not be reliable.")
self.args = (msg,)
# Errors
| NearConstantInputWarning |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 1702,
"end": 1795
} | class ____(SQLRole):
__slots__ = ()
_role_name = "Column expression"
| ColumnArgumentRole |
python | django__django | tests/backends/sqlite/tests.py | {
"start": 11136,
"end": 13220
} | class ____(SimpleTestCase):
databases = {"default"}
def test_default_transaction_mode(self):
with CaptureQueriesContext(connection) as captured_queries:
with transaction.atomic():
pass
begin_query, commit_query = captured_queries
self.assertEqual(begin_query... | TestTransactionMode |
python | kamyu104__LeetCode-Solutions | Python/count-houses-in-a-circular-street-ii.py | {
"start": 56,
"end": 213
} | class ____:
def closeDoor(self):
pass
def isDoorOpen(self):
pass
def moveRight(self):
pass
# constructive algorithms
| Street |
python | pallets__flask | src/flask/testing.py | {
"start": 8823,
"end": 10114
} | class ____(CliRunner):
"""A :class:`~click.testing.CliRunner` for testing a Flask app's
CLI commands. Typically created using
:meth:`~flask.Flask.test_cli_runner`. See :ref:`testing-cli`.
"""
def __init__(self, app: Flask, **kwargs: t.Any) -> None:
self.app = app
super().__init__(**... | FlaskCliRunner |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/snap.py | {
"start": 6155,
"end": 6260
} | class ____:
value: str
description: Optional[str]
@whitelist_for_serdes
@record
| ConfigEnumValueSnap |
python | weaviate__weaviate-python-client | weaviate/collections/data/executor.py | {
"start": 1527,
"end": 28273
} | class ____(Generic[ConnectionType, Properties]):
def __init__(
self,
connection: ConnectionType,
name: str,
consistency_level: Optional[ConsistencyLevel],
tenant: Optional[str],
validate_arguments: bool,
type_: Optional[Type[Properties]] = None,
) -> None:... | _DataCollectionExecutor |
python | pytest-dev__pytest | src/_pytest/pathlib.py | {
"start": 15096,
"end": 15262
} | class ____(Enum):
"""Possible values for `mode` parameter of `import_path`."""
prepend = "prepend"
append = "append"
importlib = "importlib"
| ImportMode |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1297402,
"end": 1299945
} | class ____(sgqlc.types.Type, Node):
"""Information about a specific package version."""
__schema__ = github_schema
__field_names__ = ("files", "package", "platform", "pre_release", "readme", "release", "statistics", "summary", "version")
files = sgqlc.types.Field(
sgqlc.types.non_null(PackageFi... | PackageVersion |
python | getsentry__sentry | tests/sentry/sudo/test_views.py | {
"start": 6079,
"end": 6600
} | class ____(BaseTestCase):
def test_redirect_to_sudo_simple(self) -> None:
response = redirect_to_sudo("/foo")
self.assertEqual(response.status_code, 302)
self.assertEqual(response["Location"], "/account/sudo/?next=/foo")
def test_redirect_to_sudo_with_querystring(self) -> None:
... | RedirectToSudoTestCase |
python | walkccc__LeetCode | solutions/2560. House Robber IV/2560.py | {
"start": 0,
"end": 375
} | class ____:
def minCapability(self, nums: list[int], k: int) -> int:
def numStolenHouses(capacity: int) -> int:
stolenHouses = 0
i = 0
while i < len(nums):
if nums[i] <= capacity:
stolenHouses += 1
i += 1
i += 1
return stolenHouses
return bisect.bis... | Solution |
python | getsentry__sentry | src/sentry/dashboards/endpoints/organization_dashboard_widget_details.py | {
"start": 567,
"end": 1988
} | class ____(OrganizationEndpoint):
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.DASHBOARDS
permission_classes = (OrganizationDashboardsPermission,)
def post(self, request: Request, organization: Organization) -> Response:
"""
Validate a Widget
... | OrganizationDashboardWidgetDetailsEndpoint |
python | openai__openai-python | src/openai/types/realtime/realtime_conversation_item_function_call_output.py | {
"start": 247,
"end": 1103
} | class ____(BaseModel):
call_id: str
"""The ID of the function call this output is for."""
output: str
"""
The output of the function call, this is free text and can contain any
information or simply be empty.
"""
type: Literal["function_call_output"]
"""The type of the item. Always... | RealtimeConversationItemFunctionCallOutput |
python | pydata__xarray | asv_bench/benchmarks/interp.py | {
"start": 377,
"end": 1945
} | class ____:
def setup(self, *args, **kwargs):
self.ds = xr.Dataset(
{
"var1": (("x", "y"), randn_xy),
"var2": (("x", "t"), randn_xt),
"var3": (("t",), randn_t),
"var4": (("z",), np.array(["text"])),
"var5": (("k",), ... | Interpolation |
python | huggingface__transformers | src/transformers/models/hgnet_v2/modeling_hgnet_v2.py | {
"start": 1633,
"end": 1859
} | class ____(PreTrainedModel):
config: HGNetV2Config
base_model_prefix = "hgnetv2"
main_input_name = "pixel_values"
input_modalities = ("image",)
_no_split_modules = ["HGNetV2BasicLayer"]
| HGNetV2PreTrainedModel |
python | huggingface__transformers | src/transformers/models/sew_d/modeling_sew_d.py | {
"start": 11870,
"end": 12876
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_id=0):
super().__init__()
self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
self.out_conv_dim = config.conv_dim[layer_id]
self.conv = nn.Conv1d(
self.in_conv_dim,
s... | SEWDGroupNormConvLayer |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/webserver.py | {
"start": 129,
"end": 246
} | class ____(BaseModel):
host: str
port: int
name: Optional[str] = None
ssl: Optional[bool] = None
| Server |
python | google__flatbuffers | tests/py_test.py | {
"start": 85001,
"end": 86692
} | class ____(unittest.TestCase):
def test_object_is_nested_error(self):
b = flatbuffers.Builder(0)
b.StartObject(0)
assertRaises(
self, lambda: b.StartObject(0), flatbuffers.builder.IsNestedError
)
def test_object_is_not_nested_error(self):
b = flatbuffers.Builder(0)
assertRaises(
... | TestExceptions |
python | networkx__networkx | networkx/algorithms/traversal/tests/test_edgedfs.py | {
"start": 812,
"end": 4775
} | class ____:
@classmethod
def setup_class(cls):
cls.nodes = [0, 1, 2, 3]
cls.edges = [(0, 1), (1, 0), (1, 0), (2, 1), (3, 1)]
def test_empty(self):
G = nx.Graph()
edges = list(edge_dfs(G))
assert edges == []
def test_graph(self):
G = nx.Graph(self.edges)
... | TestEdgeDFS |
python | kamyu104__LeetCode-Solutions | Python/find-the-maximum-length-of-a-good-subsequence-i.py | {
"start": 1180,
"end": 1727
} | class ____(object):
def maximumLength(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
dp = [[0]*(k+1) for _ in xrange(len(nums))]
result = 0
for i in xrange(len(nums)):
dp[i][0] = 1
for l in xrange(k+1):
... | Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/selector.py | {
"start": 9662,
"end": 10071
} | class ____:
"""The information needed to resolve a graph within a host process."""
location_name: str
repository_name: str
graph_name: str
def to_graphql_input(self):
return {
"repositoryLocationName": self.location_name,
"repositoryName": self.repository_name,
... | GraphSelector |
python | pyca__cryptography | tests/hazmat/primitives/test_pkcs12.py | {
"start": 27466,
"end": 35963
} | class ____:
def test_generate_valid_truststore(self, backend):
# serialize_java_truststore adds a special attribute to each
# certificate's safebag. As we cannot read this back currently,
# comparison against a pre-verified file is necessary.
cert1 = _load_cert(
backend, ... | TestPKCS12TrustStoreCreation |
python | kamyu104__LeetCode-Solutions | Python/stamping-the-sequence.py | {
"start": 70,
"end": 1306
} | class ____(object):
def movesToStamp(self, stamp, target):
M, N = len(stamp), len(target)
q = collections.deque()
lookup = [False]*N
result = []
A = []
for i in xrange(N-M+1):
made, todo = set(), set()
for j, c in enumerate(stamp):
... | Solution |
python | django__django | tests/migrations/migrations_test_apps/with_generic_model/models.py | {
"start": 599,
"end": 657
} | class ____(Parent1[T1, T3], Parent2[T2, T3]):
pass
| Child |
python | pytransitions__transitions | transitions/extensions/diagrams.py | {
"start": 12288,
"end": 12508
} | class ____(TransitionGraphSupport, NestedTransition):
"""
A transition type to be used with (subclasses of) `HierarchicalGraphMachine` and
`LockedHierarchicalGraphMachine`.
"""
| NestedGraphTransition |
python | django__django | django/contrib/admin/filters.py | {
"start": 25056,
"end": 27668
} | class ____(FieldListFilter):
def __init__(self, field, request, params, model, model_admin, field_path):
if not field.empty_strings_allowed and not field.null:
raise ImproperlyConfigured(
"The list filter '%s' cannot be used with field '%s' which "
"doesn't allow ... | EmptyFieldListFilter |
python | doocs__leetcode | solution/0300-0399/0333.Largest BST Subtree/Solution.py | {
"start": 192,
"end": 714
} | class ____:
def largestBSTSubtree(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if root is None:
return inf, -inf, 0
lmi, lmx, ln = dfs(root.left)
rmi, rmx, rn = dfs(root.right)
nonlocal ans
if lmx < root.val < rmi:
... | Solution |
python | chroma-core__chroma | chromadb/errors.py | {
"start": 123,
"end": 520
} | class ____(Exception, EnforceOverrides):
trace_id: Optional[str] = None
def code(self) -> int:
"""Return an appropriate HTTP response code for this error"""
return 400 # Bad Request
def message(self) -> str:
return ", ".join(self.args)
@classmethod
@abstractmethod
def... | ChromaError |
python | keras-team__keras | keras/src/metrics/accuracy_metrics.py | {
"start": 5343,
"end": 8482
} | class ____(reduction_metrics.MeanMetricWrapper):
"""Calculates how often predictions match one-hot labels.
You can provide logits of classes as `y_pred`, since argmax of
logits and probabilities are same.
This metric creates two local variables, `total` and `count` that are used
to compute the fre... | CategoricalAccuracy |
python | walkccc__LeetCode | solutions/2816. Double a Number Represented as a Linked List/2816-2.py | {
"start": 0,
"end": 313
} | class ____:
def doubleIt(self, head: ListNode | None) -> ListNode | None:
if head.val >= 5:
head = ListNode(0, head)
curr = head
while curr:
curr.val *= 2
curr.val %= 10
if curr.next and curr.next.val >= 5:
curr.val += 1
curr = curr.next
return head
| Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/selectors/pydantic_selectors.py | {
"start": 3325,
"end": 5207
} | class ____(BaseSelector):
def __init__(
self, selector_program: BasePydanticProgram, max_outputs: Optional[int] = None
) -> None:
self._selector_program = selector_program
self._max_outputs = max_outputs
@classmethod
def from_defaults(
cls,
program: Optional[Base... | PydanticMultiSelector |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/optimization/test_manual_optimization.py | {
"start": 5174,
"end": 10311
} | class ____(BoringModel):
count = 0
called = collections.defaultdict(int)
detach = False
def __init__(self):
super().__init__()
self.automatic_optimization = False
@property
def should_update(self):
return self.count % 2 == 0
def on_train_batch_start(self, batch, ba... | ManualOptimizationExtendedModel |
python | getsentry__sentry | src/sentry/relay/projectconfig_debounce_cache/redis.py | {
"start": 368,
"end": 3143
} | class ____(ProjectConfigDebounceCache):
def __init__(self, **options):
self._key_prefix = options.pop("key_prefix", "relayconfig-debounce")
self._debounce_ttl = options.pop("debounce_ttl", REDIS_CACHE_TIMEOUT)
self.is_redis_cluster, self.cluster, options = get_dynamic_cluster_from_options(
... | RedisProjectConfigDebounceCache |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/resource.py | {
"start": 1716,
"end": 1874
} | class ____(graphene.ObjectType):
class Meta:
name = "ResourceConnection"
resources = non_null_list(GrapheneResource)
| GrapheneResourceConnection |
python | tiangolo__fastapi | docs_src/body_nested_models/tutorial006_py310.py | {
"start": 144,
"end": 475
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
tags: set[str] = set()
images: list[Image] | None = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
results = {"item_id": item_id, "item": item}
retu... | Item |
python | conda__conda | conda/plugins/prefix_data_loaders/pypi/pkg_format.py | {
"start": 41608,
"end": 48524
} | class ____:
"""This class is used to evaluate marker expressions."""
operations = {
"==": lambda x, y: x == y,
"===": lambda x, y: x == y,
"~=": lambda x, y: x == y or x > y,
"!=": lambda x, y: x != y,
"<": lambda x, y: x < y,
"<=": lambda x, y: x == y or x < y,
... | Evaluator |
python | walkccc__LeetCode | solutions/1472. Design Browser History/1472.py | {
"start": 0,
"end": 591
} | class ____:
def __init__(self, homepage: str):
self.urls = []
self.index = -1
self.lastIndex = -1
self.visit(homepage)
def visit(self, url: str) -> None:
self.index += 1
if self.index < len(self.urls):
self.urls[self.index] = url
else:
self.urls.append(url)
self.lastInde... | BrowserHistory |
python | pytorch__pytorch | test/distributed/checkpoint/test_quantized_hf_storage.py | {
"start": 502,
"end": 11348
} | class ____(TestCase):
def setUp(self):
super().setUp()
"""Set up common test fixtures."""
self.temp_dir = tempfile.TemporaryDirectory()
self.path = self.temp_dir.name
def tearDown(self):
"""Clean up test fixtures."""
self.temp_dir.cleanup()
def test_dequanti... | TestQuantizedHfStorage |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-sec-filings/llama_index/readers/sec_filings/prepline_sec_filings/sec_document.py | {
"start": 2005,
"end": 18393
} | class ____(HTMLDocument):
filing_type = None
def _filter_table_of_contents(self, elements: List[Text]) -> List[Text]:
"""Filter out unnecessary elements in the table of contents using keyword search."""
if self.filing_type in REPORT_TYPES:
# NOTE(yuming): Narrow TOC as all elements ... | SECDocument |
python | scipy__scipy | scipy/stats/_morestats.py | {
"start": 162052,
"end": 177966
} | class ____:
def __init__(self, mean_direction, mean_resultant_length):
self.mean_direction = mean_direction
self.mean_resultant_length = mean_resultant_length
def __repr__(self):
return (f"DirectionalStats(mean_direction={self.mean_direction},"
f" mean_resultant_length={... | DirectionalStats |
python | huggingface__transformers | src/transformers/models/deepseek_vl_hybrid/modular_deepseek_vl_hybrid.py | {
"start": 8096,
"end": 8934
} | class ____(DeepseekVLPreTrainedModel):
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
if isinstance(module, nn.Linear):
init.normal_(module.weight, mean=0.0, std=self.config.text_config.initializer_range)
if module.bias is not None:
... | DeepseekVLHybridPreTrainedModel |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/test_project/__init__.py | {
"start": 3210,
"end": 4467
} | class ____(ReconstructableJob):
def __new__(
cls,
reconstructable_job: ReconstructableJob,
):
return super().__new__(
cls,
reconstructable_job.repository,
reconstructable_job.job_name,
reconstructable_job.op_selection,
)
def ge... | ReOriginatedReconstructableJobForTest |
python | wandb__wandb | wandb/vendor/pygments/lexers/c_cpp.py | {
"start": 7809,
"end": 8245
} | class ____(CFamilyLexer):
"""
For C source code with preprocessor directives.
"""
name = 'C'
aliases = ['c']
filenames = ['*.c', '*.h', '*.idc']
mimetypes = ['text/x-chdr', 'text/x-csrc']
priority = 0.1
def analyse_text(text):
if re.search('^\s*#include [<"]', text, re.MULTI... | CLexer |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 48781,
"end": 50672
} | class ____(TestCase):
"""Tests for ``split_after()``"""
def test_starts_with_sep(self):
actual = list(mi.split_after('xooxoo', lambda c: c == 'x'))
expected = [['x'], ['o', 'o', 'x'], ['o', 'o']]
self.assertEqual(actual, expected)
def test_ends_with_sep(self):
actual = list... | SplitAfterTest |
python | fluentpython__example-code-2e | 15-more-types/protocol/abs_demo.py | {
"start": 56,
"end": 660
} | class ____(NamedTuple):
x: float
y: float
def __abs__(self) -> float: # <1>
return math.hypot(self.x, self.y)
def is_unit(v: SupportsAbs[float]) -> bool: # <2>
"""'True' if the magnitude of 'v' is close to 1."""
return math.isclose(abs(v), 1.0) # <3>
assert issubclass(Vector2d, Support... | Vector2d |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 335981,
"end": 337733
} | class ____(VegaLiteSchema):
"""
ErrorBarConfig schema wrapper.
Parameters
----------
extent : :class:`ErrorBarExtent`, Literal['ci', 'iqr', 'stderr', 'stdev']
The extent of the rule. Available options include:
* ``"ci"``: Extend the rule to the 95% bootstrapped confidence interval ... | ErrorBarConfig |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 307445,
"end": 308910
} | class ____:
def _create_data(self):
m = np.array([1, 2, 3, 4, 5, 6])
m_rect = m.reshape((2, 3))
return m, m_rect
def test_basic(self):
m, _ = self._create_data()
A = np.repeat(m, [1, 3, 2, 1, 1, 2])
assert_equal(A, [1, 2, 2, 2, 3,
3, 4, 5... | TestRepeat |
python | getsentry__sentry | src/sentry/users/models/identity.py | {
"start": 994,
"end": 1084
} | class ____:
UNKNOWN = 0
VALID = 1
INVALID = 2
@control_silo_model
| IdentityStatus |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zenloop/source_zenloop/streams.py | {
"start": 3062,
"end": 4539
} | class ____(ZenloopStream, ABC):
# checkpoint stream reads after 1000 records.
state_checkpoint_interval = 1000
cursor_field = "inserted_at"
def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:
# latest_record has obj... | IncrementalZenloopStream |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/compiler.py | {
"start": 11070,
"end": 11213
} | class ____(TypedDict):
asfrom_froms: Set[FromClause]
correlate_froms: Set[FromClause]
selectable: ReturnsRows
| _BaseCompilerStackEntry |
python | openai__openai-python | src/openai/types/realtime/realtime_response.py | {
"start": 1131,
"end": 1198
} | class ____(BaseModel):
output: Optional[AudioOutput] = None
| Audio |
python | django__django | django/http/multipartparser.py | {
"start": 21133,
"end": 21720
} | class ____:
"""
An iterable that will yield chunks of data. Given a file-like object as the
constructor, yield chunks of read operations from that object.
"""
def __init__(self, flo, chunk_size=64 * 1024):
self.flo = flo
self.chunk_size = chunk_size
def __next__(self):
... | ChunkIter |
python | pennersr__django-allauth | allauth/socialaccount/providers/stocktwits/provider.py | {
"start": 227,
"end": 463
} | class ____(ProviderAccount):
def get_avatar_url(self):
return self.account.extra_data.get("user", {}).get("avatar_url_ssl")
def get_user_data(self):
return self.account.extra_data.get("user", {})
| StocktwitsAccount |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP049_1.py | {
"start": 1665,
"end": 1830
} | class ____[_T]:
T = 42
v1 = cast(_T, ...)
v2 = cast('_T', ...)
# Unfixable as the new name collides with a variable visible from one of the inner scopes
| C |
python | PyCQA__pylint | pylint/config/argument.py | {
"start": 13819,
"end": 14859
} | class ____(_Argument):
"""Class representing an callable argument to be parsed by an
argparse.ArgumentsParser.
This is based on the parameters passed to argparse.ArgumentsParser.add_message.
See:
https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument
"""
def _... | _CallableArgument |
python | Farama-Foundation__Gymnasium | docs/tutorials/training_agents/frozenlake_q_learning.py | {
"start": 904,
"end": 2841
} | class ____(NamedTuple):
total_episodes: int # Total episodes
learning_rate: float # Learning rate
gamma: float # Discounting rate
epsilon: float # Exploration probability
map_size: int # Number of tiles of one side of the squared environment
seed: int # Define a seed so that we get reprodu... | Params |
python | ansible__ansible | lib/ansible/galaxy/collection/galaxy_api_proxy.py | {
"start": 762,
"end": 7805
} | class ____:
"""A proxy that abstracts talking to multiple Galaxy instances."""
def __init__(self, apis: t.Iterable[GalaxyAPI], concrete_artifacts_manager: ConcreteArtifactsManager, offline: bool = False) -> None:
"""Initialize the target APIs list."""
self._apis = apis
self._concrete_ar... | MultiGalaxyAPIProxy |
python | great-expectations__great_expectations | great_expectations/execution_engine/execution_engine.py | {
"start": 3295,
"end": 3552
} | class ____:
"""compute_domain_kwargs, accessor_domain_kwargs when partitioned from domain_kwargs
The union of compute_domain_kwargs, accessor_domain_kwargs is the input domain_kwargs
"""
compute: dict
accessor: dict
| PartitionDomainKwargs |
python | django__django | tests/contenttypes_tests/models.py | {
"start": 1467,
"end": 1688
} | class ____(FooWithoutUrl):
"""
Fake model defining a ``get_absolute_url`` method containing an error
"""
def get_absolute_url(self):
return "/users/%s/" % self.unknown_field
| FooWithBrokenAbsoluteUrl |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 6814,
"end": 7439
} | class ____(Element, ABC):
"""Widget base class for testing."""
id: str = field(repr=False)
disabled: bool
key: str | None
_value: Any
def __init__(self, proto: Any, root: ElementTree) -> None:
self.proto = proto
self.root = root
self.key = user_key_from_element_id(self.... | Widget |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/tests/test_registry.py | {
"start": 3770,
"end": 5172
} | class ____:
"""Tests for _convert_json_to_metrics_dict function."""
@pytest.mark.parametrize(
"jsonl_input,expected_output,description",
[
(
'{"_airbyte_data": {"connector_definition_id": "conn-123", "airbyte_platform": "cloud", "usage": 100}}',
{"con... | TestConvertJsonToMetricsDict |
python | ethereum__web3.py | web3/types.py | {
"start": 9785,
"end": 9882
} | class ____(TypedDict):
key: HexStr
proof: Sequence[HexStr]
value: HexBytes
| StorageProof |
python | doocs__leetcode | solution/2600-2699/2646.Minimize the Total Price of the Trips/Solution.py | {
"start": 0,
"end": 927
} | class ____:
def minimumTotalPrice(
self, n: int, edges: List[List[int]], price: List[int], trips: List[List[int]]
) -> int:
def dfs(i: int, fa: int, k: int) -> bool:
cnt[i] += 1
if i == k:
return True
ok = any(j != fa and dfs(j, i, k) for j in ... | Solution |
python | getsentry__sentry | tests/sentry/auth_v2/utils/test_session.py | {
"start": 327,
"end": 802
} | class ____(SessionBase):
"""Mock session class for testing."""
def __init__(self):
self.data = {}
def get(self, key, default=None):
return self.data.get(key, default)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[ke... | MockSession |
python | davidhalter__parso | parso/python/errors.py | {
"start": 45516,
"end": 45795
} | class ____(_CheckAssignmentRule):
def is_issue(self, del_stmt):
child = del_stmt.children[1]
if child.type != 'expr_list': # Already handled.
self._check_assignment(child, is_deletion=True)
@ErrorFinder.register_rule(type='expr_list')
| _DelStmtRule |
python | getsentry__sentry | tests/sentry/sentry_apps/models/test_sentryapp.py | {
"start": 460,
"end": 4144
} | class ____(TestCase):
def setUp(self) -> None:
self.user = self.create_user()
self.org = self.create_organization(owner=self.user)
self.proxy = self.create_user()
self.application = ApiApplication.objects.create(owner=self.proxy)
self.sentry_app = SentryApp(
appl... | SentryAppTest |
python | pypa__warehouse | tests/unit/admin/views/test_helpscout.py | {
"start": 227,
"end": 3955
} | class ____:
def test_no_secret(self, db_request):
db_request.headers["X-HelpScout-Signature"] = base64.b64encode(b"bitsnbytes")
result = views.helpscout(db_request)
assert result == {"Error": "NotAuthorized"}
def test_no_auth(self, db_request):
db_request.registry.settings["admi... | TestHelpscoutApp |
python | apache__thrift | lib/py/test/thrift_TSerializer.py | {
"start": 1419,
"end": 2767
} | class ____(unittest.TestCase):
def setUp(self):
self.message = Message("hello thrift", 42)
self.binary_serialized = b"\x0b\x00\x01\x00\x00\x00\x0chello thrift\n\x00\x02\x00\x00\x00\x00\x00\x00\x00*\x00"
self.compact_serialized = b'\x18\x0chello thrift\x16T\x00'
def verify(self, serializ... | TestSerializer |
python | run-llama__llama_index | llama-index-core/llama_index/core/schema.py | {
"start": 40435,
"end": 44679
} | class ____(Document):
"""Backward compatible wrapper around Document containing an image."""
def __init__(self, **kwargs: Any) -> None:
image = kwargs.pop("image", None)
image_path = kwargs.pop("image_path", None)
image_url = kwargs.pop("image_url", None)
image_mimetype = kwargs... | ImageDocument |
python | encode__starlette | starlette/routing.py | {
"start": 21532,
"end": 22382
} | class ____(AbstractAsyncContextManager[_T]):
def __init__(self, cm: AbstractContextManager[_T]):
self._cm = cm
async def __aenter__(self) -> _T:
return self._cm.__enter__()
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | N... | _AsyncLiftContextManager |
python | huggingface__transformers | tests/models/moshi/test_modeling_moshi.py | {
"start": 37201,
"end": 43782
} | class ____(unittest.TestCase):
@cached_property
def feature_extractor(self):
return AutoFeatureExtractor.from_pretrained("kmhf/hf-moshiko")
@cached_property
def tokenizer(self):
return AutoTokenizer.from_pretrained("kmhf/hf-moshiko")
def _load_datasample(self):
ds = load_da... | MoshiIntegrationTests |
python | Textualize__textual | tests/option_list/test_option_messages.py | {
"start": 264,
"end": 4303
} | class ____(App[None]):
"""Test option list application."""
def __init__(self) -> None:
super().__init__()
self.messages: list[tuple[str, str, int]] = []
def compose(self) -> ComposeResult:
yield OptionList(*[Option(str(n), id=str(n)) for n in range(10)])
def _record(self, even... | OptionListApp |
python | GoogleCloudPlatform__python-docs-samples | endpoints/bookstore-grpc-transcoding/bookstore_pb2_grpc.py | {
"start": 3277,
"end": 7927
} | class ____:
"""A simple Bookstore API.
The API manages shelves and books resources. Shelves contain books.
"""
def ListShelves(self, request, context):
"""Returns a list of all shelves in the bookstore."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Met... | BookstoreServicer |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 221014,
"end": 221589
} | class ____(Operation):
def call(self, x):
return backend.numpy.negative(x)
def compute_output_spec(self, x):
sparse = getattr(x, "sparse", False)
return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse)
@keras_export(["keras.ops.negative", "keras.ops.numpy.negative"])
def negative(x)... | Negative |
python | readthedocs__readthedocs.org | readthedocs/core/unresolver.py | {
"start": 979,
"end": 1041
} | class ____(UnresolverError):
pass
| InvalidXRTDSlugHeaderError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.