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 | walkccc__LeetCode | solutions/271. Encode and Decode Strings/271.py | {
"start": 0,
"end": 463
} | class ____:
def encode(self, strs: list[str]) -> str:
"""Encodes a list of strings to a single string."""
return ''.join(str(len(s)) + '/' + s for s in strs)
def decode(self, s: str) -> list[str]:
"""Decodes a single string to a list of strings."""
decoded = []
i = 0
while i < len(s):
... | Codec |
python | sympy__sympy | sympy/simplify/hyperexpand.py | {
"start": 35163,
"end": 36864
} | class ____:
"""
Base class for operators to be applied to our functions.
Explanation
===========
These operators are differential operators. They are by convention
expressed in the variable D = z*d/dz (although this base class does
not actually care).
Note that when the operator is app... | Operator |
python | kamyu104__LeetCode-Solutions | Python/maximum-score-of-non-overlapping-intervals.py | {
"start": 1083,
"end": 1982
} | class ____(object):
def maximumWeight(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[int]
"""
K = 4
lookup = {}
for i, (l, r, w) in enumerate(intervals):
if (l, r, w) not in lookup:
lookup[l, r, w] = i
s... | Solution2 |
python | plotly__plotly.py | plotly/graph_objs/icicle/_insidetextfont.py | {
"start": 233,
"end": 17186
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "icicle"
_path_str = "icicle.insidetextfont"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
... | Insidetextfont |
python | wepe__MachineLearning | DeepLearning Tutorials/Softmax_sgd(or logistic_sgd)/logistic_sgd.py | {
"start": 155,
"end": 9456
} | class ____(object):
def __init__(self, input, n_in, n_out):
self.W = theano.shared(
value=numpy.zeros(
(n_in, n_out),
dtype=theano.config.floatX
),
name='W',
borrow=True
)
self.b = theano.shared(
val... | LogisticRegression |
python | rapidsai__cudf | python/cudf/cudf/pandas/fast_slow_proxy.py | {
"start": 29565,
"end": 32238
} | class ____:
"""
A descriptor type used to define attributes of fast-slow proxies.
"""
_attr: Any
def __init__(self, name: str, *, private: bool = False):
self._name = name
self._private = private
self._attr = None
self._doc = None
self._dir = None
def _... | _FastSlowAttribute |
python | great-expectations__great_expectations | tests/core/factory/test_suite_factory.py | {
"start": 9229,
"end": 15555
} | class ____:
def test_add_empty_new_suite(
self,
unset_gx_env_variables: None,
data_context: AbstractDataContext,
) -> None:
# arrange
suite_name = "suite A"
suite = ExpectationSuite(name=suite_name)
# act
created_suite = data_context.suites.add_or... | TestSuiteFactoryAddOrUpdate |
python | redis__redis-py | redis/multidb/exception.py | {
"start": 54,
"end": 373
} | class ____(Exception):
"""Exception raised when a database is unhealthy due to an underlying exception."""
def __init__(self, message, database, original_exception):
super().__init__(message)
self.database = database
self.original_exception = original_exception
| UnhealthyDatabaseException |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 4052,
"end": 4288
} | class ____(PydanticValueError):
code = 'const'
def __str__(self) -> str:
permitted = ', '.join(repr(v) for v in self.permitted) # type: ignore
return f'unexpected value; permitted: {permitted}'
| WrongConstantError |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_code_execution_output_block.py | {
"start": 205,
"end": 313
} | class ____(BaseModel):
file_id: str
type: Literal["code_execution_output"]
| BetaCodeExecutionOutputBlock |
python | ansible__ansible | lib/ansible/utils/collection_loader/_collection_finder.py | {
"start": 29019,
"end": 32649
} | class ____(_AnsibleCollectionPkgLoaderBase):
def _validate_args(self):
super(_AnsibleCollectionPkgLoader, self)._validate_args()
if len(self._split_name) != 3:
raise ImportError('this loader can only load collection packages, not {0}'.format(self._fullname))
def _validate_final(self... | _AnsibleCollectionPkgLoader |
python | ray-project__ray | python/ray/tests/test_placement_group_failover.py | {
"start": 344,
"end": 9402
} | class ____(object):
def __init__(self):
self.n = 0
def value(self):
return self.n
def test_placement_group_recover_prepare_failure(monkeypatch, ray_start_cluster):
# Test to make sure that gcs can handle the prepare pg failure
# by retrying on other nodes.
cluster = ray_start_clus... | Actor |
python | geekcomputers__Python | spotifyAccount.py | {
"start": 536,
"end": 3267
} | class ____:
def update(self):
while True:
data = ""
urls = [
"https://api.proxyscrape.com/?request=getproxies&proxytype=socks4&timeout=10000&ssl=yes"
]
for url in urls:
data += requests.get(url).text
self.splited... | proxy |
python | kamyu104__LeetCode-Solutions | Python/rotate-array.py | {
"start": 2314,
"end": 2582
} | class ____(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
while k > 0:
nums.insert(0, nums.pop())
k -= 1
| Solution5 |
python | ray-project__ray | python/ray/llm/tests/serve/cpu/deployments/llm/test_builder_llm_server.py | {
"start": 216,
"end": 2184
} | class ____:
def test_build_llm_deployment(
self,
llm_config_with_mock_engine,
shutdown_ray_and_serve,
disable_placement_bundles,
):
"""Test `build_llm_deployment` can build a vLLM deployment."""
app = build_llm_deployment(llm_config_with_mock_engine)
asse... | TestBuildVllmDeployment |
python | kamyu104__LeetCode-Solutions | Python/find-beautiful-indices-in-the-given-array-i.py | {
"start": 109,
"end": 1552
} | class ____(object):
def beautifulIndices(self, s, a, b, k):
"""
:type s: str
:type a: str
:type b: str
:type k: int
:rtype: List[int]
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, l... | Solution |
python | huggingface__transformers | src/transformers/models/sam2/configuration_sam2.py | {
"start": 827,
"end": 6933
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Sam2HieraDetModel`]. It is used to instantiate
a HieraDet model as defined in the original sam2 repo according to the specified arguments, defining the model architecture.
Instantiating a configuration d... | Sam2HieraDetConfig |
python | astropy__astropy | astropy/utils/state.py | {
"start": 151,
"end": 731
} | class ____:
def __init__(self, parent, value):
self._value = value
self._parent = parent
def __enter__(self):
pass
def __exit__(self, type, value, tb):
self._parent._value = self._value
def __repr__(self):
# Ensure we have a single-line repr, just in case our
... | _ScienceStateContext |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_details.py | {
"start": 52,
"end": 9307
} | class ____(util.MdCase):
"""Test Details."""
extension = ['pymdownx.details', 'markdown.extensions.def_list']
extension_configs = {
'pymdownx.blocks': {
'blocks': ['pymdownx.blocks.details:Details']
}
}
def test_with_preceding_text(self):
"""Test content right b... | TestDetails |
python | falconry__falcon | falcon/errors.py | {
"start": 43082,
"end": 45520
} | class ____(HTTPError):
"""415 Unsupported Media Type.
The origin server is refusing to service the request because the
payload is in a format not supported by this method on the target
resource.
The format problem might be due to the request's indicated Content-
Type or Content-Encoding, or as... | HTTPUnsupportedMediaType |
python | getsentry__sentry | src/sentry/web/frontend/debug/mail.py | {
"start": 11466,
"end": 12358
} | class ____:
def __init__(self, html_template, text_template, context=None, subject=None):
self.html_template = html_template
self.text_template = text_template
self.subject = subject
self.context = context if context is not None else {}
add_unsubscribe_link(self.context)
... | MailPreview |
python | pypa__setuptools | setuptools/_vendor/jaraco/collections/__init__.py | {
"start": 23175,
"end": 23641
} | class ____(collections.UserDict):
"""
Instrument an existing dictionary with additional
functionality, but always reference and mutate
the original dictionary.
>>> orig = {'a': 1, 'b': 2}
>>> inst = InstrumentedDict(orig)
>>> inst['a']
1
>>> inst['c'] = 3
>>> orig['c']
3
... | InstrumentedDict |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/rnn_test.py | {
"start": 3287,
"end": 3860
} | class ____(rnn_cell_impl.RNNCell):
"""RNN Cell its state as a TensorArray."""
@property
def output_size(self):
return 1
@property
def state_size(self):
return (tensor_shape.TensorShape([]), ())
def zero_state(self, batch_size, dtype):
return (array_ops.zeros([], dtype=dtypes.int32),
... | TensorArrayStateRNNCell |
python | spack__spack | lib/spack/spack/util/web.py | {
"start": 30594,
"end": 30694
} | class ____(spack.error.SpackError):
"""Superclass for Spack web spidering errors."""
| SpackWebError |
python | gevent__gevent | src/gevent/tests/test__queue.py | {
"start": 16763,
"end": 16893
} | class ____(TestPutInterrupt):
kind = queue.Channel
def _makeOne(self):
return self.kind()
| TestPutInterruptChannel |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec25.py | {
"start": 305,
"end": 697
} | class ____(Generic[P]):
def __init__(self, handler: CommandHandler[P]) -> None: ...
def handler_no_args(ctx: Context) -> None: ...
def handler_one_arg(ctx: Context, a: int) -> None: ...
cmd_no_args = Command(handler_no_args)
reveal_type(cmd_no_args, expected_text="Command[()]")
cmd_one_arg = Command(handler_... | Command |
python | falconry__falcon | tests/test_headers.py | {
"start": 8153,
"end": 8373
} | class ____:
def on_get(self, req, resp):
headers = CustomHeaders()
resp.set_headers(headers)
def on_post(self, req, resp):
resp.set_headers(CustomHeadersNotCallable())
| CustomHeadersResource |
python | pandas-dev__pandas | pandas/tests/extension/base/reduce.py | {
"start": 92,
"end": 4975
} | class ____:
"""
Reduction specific tests. Generally these only
make sense for numeric/boolean operations.
"""
def _supports_reduction(self, ser: pd.Series, op_name: str) -> bool:
# Specify if we expect this reduction to succeed.
return False
def check_reduce(self, ser: pd.Serie... | BaseReduceTests |
python | encode__django-rest-framework | tests/test_validation.py | {
"start": 4170,
"end": 5672
} | class ____(TestCase):
def test_max_value_validation_serializer_success(self):
serializer = ValidationMaxValueValidatorModelSerializer(data={'number_value': 99})
assert serializer.is_valid()
def test_max_value_validation_serializer_fails(self):
serializer = ValidationMaxValueValidatorMo... | TestMaxValueValidatorValidation |
python | huggingface__transformers | src/transformers/models/dia/modular_dia.py | {
"start": 3396,
"end": 3430
} | class ____(Phi3MLP):
pass
| DiaMLP |
python | langchain-ai__langchain | libs/partners/openai/langchain_openai/chat_models/base.py | {
"start": 137907,
"end": 176508
} | class ____(Exception):
"""Error raised when OpenAI Structured Outputs API returns a refusal.
When using OpenAI's Structured Outputs API with user-generated input, the model
may occasionally refuse to fulfill the request for safety reasons.
See [more on refusals](https://platform.openai.com/docs/guides... | OpenAIRefusalError |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_tool_computer_use_20250124_param.py | {
"start": 362,
"end": 1331
} | class ____(TypedDict, total=False):
display_height_px: Required[int]
"""The height of the display in pixels."""
display_width_px: Required[int]
"""The width of the display in pixels."""
name: Required[Literal["computer"]]
"""Name of the tool.
This is how the tool will be called by the mod... | BetaToolComputerUse20250124Param |
python | numba__numba | numba/misc/gdb_print_extension.py | {
"start": 186,
"end": 5379
} | class ____:
def __init__(self, val):
self.val = val
def to_string(self):
try:
import numpy as np
HAVE_NUMPY = True
except ImportError:
HAVE_NUMPY = False
try:
NULL = 0x0
# Raw data references, these need unpacking/in... | NumbaArrayPrinter |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 19469,
"end": 20009
} | class ____(GatherDepDoneEvent):
""":class:`GatherDep` instruction terminated:
remote worker fetched successfully
"""
__slots__ = ("data",)
data: dict[Key, object] # There may be fewer keys than in GatherDep
def to_loggable(self, *, handled: float) -> StateMachineEvent:
out = copy(sel... | GatherDepSuccessEvent |
python | pypa__warehouse | warehouse/rate_limiting/interfaces.py | {
"start": 78,
"end": 871
} | class ____(Interface):
def test(*identifiers):
"""
Checks if the rate limit identified by the identifiers has been
reached, returning a boolean to indicate whether or not to allow the
action.
"""
def hit(*identifiers):
"""
Registers a hit for the rate lim... | IRateLimiter |
python | pytorch__pytorch | torch/utils/data/datapipes/dataframe/datapipes.py | {
"start": 1928,
"end": 2754
} | class ____(DFIterDataPipe):
def __init__(self, source_datapipe) -> None:
self.source_datapipe = source_datapipe
def __iter__(self):
size = None
all_buffer: list[Any] = []
for df in self.source_datapipe:
if size is None:
size = df_wrapper.get_len(df)
... | ShuffleDataFramesPipe |
python | getsentry__sentry | src/sentry/dynamic_sampling/rules/helpers/time_to_adoptions.py | {
"start": 4226,
"end": 4417
} | class ____:
name: str | None = None
@property
def time_to_adoption(self) -> int:
return LATEST_RELEASE_TTAS.get(self.name, DEFAULT_TTA) if self.name else DEFAULT_TTA
| Platform |
python | getsentry__sentry | tests/sentry/api/endpoints/test_rule_snooze.py | {
"start": 914,
"end": 14190
} | class ____(BaseRuleSnoozeTest):
endpoint = "sentry-api-0-rule-snooze"
method = "post"
def test_cannot_mute_unowned_alert(self) -> None:
user2 = self.create_user("foo@example.com")
org2 = self.create_organization(name="Other Org", owner=user2)
project2 = self.create_project(organizat... | PostRuleSnoozeTest |
python | pytorch__pytorch | torch/testing/_internal/common_pruning.py | {
"start": 12485,
"end": 13053
} | class ____(nn.Module):
"""Container module with an encoder, a recurrent module, and a linear."""
def __init__(
self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int
) -> None:
super().__init__()
self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers)
self.li... | LSTMLinearModel |
python | allegroai__clearml | clearml/router/endpoint_telemetry.py | {
"start": 196,
"end": 9972
} | class ____:
BACKEND_STAT_MAP = {
"cpu_usage_*": "cpu_usage",
"cpu_temperature_*": "cpu_temperature",
"disk_free_percent": "disk_free_home",
"io_read_mbs": "disk_read",
"io_write_mbs": "disk_write",
"network_tx_mbs": "network_tx",
"network_rx_mbs": "network_rx"... | EndpointTelemetry |
python | getsentry__sentry | src/sentry/users/models/user_avatar.py | {
"start": 1001,
"end": 3094
} | class ____(ControlAvatarBase):
"""
A UserAvatar associates a User with their avatar photo File
and contains their preferences for avatar type.
"""
AVATAR_TYPES = UserAvatarType.as_choices()
FILE_TYPE = "avatar.file"
user = FlexibleForeignKey("sentry.User", unique=True, related_name="avata... | UserAvatar |
python | huggingface__transformers | src/transformers/models/owlv2/processing_owlv2.py | {
"start": 1159,
"end": 1252
} | class ____(ImagesKwargs, total=False):
query_images: Optional[ImageInput]
| Owlv2ImagesKwargs |
python | astropy__astropy | astropy/cosmology/_src/tests/io/test_mapping.py | {
"start": 399,
"end": 9062
} | class ____(ToFromTestMixinBase):
"""Tests for a Cosmology[To/From]Format with ``format="mapping"``.
This class will not be directly called by :mod:`pytest` since its name does
not begin with ``Test``. To activate the contained tests this class must
be inherited in a subclass. Subclasses must define a :... | ToFromMappingTestMixin |
python | kamyu104__LeetCode-Solutions | Python/construct-product-matrix.py | {
"start": 727,
"end": 1536
} | class ____(object):
def constructProductMatrix(self, grid):
"""
:type grid: List[List[int]]
:rtype: List[List[int]]
"""
MOD = 12345
left = [1]*(len(grid)*len(grid[0])+1)
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
lef... | Solution2 |
python | joke2k__faker | faker/providers/date_time/el_GR/__init__.py | {
"start": 46,
"end": 805
} | class ____(DateTimeProvider):
DAY_NAMES = {
"0": "Κυριακή",
"1": "Δευτέρα",
"2": "Τρίτη",
"3": "Τετάρτη",
"4": "Πέμπτη",
"5": "Παρασκευή",
"6": "Σάββατο",
}
MONTH_NAMES = {
"01": "Ιανουάριος",
"02": "Φεβρουάριος",
"03": "Μάρτιο... | Provider |
python | great-expectations__great_expectations | tests/core/test_expectation_validation_result.py | {
"start": 17868,
"end": 20268
} | class ____:
@pytest.mark.unit
def test_expectation_validation_results_serializes(self) -> None:
evr = ExpectationValidationResult(
success=True,
expectation_config=gxe.ExpectColumnDistinctValuesToEqualSet(
column="passenger_count",
value_set=[1, 2]... | TestSerialization |
python | run-llama__llama_index | llama-index-core/llama_index/core/query_engine/router_query_engine.py | {
"start": 3913,
"end": 10441
} | class ____(BaseQueryEngine):
"""
Router query engine.
Selects one out of several candidate query engines to execute a query.
Args:
selector (BaseSelector): A selector that chooses one out of many options based
on each candidate's metadata and query.
query_engine_tools (Sequ... | RouterQueryEngine |
python | ansible__ansible | lib/ansible/utils/encrypt.py | {
"start": 2635,
"end": 2865
} | class ____:
crypt_id: str
salt_size: int
implicit_rounds: int | None = None
salt_exact: bool = False
implicit_ident: str | None = None
rounds_format: str | None = None
requires_gensalt: bool = False
| _Algo |
python | falconry__falcon | tests/test_http_method_routing.py | {
"start": 3752,
"end": 4072
} | class ____:
@selfless_decorator
def on_get(self, req, resp):
pass
@pytest.fixture
def catch_wsgiref_query_warning(asgi):
if asgi:
ctx = nullcontext()
else:
ctx = pytest.warns(WSGIWarning, match="Unknown REQUEST_METHOD: 'QUERY'")
with ctx:
yield
| FaultyDecoratedResource |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/streams.py | {
"start": 4993,
"end": 5474
} | class ____(FBMarketingIncrementalStream):
"""doc: https://developers.facebook.com/docs/marketing-api/reference/ad-campaign-group"""
entity_prefix = "campaign"
status_field = "effective_status"
valid_statuses = [status.value for status in ValidCampaignStatuses]
def list_objects(self, params: Mappin... | Campaigns |
python | tensorflow__tensorflow | tensorflow/python/debug/wrappers/framework_test.py | {
"start": 3173,
"end": 4951
} | class ____(framework.BaseDebugWrapperSession):
"""A concrete implementation of BaseDebugWrapperSession for test.
This class intentionally puts a bad action value in OnSessionInitResponse
and/or in OnRunStartAction to test the handling of such invalid cases.
"""
def __init__(
self,
sess,
ba... | TestDebugWrapperSessionBadAction |
python | pypa__warehouse | warehouse/integrations/vulnerabilities/models.py | {
"start": 391,
"end": 980
} | class ____(db.ModelBase):
__tablename__ = "release_vulnerabilities"
__table_args__ = (
ForeignKeyConstraint(
["vulnerability_source", "vulnerability_id"],
["vulnerabilities.source", "vulnerabilities.id"],
onupdate="CASCADE",
ondelete="CASCADE",
),
... | ReleaseVulnerability |
python | huggingface__transformers | src/transformers/models/timesformer/modeling_timesformer.py | {
"start": 7097,
"end": 7716
} | class ____(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob: Optional[float] = None) -> None:
super().__init__()
self.drop_prob = drop_prob
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:... | TimeSformerDropPath |
python | sqlalchemy__sqlalchemy | test/orm/test_deprecations.py | {
"start": 71893,
"end": 74678
} | class ____(_fixtures.FixtureTest):
run_inserts = "once"
run_deletes = None
def test_o2m_noload(self):
Address, addresses, users, User = (
self.classes.Address,
self.tables.addresses,
self.tables.users,
self.classes.User,
)
m = self.ma... | NoLoadTest |
python | numba__numba | numba/tests/test_parfors.py | {
"start": 109736,
"end": 116551
} | class ____(TestParforsBase):
def check(self, pyfunc, *args, **kwargs):
cfunc, cpfunc = self.compile_all(pyfunc, *args)
self.check_parfors_vs_others(pyfunc, cfunc, cpfunc, *args, **kwargs)
def assert_fusion_equivalence(self, got, expected):
a = self._fusion_equivalent(got)
b = s... | TestParforsDiagnostics |
python | huggingface__transformers | src/transformers/models/eomt/modeling_eomt.py | {
"start": 42438,
"end": 42869
} | class ____(nn.Module):
def __init__(self, config: EomtConfig):
super().__init__()
self.num_blocks = config.num_upscale_blocks
self.block = nn.ModuleList([EomtScaleLayer(config) for _ in range(self.num_blocks)])
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
for ... | EomtScaleBlock |
python | pallets__werkzeug | examples/webpylike/webpylike.py | {
"start": 695,
"end": 1678
} | class ____:
"""
An interface to a web.py like application. It works like the web.run
function in web.py
"""
def __init__(self, urls, views):
self.urls = [
(re.compile(f"^{urls[i]}$"), urls[i + 1]) for i in range(0, len(urls), 2)
]
self.views = views
def __c... | WebPyApp |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_compute.py | {
"start": 16204,
"end": 18182
} | class ____:
@mock.patch(COMPUTE_ENGINE_HOOK_PATH)
def test_delete_instance_should_execute_successfully(self, mock_hook):
op = ComputeEngineDeleteInstanceOperator(
resource_id=GCE_RESOURCE_ID,
zone=GCE_ZONE,
task_id=TASK_ID,
retry=RETRY,
timeout... | TestGceInstanceDelete |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/iterator_test.py | {
"start": 2290,
"end": 42623
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(test_base.graph_only_combinations())
def testNoGradients(self):
component = constant_op.constant([1.])
side = constant_op.constant(0.)
add = lambda x: x + side
dataset = dataset_ops.Dataset.from_tensor_slices(comp... | IteratorTest |
python | numba__numba | numba/core/types/scalars.py | {
"start": 2502,
"end": 2987
} | class ____(Literal, Boolean):
def __init__(self, value):
self._literal_init(value)
name = 'Literal[bool]({})'.format(value)
Boolean.__init__(
self,
name=name
)
def can_convert_to(self, typingctx, other):
conv = typingctx.can_convert(self.lite... | BooleanLiteral |
python | encode__django-rest-framework | tests/test_views.py | {
"start": 1109,
"end": 1400
} | class ____(APIView):
def get(self, request, *args, **kwargs):
raise Exception
def custom_handler(exc, context):
if isinstance(exc, SyntaxError):
return Response({'error': 'SyntaxError'}, status=400)
return Response({'error': 'UnknownError'}, status=500)
| ErrorView |
python | pypa__installer | tests/test_utils.py | {
"start": 3263,
"end": 3813
} | class ____:
def test_basic_functionality(self):
data = b"input data is this"
hash_ = (
base64.urlsafe_b64encode(hashlib.sha256(data).digest())
.decode("ascii")
.rstrip("=")
)
size = len(data)
with BytesIO(data) as source, BytesIO() as dest... | TestCopyFileObjWithHashing |
python | docker__docker-py | tests/integration/api_container_test.py | {
"start": 1240,
"end": 17901
} | class ____(BaseAPIIntegrationTest):
def test_create(self):
res = self.client.create_container(TEST_IMG, 'true')
assert 'Id' in res
self.tmp_containers.append(res['Id'])
def test_create_with_host_pid_mode(self):
ctnr = self.client.create_container(
TEST_IMG, 'true', ... | CreateContainerTest |
python | pandas-dev__pandas | pandas/tests/indexes/datetimes/test_date_range.py | {
"start": 39120,
"end": 46531
} | class ____:
def test_constructor(self):
bdate_range(START, END, freq=CDay())
bdate_range(START, periods=20, freq=CDay())
bdate_range(end=START, periods=20, freq=CDay())
msg = "periods must be an integer, got C"
with pytest.raises(TypeError, match=msg):
date_range... | TestCustomDateRange |
python | tensorflow__tensorflow | tensorflow/python/tools/api/generator2/generator/generator.py | {
"start": 4643,
"end": 6121
} | class ____:
"""An entrypoint that was exposed by the use of a decorator.
Attributes:
module: The public module that the symbol was exposed to. For example:
tensorflow.io.
name: The name the symbol was exported as. For example: decode_png.
exported_symbol: The symbol that this entrypoint refers ba... | _Entrypoint |
python | davidhalter__parso | parso/python/diff.py | {
"start": 19937,
"end": 22628
} | class ____:
_ChildrenGroup = namedtuple(
'_ChildrenGroup',
'prefix children line_offset last_line_offset_leaf')
def __init__(self, tree_node, parent=None, indentation=0):
self.tree_node = tree_node
self._children_groups = []
self.parent = parent
self._node_childr... | _NodesTreeNode |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 111704,
"end": 112032
} | class ____(BaseModel):
"""
Result of the points read request
"""
points: List["Record"] = Field(..., description="List of retrieved points")
next_page_offset: Optional["ExtendedPointId"] = Field(
default=None, description="Offset which should be used to retrieve a next page result"
)
| ScrollResult |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 73953,
"end": 76512
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
queue_url: str,
region: str,
delete_messages: bool,
max_batch_size: Optional[int] = None,
max_wait_time: Optional[int] = None,
attributes_to_return: Optional[str] = None,
... | AmazonSqsSource |
python | huggingface__transformers | tests/models/gpt_neox_japanese/test_tokenization_gpt_neox_japanese.py | {
"start": 933,
"end": 5263
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "abeja/gpt-neox-japanese-2.7b"
tokenizer_class = GPTNeoXJapaneseTokenizer
test_rust_tokenizer = False
from_pretrained_kwargs = {"do_clean_text": False, "add_prefix_space": False}
@classmethod
def setUpClass(cls):
... | GPTNeoXJapaneseTokenizationTest |
python | django__django | tests/forms_tests/tests/test_forms.py | {
"start": 232143,
"end": 232385
} | class ____(BoundField):
def label_tag(self, contents=None, attrs=None, label_suffix=None, tag=None):
return super().label_tag(
contents=contents, attrs=attrs, label_suffix="::", tag=None
)
| BoundFieldWithTwoColons |
python | dask__dask | dask/dataframe/dask_expr/_accessor.py | {
"start": 3753,
"end": 3908
} | class ____(FunctionMap):
def _divisions(self):
# TODO: We can do better here
return (None,) * (self.frame.npartitions + 1)
| FunctionMapIndex |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/tests/core/test_runner.py | {
"start": 7498,
"end": 8770
} | class ____:
"""Test graph loading functionality."""
def test_graph_loading_creates_linker_and_graph(self, mock_manifest):
"""Test that graph loading creates linker and graph correctly."""
runner = PrefectDbtRunner(manifest=mock_manifest)
with (
patch("prefect_dbt.core.runne... | TestPrefectDbtRunnerGraphLoading |
python | django__django | tests/serializers/test_jsonl.py | {
"start": 9105,
"end": 9911
} | class ____(
SerializersTransactionTestBase, TransactionTestCase
):
serializer_name = "jsonl"
fwd_ref_str = [
"""{
"pk": 1,
"model": "serializers.article",
"fields": {
"headline": "Forward references pose no problem",
"pub_date": "20... | JsonSerializerTransactionTestCase |
python | pytorch__pytorch | torch/distributed/elastic/multiprocessing/api.py | {
"start": 5967,
"end": 7502
} | class ____(ABC):
"""
Defines logs processing and redirection for each worker process.
Args:
log_dir:
Base directory where logs will be written.
redirects:
Streams to redirect to files. Pass a single ``Std``
enum to redirect for all workers, or a mapping k... | LogsSpecs |
python | skorch-dev__skorch | examples/benchmarks/mnist.py | {
"start": 1692,
"end": 8495
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.cnn = nn.Sequential(
nn.Conv2d(1, 32, (3, 3)),
nn.ReLU(),
nn.Conv2d(32, 64, (3, 3)),
nn.ReLU(),
nn.MaxPool2d((2, 2)),
nn.Dropout(0.25),
)
self.o... | ClassifierModule |
python | apache__airflow | providers/sftp/src/airflow/providers/sftp/triggers/sftp.py | {
"start": 1202,
"end": 6164
} | class ____(BaseTrigger):
"""
SFTPTrigger that fires in below listed scenarios.
1. The path on the SFTP server does not exist
2. The pattern do not match
:param path: The path on the SFTP server to search for a file matching the file pattern.
Authentication method used in the SFTP c... | SFTPTrigger |
python | kamyu104__LeetCode-Solutions | Python/balance-a-binary-search-tree.py | {
"start": 217,
"end": 1659
} | class ____(object):
def balanceBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def inorderTraversal(root):
result, stk = [], [(root, False)]
while stk:
node, is_visited = stk.pop()
if node is None:
... | Solution |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/batch_matmul_test.py | {
"start": 2601,
"end": 3327
} | class ____(BatchMatMultTestBase):
"""Testing BatchMatMulV2: one operand is weight and both have same rank."""
def ShouldAllowTF32Computation(self):
return False
def GraphFn(self, inp):
dtype = inp.dtype
b = constant_op.constant(
np.random.randn(1, 5, 7), dtype=dtype, name="kernel")
x1 = ... | BatchMatMulWeightBroadcastTest |
python | jupyterlab__jupyterlab | jupyterlab/extensions/manager.py | {
"start": 3840,
"end": 4434
} | class ____:
"""Action result
Attributes:
status: Action status - ["ok", "warning", "error"]
message: Action status explanation
needs_restart: Required action follow-up - Valid follow-up are "frontend", "kernel" and "server"
"""
# Note: no simple way to use Enum in dataclass - h... | ActionResult |
python | joke2k__faker | tests/providers/test_phone_number.py | {
"start": 15974,
"end": 16309
} | class ____:
"""Test ja_JP phone number provider methods"""
def test_phone_number(self, faker, num_samples):
for _ in range(num_samples):
pattern: Pattern = re.compile(r"(?:0[789]0|\d{2})-\d{4}-\d{4}")
phone_number = faker.phone_number()
assert pattern.fullmatch(phone... | TestJaJp |
python | pydata__xarray | xarray/backends/file_manager.py | {
"start": 11479,
"end": 12048
} | class ____:
"""Class for keeping track of reference counts."""
def __init__(self, counts):
self._counts = counts
self._lock = threading.Lock()
def increment(self, name):
with self._lock:
count = self._counts[name] = self._counts.get(name, 0) + 1
return count
... | _RefCounter |
python | wandb__wandb | wandb/sdk/data_types/helper_types/classes.py | {
"start": 1906,
"end": 5520
} | class ____(_dtypes.Type):
name = "classesId"
legacy_names = ["wandb.Classes_id"]
types = [Classes]
def __init__(
self,
classes_obj: Optional[Classes] = None,
valid_ids: Optional["_dtypes.UnionType"] = None,
):
if valid_ids is None:
valid_ids = _dtypes.Uni... | _ClassesIdType |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/qarithmetic_test.py | {
"start": 703,
"end": 1323
} | class ____(op_bench.TorchBenchmarkBase):
def setup(self, N, dtype, contig):
self.qfunctional = torch.ao.nn.quantized.QFunctional()
# TODO: Consider more diverse shapes
f_input = (torch.rand(N, N) - 0.5) * 256
self.scale = 1.0
self.zero_point = 0
self.q_input_a = torc... | _QFunctionalBinaryArithmeticBenchmarkBase |
python | apache__airflow | airflow-core/tests/unit/models/test_taskinstance.py | {
"start": 5218,
"end": 114141
} | class ____:
@staticmethod
def clean_db():
db.clear_db_dags()
db.clear_db_pools()
db.clear_db_runs()
db.clear_rendered_ti_fields()
db.clear_db_task_reschedule()
db.clear_db_assets()
db.clear_db_xcom()
def setup_method(self):
self.clean_db()
... | TestTaskInstance |
python | getsentry__sentry | tests/sentry/web/frontend/test_oauth_authorize.py | {
"start": 14280,
"end": 20416
} | class ____(TestCase):
@cached_property
def path(self) -> str:
return "/oauth/authorize/"
def setUp(self) -> None:
super().setUp()
self.owner = self.create_user(email="admin@test.com")
self.create_member(user=self.owner, organization=self.organization, role="owner")
s... | OAuthAuthorizeOrgScopedTest |
python | ipython__ipython | IPython/sphinxext/ipython_directive.py | {
"start": 34035,
"end": 45152
} | class ____(Directive):
has_content: bool = True
required_arguments: int = 0
optional_arguments: int = 4 # python, suppress, verbatim, doctest
final_argumuent_whitespace: bool = True
option_spec: Dict[str, Any] = {
"python": directives.unchanged,
"suppress": directives.flag,
... | IPythonDirective |
python | redis__redis-py | redis/multidb/database.py | {
"start": 1629,
"end": 2413
} | class ____(AbstractDatabase):
"""Database with an underlying synchronous redis client."""
@property
@abstractmethod
def client(self) -> Union[redis.Redis, RedisCluster]:
"""The underlying redis client."""
pass
@client.setter
@abstractmethod
def client(self, client: Union[re... | SyncDatabase |
python | PyCQA__pylint | tests/functional/u/useless/useless_object_inheritance.py | {
"start": 602,
"end": 645
} | class ____(A): # positive test case
pass
| F |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 20571,
"end": 21517
} | class ____(PrefectOperatorFilterBaseModel):
"""Filter by `FlowRun.parent_task_run_id`."""
any_: Optional[list[UUID]] = Field(
default=None, description="A list of flow run parent_task_run_ids to include"
)
is_null_: Optional[bool] = Field(
default=None,
description="If true, onl... | FlowRunFilterParentTaskRunId |
python | spack__spack | lib/spack/spack/fetch_strategy.py | {
"start": 25170,
"end": 27158
} | class ____(VCSFetchStrategy):
"""Fetch strategy that employs the ``go get`` infrastructure.
Use like this in a package::
version("name", go="github.com/monochromegane/the_platinum_searcher/...")
Go get does not natively support versions, they can be faked with git.
The fetched source will be ... | GoFetchStrategy |
python | facebookresearch__faiss | tests/test_rabitq.py | {
"start": 48348,
"end": 51130
} | class ____(unittest.TestCase):
def do_test_encode_decode(self, d, metric):
# rabitq must precisely reconstruct a vector,
# which consists of +A and -A values
seed = 123
rs = np.random.RandomState(seed)
ampl = 100
n = 10
vec = (2 * rs.randint(0, 2, d * n) -... | TestRaBitQuantizerEncodeDecode |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/executor/step_delegating/step_handler/base.py | {
"start": 502,
"end": 1893
} | class ____:
def __init__(
self,
instance: DagsterInstance,
plan_context: PlanOrchestrationContext,
steps: Sequence[ExecutionStep],
execute_step_args: ExecuteStepArgs,
dagster_run: Optional[DagsterRun] = None,
) -> None:
self._instance = instance
se... | StepHandlerContext |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyflakes/F811_30.py | {
"start": 292,
"end": 384
} | class ____:
"""C."""
def foo(self) -> None:
"""Foo."""
bar = (foo := 1)
| C |
python | huggingface__transformers | tests/models/umt5/test_modeling_umt5.py | {
"start": 1476,
"end": 8581
} | class ____:
def __init__(
self,
parent,
vocab_size=99,
batch_size=13,
encoder_seq_length=7,
decoder_seq_length=7,
# For common tests
is_training=True,
use_attention_mask=True,
use_labels=False,
hidden_size=32,
num_hidden... | UMT5ModelTester |
python | getsentry__sentry | tests/sentry/auth/test_superuser.py | {
"start": 1590,
"end": 23410
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.current_datetime = timezone.now()
self.default_token = "abcdefghjiklmnog"
self.superuser = self.create_user(is_superuser=True)
def build_request(
self,
cookie_token=UNSET,
session_token=U... | SuperuserTestCase |
python | python-pillow__Pillow | src/PIL/Image.py | {
"start": 107360,
"end": 107584
} | class ____(abc.ABC):
"""
Used as a mixin by point transforms
(for use with :py:meth:`~PIL.Image.Image.point`)
"""
@abc.abstractmethod
def point(self, im: Image) -> Image:
pass
| ImagePointHandler |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 14257,
"end": 14430
} | class ____:
__slots__ = ()
def _post_coercion(self, resolved, **kw):
from .util import _deep_deannotate
return _deep_deannotate(resolved)
| _Deannotate |
python | streamlit__streamlit | lib/tests/streamlit/connections/base_connection_test.py | {
"start": 1014,
"end": 1192
} | class ____(BaseConnection[str]):
def _connect(self, **kwargs) -> str:
return MockRawConnection()
def some_method(self):
return "some method"
| MockConnection |
python | wandb__wandb | wandb/sdk/launch/sweeps/scheduler.py | {
"start": 1249,
"end": 2063
} | class ____(Enum):
RUNNING = "running", "alive"
PENDING = "pending", "alive"
PREEMPTING = "preempting", "alive"
CRASHED = "crashed", "dead"
FAILED = "failed", "dead"
KILLED = "killed", "dead"
FINISHED = "finished", "dead"
PREEMPTED = "preempted", "dead"
# unknown when api.get_run_stat... | RunState |
python | huggingface__transformers | src/transformers/models/vipllava/modeling_vipllava.py | {
"start": 5828,
"end": 12731
} | class ____(VipLlavaPreTrainedModel):
_checkpoint_conversion_mapping = {
r"^language_model.model": "language_model",
}
def __init__(self, config: VipLlavaConfig):
super().__init__(config)
self.vision_tower = AutoModel.from_config(config.vision_config)
self.multi_modal_projec... | VipLlavaModel |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.