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 | encode__django-rest-framework | tests/test_model_serializer.py | {
"start": 3681,
"end": 3890
} | class ____(models.Model):
parent = models.ForeignKey(Issue3674ParentModel, related_name='children', on_delete=models.CASCADE)
value = models.CharField(primary_key=True, max_length=64)
| Issue3674ChildModel |
python | SmileyChris__easy-thumbnails | easy_thumbnails/apps.py | {
"start": 36,
"end": 159
} | class ____(AppConfig):
name = 'easy_thumbnails'
default_auto_field = 'django.db.models.AutoField'
| EasyThumbnailsConfig |
python | networkx__networkx | networkx/algorithms/tests/test_chordal.py | {
"start": 39,
"end": 4438
} | class ____:
@classmethod
def setup_class(cls):
# simple graph
connected_chordal_G = nx.Graph()
connected_chordal_G.add_edges_from(
[
(1, 2),
(1, 3),
(2, 3),
(2, 4),
(3, 4),
(3, 5),... | TestMCS |
python | joke2k__faker | faker/providers/automotive/en_GB/__init__.py | {
"start": 48,
"end": 322
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``en_GB`` locale.
Sources:
- https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_United_Kingdom
"""
license_formats = (
"??## ???",
"??##???",
)
| Provider |
python | django__django | tests/delete_regress/models.py | {
"start": 2893,
"end": 2978
} | class ____(models.Model):
my_file = models.ForeignKey(File, models.CASCADE)
| FooFile |
python | Textualize__textual | tests/option_list/test_option_prompt_replacement.py | {
"start": 223,
"end": 3245
} | class ____(App[None]):
"""Test option list application."""
def compose(self) -> ComposeResult:
yield OptionList(
Option("0", id="0"),
Option("line1\nline2"),
)
async def test_replace_option_prompt_with_invalid_id() -> None:
"""Attempting to replace the prompt of an... | OptionListApp |
python | joke2k__faker | tests/providers/test_internet.py | {
"start": 34547,
"end": 34856
} | class ____:
"""Test th_TH internet provider methods"""
def test_tld(self, faker):
tld = faker.tld()
assert tld in ThThInternetProvider.tlds
def test_slug(self, faker):
num_of_samples = 100
for _ in range(num_of_samples):
assert faker.slug() != ""
| TestThTh |
python | scikit-learn__scikit-learn | sklearn/linear_model/_ridge.py | {
"start": 99442,
"end": 107366
} | class ____(_RidgeClassifierMixin, _BaseRidgeCV):
"""Ridge classifier with built-in cross-validation.
See glossary entry for :term:`cross-validation estimator`.
By default, it performs Leave-One-Out Cross-Validation. Currently,
only the n_features > n_samples case is handled efficiently.
Read more... | RidgeClassifierCV |
python | skorch-dev__skorch | skorch/tests/test_doctor.py | {
"start": 148,
"end": 22074
} | class ____: # pylint: disable=too-many-public-methods
"""Test functionality of SkorchDoctor using a simple model"""
@pytest.fixture(scope='module')
def module_cls(self):
"""Return a simple module class with predictable parameters"""
class MyModule(nn.Module):
"""Module with pred... | TestSkorchDoctorSimple |
python | huggingface__transformers | src/transformers/models/dbrx/configuration_dbrx.py | {
"start": 2083,
"end": 4689
} | class ____(PreTrainedConfig):
"""Configuration class for Dbrx FFN.
[`DbrxFFN`] class. It is used to instantiate feedforward layers according to
the specified arguments, defining the layers architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model output... | DbrxFFNConfig |
python | bokeh__bokeh | src/bokeh/sphinxext/_internal/bokeh_autodoc.py | {
"start": 1960,
"end": 2418
} | class ____(ModuleLevelDocumenter):
directivetype = "bokeh-color"
objtype = ""
priority = 20
@classmethod
def can_document_member(cls, member, membername, isattr, parent):
return isinstance(member, Color)
# We don't need/want anything from the actual NamedColor class
def add_content... | ColorDocumenter |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 40908,
"end": 42865
} | class ____(Response):
"""
Response of events.debug_images endpoint.
:param metrics: Debug image events grouped by task metrics and iterations
:type metrics: Sequence[dict]
:param scroll_id: Scroll ID for getting more results
:type scroll_id: str
"""
_service = "events"
_action = "d... | DebugImagesResponse |
python | scipy__scipy | scipy/integrate/_quad_vec.py | {
"start": 662,
"end": 1402
} | class ____:
"""
Argument transform from (start, +-oo) to (0, 1)
"""
def __init__(self, func, start, infty):
self._func = func
self._start = start
self._sgn = -1 if infty < 0 else 1
# Overflow threshold for the 1/t**2 factor
self._tmin = sys.float_info.min**0.5
... | SemiInfiniteFunc |
python | google__jax | jax/_src/cache_key.py | {
"start": 1771,
"end": 12942
} | class ____(enum.IntEnum):
# Do not remove any callback pointers from precompiled IR.
NO = enum.auto()
# Remove all callback pointers from precompiled IR.
ALL = enum.auto()
# Remove only custom_partitioning callback pointer from precompiled IR.
CUSTOM_PARTITIONING = enum.auto()
def get(
module: ir.Modu... | IgnoreCallbacks |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_vision.py | {
"start": 39974,
"end": 41558
} | class ____(nn.Module):
"""
Pyramid Pooling Module (PPM) used in PSPNet.
Args:
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
Module.
in_channels (int): Input channels.
channels (int): Channels after modules, before conv_seg.
align_corners (bool)... | Data2VecVisionPyramidPoolingModule |
python | crytic__slither | slither/core/variables/local_variable_init_from_tuple.py | {
"start": 95,
"end": 693
} | class ____(LocalVariable):
"""
Use on this pattern:
var(a,b) = f()
It is not possible to split the variable declaration in sigleton and keep the init value
We init a and b with f(). get_tuple_index ret() returns which returns values of f is to be used
"""
def __init__(self) -> None:
... | LocalVariableInitFromTuple |
python | pypa__pip | src/pip/_vendor/rich/markup.py | {
"start": 453,
"end": 8451
} | class ____(NamedTuple):
"""A tag in console markup."""
name: str
"""The tag name. e.g. 'bold'."""
parameters: Optional[str]
"""Any additional parameters after the name."""
def __str__(self) -> str:
return (
self.name if self.parameters is None else f"{self.name} {self.param... | Tag |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/views/permissions.py | {
"start": 1613,
"end": 2328
} | class ____(PermissionViewModelView):
"""Customize permission names for FAB's builtin PermissionViewModelView."""
class_permission_name = permissions.RESOURCE_PERMISSION
route_base = "/permissions"
method_permission_name = {
"list": "read",
}
base_permissions = [
permissions.ACTI... | PermissionPairModelView |
python | ray-project__ray | python/ray/tune/search/basic_variant.py | {
"start": 1937,
"end": 6506
} | class ____:
"""Generates trials from the spec.
Args:
uuid_prefix: Used in creating the trial name.
num_samples: Number of samples from distribution
(same as tune.TuneConfig).
unresolved_spec: Experiment specification
that might have unresolved distributions.
... | _TrialIterator |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_shape_base_.py | {
"start": 17363,
"end": 18210
} | class ____(TestCase):
def test_non_iterable(self):
assert_raises(TypeError, column_stack, 1)
def test_1D_arrays(self):
# example from docstring
a = np.array((1, 2, 3))
b = np.array((2, 3, 4))
expected = np.array([[1, 2], [2, 3], [3, 4]])
actual = np.column_stack(... | TestColumnStack |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/types/python_set.py | {
"start": 2709,
"end": 2860
} | class ____:
def __getitem__(self, inner_type):
return create_typed_runtime_set(inner_type)
Set: DagsterSetApi = DagsterSetApi()
| DagsterSetApi |
python | pytorch__pytorch | test/inductor/test_loop_ordering.py | {
"start": 40441,
"end": 44835
} | class ____(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
gm = torch.fx.symbolic_trace(lambda: 0)
graph = GraphLowering(gm)
graph.scheduler = MockScheduler
cls._exit_stack = contextlib.ExitStack()
cls._exit_stack.enter_context(V.set_graph_handl... | TestIndexInversion |
python | redis__redis-py | redis/cache.py | {
"start": 3451,
"end": 6248
} | class ____(CacheInterface):
def __init__(
self,
cache_config: CacheConfigurationInterface,
) -> None:
self._cache = OrderedDict()
self._cache_config = cache_config
self._eviction_policy = self._cache_config.get_eviction_policy().value()
self._eviction_policy.cache... | DefaultCache |
python | scikit-learn__scikit-learn | sklearn/feature_selection/_univariate_selection.py | {
"start": 34099,
"end": 36823
} | class ____(_BaseFilter):
"""Filter: Select the p-values corresponding to Family-wise error rate.
Read more in the :ref:`User Guide <univariate_feature_selection>`.
Parameters
----------
score_func : callable, default=f_classif
Function taking two arrays X and y, and returning a pair of arr... | SelectFwe |
python | spyder-ide__spyder | spyder/plugins/editor/extensions/closequotes.py | {
"start": 1446,
"end": 4887
} | class ____(EditorExtension):
"""Editor Extension for insert closing quotes automatically."""
def on_state_changed(self, state):
"""Connect/disconnect sig_key_pressed signal."""
if state:
self.editor.sig_key_pressed.connect(self._on_key_pressed)
else:
self.editor.... | CloseQuotesExtension |
python | getsentry__sentry | tests/sentry/auth_v2/endpoints/test_csrf.py | {
"start": 270,
"end": 3391
} | class ____(APITestCase):
endpoint = "sentry-api-0-auth-v2-csrf"
def setUp(self) -> None:
super().setUp()
self.url = reverse(self.endpoint)
self.user = self.create_user()
def test_get_csrf_token_anonymous(self) -> None:
response = self.client.get(self.url, HTTP_X_SENTRY_AUTH... | CsrfTokenEndpointTest |
python | nedbat__coveragepy | tests/test_oddball.py | {
"start": 591,
"end": 1827
} | class ____(CoverageTest):
"""Tests of the threading support."""
def test_threading(self) -> None:
self.check_coverage(
"""\
import threading
def fromMainThread():
return "called from main thread"
def fromOtherThread():
re... | ThreadingTest |
python | cython__cython | Cython/Compiler/UtilityCode.py | {
"start": 11769,
"end": 14332
} | class ____(Code.AbstractUtilityCode):
def __init__(self, pxd_name, shared_utility_qualified_name, template_context, requires):
self._pxd_name = pxd_name
self._shared_utility_qualified_name = shared_utility_qualified_name
self.template_context = template_context
self.requires = requir... | CythonSharedUtilityCode |
python | google__pytype | pytype/pyi/parser_test.py | {
"start": 91511,
"end": 93989
} | class ____(parser_test_base.ParserTestBase):
"""Tests for typing.Self."""
def test_method_return(self):
self.check(
"""
from typing_extensions import Self
class A:
def f(self) -> Self: ...
""",
"""
from typing import TypeVar
from typing_extensions import S... | TypingSelfTest |
python | tensorflow__tensorflow | tensorflow/python/framework/py_context_manager_test.py | {
"start": 1820,
"end": 3745
} | class ____(test_util.TensorFlowTestCase):
def testBasic(self):
cm = TestContextManager()
def body(var):
cm.log.append("body(%r)" % var)
_py_context_manager.test_py_context_manager(cm, body)
self.assertEqual("\n".join(cm.log), NO_EXCEPTION_LOG)
def testBodyRaisesException(self):
cm = Te... | OpDefUtilTest |
python | Pylons__pyramid | docs/quick_tutorial/authentication/tutorial/views.py | {
"start": 271,
"end": 1718
} | class ____:
def __init__(self, request):
self.request = request
self.logged_in = request.authenticated_userid
@view_config(route_name='home')
def home(self):
return {'name': 'Home View'}
@view_config(route_name='hello')
def hello(self):
return {'name': 'Hello View'}... | TutorialViews |
python | great-expectations__great_expectations | great_expectations/render/renderer/content_block/validation_results_table_content_block.py | {
"start": 689,
"end": 11066
} | class ____(ExpectationStringRenderer):
_content_block_type = "table"
_rendered_component_type = RenderedTableContent
_rendered_component_default_init_kwargs = {"table_options": {"search": True, "icon-size": "sm"}}
_default_element_styling = {
"default": {"classes": ["badge", "badge-secondary"]}... | ValidationResultsTableContentBlockRenderer |
python | Textualize__textual | examples/sidebar.py | {
"start": 583,
"end": 1469
} | class ____(Widget):
"""
Our sidebar widget.
Add desired content to compose()
"""
DEFAULT_CSS = """
Sidebar {
width: 30;
/* Needs to go in its own layer to sit above content */
layer: sidebar;
/* Dock the sidebar to the appropriate side */
dock: left;
... | Sidebar |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/unit_tests/test_client.py | {
"start": 1601,
"end": 13802
} | class ____:
def test_limit_reached(self, mocker, requests_mock, api, fb_call_rate_response, account_id, some_config):
"""Error once, check that we retry and not fail"""
# turn Campaigns into non batch mode to test non batch logic
campaign_responses = [
fb_call_rate_response,
... | TestBackoff |
python | django__django | tests/model_regress/models.py | {
"start": 801,
"end": 869
} | class ____(models.Model):
when = models.DateField(null=True)
| Party |
python | wireservice__csvkit | tests/test_cli.py | {
"start": 92,
"end": 2749
} | class ____(unittest.TestCase):
def setUp(self):
self.headers = ['id', 'name', 'i_work_here', '1', 'more-header-values', 'stuff', 'blueberry']
def test_match_column_identifier_string(self):
self.assertEqual(2, match_column_identifier(self.headers, 'i_work_here'))
self.assertEqual(2, mat... | TestCli |
python | django__django | tests/file_storage/models.py | {
"start": 382,
"end": 774
} | class ____(FileSystemStorage):
def get_valid_name(self, name):
# mark the name to show that this was called
return name + "_valid"
temp_storage_location = tempfile.mkdtemp()
temp_storage = FileSystemStorage(location=temp_storage_location)
def callable_storage():
return temp_storage
def cal... | CustomValidNameStorage |
python | redis__redis-py | tests/test_asyncio/test_connection_pool.py | {
"start": 28215,
"end": 28504
} | class ____:
@pytest_asyncio.fixture()
async def r(self, create_redis, server):
redis = await create_redis(single_connection_client=False)
yield redis
await redis.flushall()
@pytest.mark.onlynoncluster
@pytest.mark.xfail(strict=False)
| TestMultiConnectionClient |
python | Pylons__pyramid | src/pyramid/scripts/pshell.py | {
"start": 689,
"end": 9504
} | class ____:
description = """\
Open an interactive shell with a Pyramid app loaded. This command
accepts one positional argument named "config_uri" which specifies the
PasteDeploy config file to use for the interactive shell. The format is
"inifile#name". If the name is left off, the Pyramid defaul... | PShellCommand |
python | keras-team__keras | keras/src/ops/einops_test.py | {
"start": 188,
"end": 2091
} | class ____(testing.TestCase):
def test_basic_rearrangement_symbolic(self):
x = keras_tensor.KerasTensor((2, 3, 4))
y = rearrange(x, "b c h -> b h c")
self.assertIsInstance(y, keras_tensor.KerasTensor)
self.assertEqual(y.shape, (2, 4, 3))
@skip_if_backend("openvino", "Test operat... | RearrangeTest |
python | mahmoud__boltons | boltons/tableutils.py | {
"start": 4259,
"end": 4622
} | class ____(InputType):
def check_type(self, obj):
return isinstance(obj, Mapping)
def guess_headers(self, obj):
return sorted(obj.keys())
def get_entry(self, obj, headers):
return [obj.get(h) for h in headers]
def get_entry_seq(self, obj, headers):
return [[ci.get(h) f... | DictInputType |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 123506,
"end": 128834
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True, arbitrary_types_allowed=True)
dbt_task: Optional[DbtTask] = Field(
None,
description=(
"If dbt_task, indicates that this must execute a dbt ... | JobTaskSettings |
python | ray-project__ray | python/ray/train/lint/check_circular_imports.py | {
"start": 1499,
"end": 1893
} | class ____:
"""
Represents an import statement.
For example, 'from X import A, B' has module 'X' and names ['A', 'B'].
Also supports 'import X'.
"""
def __init__(
self, module: str, names: List[str] = None, is_package: bool = False
) -> None:
self.is_package = is_package
... | Import |
python | FactoryBoy__factory_boy | factory/declarations.py | {
"start": 2729,
"end": 3222
} | class ____(BaseDeclaration):
"""Simplest BaseDeclaration computed by calling the given function.
Attributes:
function (function): a function without arguments and
returning the computed value.
"""
def __init__(self, function):
super().__init__()
self.function = func... | LazyFunction |
python | pikepdf__pikepdf | src/pikepdf/form.py | {
"start": 5828,
"end": 6812
} | class ____:
"""Base class for other field types.
In addition to the methods and properties documented here, all fields expose the
same properties and methods defined on `pikepdf.AcroFormField`. These are forwarded
to the underlying field object.
"""
def __init__(self, form: Form, field: AcroFo... | _FieldWrapper |
python | django__django | django/db/models/fields/__init__.py | {
"start": 76725,
"end": 77167
} | class ____(IntegerField):
description = _("Big (8 byte) integer")
MAX_BIGINT = 9223372036854775807
def get_internal_type(self):
return "BigIntegerField"
def formfield(self, **kwargs):
return super().formfield(
**{
"min_value": -BigIntegerField.MAX_BIGINT - 1... | BigIntegerField |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/random/multinomial_op_big_test.py | {
"start": 1036,
"end": 3514
} | class ____(test.TestCase):
# check that events with tiny probabilities are not over-sampled
def testLargeDynamicRange(self):
random_seed.set_random_seed(10)
counts_by_indices = {}
with self.test_session():
samples = random_ops.multinomial(
constant_op.constant([[-30, 0]], dtype=dtypes.f... | MultinomialTest |
python | walkccc__LeetCode | solutions/2652. Sum Multiples/2652.py | {
"start": 0,
"end": 182
} | class ____:
def sumOfMultiples(self, n: int) -> int:
ans = 0
for i in range(1, n + 1):
if i % 3 == 0 or i % 5 == 0 or i % 7 == 0:
ans += i
return ans
| Solution |
python | pandas-dev__pandas | pandas/tests/indexes/timedeltas/test_setops.py | {
"start": 243,
"end": 7956
} | class ____:
def test_union(self):
i1 = timedelta_range("1day", periods=5)
i2 = timedelta_range("3day", periods=5)
result = i1.union(i2)
expected = timedelta_range("1day", periods=7)
tm.assert_index_equal(result, expected)
i1 = Index(np.arange(0, 20, 2, dtype=np.int64... | TestTimedeltaIndex |
python | eventlet__eventlet | eventlet/event.py | {
"start": 192,
"end": 7496
} | class ____:
"""An abstraction where an arbitrary number of coroutines
can wait for one event from another.
Events are similar to a Queue that can only hold one item, but differ
in two important ways:
1. calling :meth:`send` never unschedules the current greenthread
2. :meth:`send` can only be ... | Event |
python | pola-rs__polars | py-polars/src/polars/datatype_expr/datatype_expr.py | {
"start": 981,
"end": 9667
} | class ____:
"""
A lazily instantiated :class:`DataType` that can be used in an :class:`Expr`.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
This expression is made to represent a :class:`DataTyp... | DataTypeExpr |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/types.py | {
"start": 5980,
"end": 7912
} | class ____(sqltypes.NativeForEmulated, sqltypes._AbstractInterval):
__visit_name__ = "INTERVAL"
def __init__(self, day_precision=None, second_precision=None):
"""Construct an INTERVAL.
Note that only DAY TO SECOND intervals are currently supported.
This is due to a lack of support for ... | INTERVAL |
python | huggingface__transformers | tests/models/glm46v/test_modeling_glm46v.py | {
"start": 1304,
"end": 6162
} | class ____:
def __init__(
self,
parent,
batch_size=3,
seq_length=7,
num_channels=3,
ignore_index=-100,
image_size=112,
video_start_token_id=3,
video_end_token_id=4,
image_start_token_id=5,
image_end_token_id=6,
image_tok... | Glm46VVisionText2TextModelTester |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/config.py | {
"start": 163,
"end": 1712
} | class ____:
def __init__(self) -> None:
self._subdomain: Optional[str] = None
self._start_date: Optional[str] = None
self._credentials: Dict[str, str] = {}
self._ignore_pagination: Optional[bool] = None
def with_subdomain(self, subdomain: str) -> "ConfigBuilder":
self._s... | ConfigBuilder |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-alloys.py | {
"start": 50,
"end": 1363
} | class ____(object):
def maxNumberOfAlloys(self, n, k, budget, composition, stock, cost):
"""
:type n: int
:type k: int
:type budget: int
:type composition: List[List[int]]
:type stock: List[int]
:type cost: List[int]
:rtype: int
"""
def... | Solution |
python | django-import-export__django-import-export | tests/core/tests/test_widgets.py | {
"start": 18337,
"end": 20214
} | class ____(TestCase, RowDeprecationTestMixin):
def setUp(self):
self.value = 0
self.widget = widgets.IntegerWidget()
self.bigintvalue = 163371428940853127
self.widget_coerce_to_string = widgets.IntegerWidget(coerce_to_string=True)
def test_clean_integer_zero(self):
self.... | IntegerWidgetTest |
python | ipython__ipython | IPython/core/interactiveshell.py | {
"start": 3788,
"end": 5555
} | class ____(DeprecationWarning):
"""
Warning class for unstable features
"""
pass
from ast import Module
_assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
_single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
#-----------------------------------------------------------------------------
# Aw... | ProvisionalWarning |
python | lazyprogrammer__machine_learning_examples | cnn_class2/tf_resnet_convblock_starter.py | {
"start": 354,
"end": 765
} | class ____:
def __init__(self):
pass
def predict(self, X):
pass
if __name__ == '__main__':
conv_block = ConvBlock()
# make a fake image
X = np.random.random((1, 224, 224, 3))
init = tf.global_variables_initializer()
with tf.Session() as session:
conv_block.session = session
session.r... | ConvBlock |
python | getsentry__sentry-python | sentry_sdk/utils.py | {
"start": 7927,
"end": 10301
} | class ____:
"""Represents a DSN."""
ORG_ID_REGEX = re.compile(r"^o(\d+)\.")
def __init__(self, value, org_id=None):
# type: (Union[Dsn, str], Optional[str]) -> None
if isinstance(value, Dsn):
self.__dict__ = dict(value.__dict__)
return
parts = urlsplit(str(v... | Dsn |
python | pytorch__pytorch | test/distributed/pipelining/test_stage.py | {
"start": 1540,
"end": 10127
} | class ____(MultiProcContinuousTest):
@classmethod
def backend_str(cls) -> str:
# Testing with NCCL backend
return backend
@classmethod
def device_type(cls) -> str:
return device_type
@property
def device(self) -> torch.device:
return torch.device(device_type, se... | StageTest |
python | eventlet__eventlet | eventlet/green/http/cookiejar.py | {
"start": 73886,
"end": 79435
} | class ____(FileCookieJar):
"""
WARNING: you may want to backup your browser's cookies file if you use
this class to save cookies. I *think* it works, but there have been
bugs in the past!
This class differs from CookieJar only in the format it uses to save and
load cookies to and from a file.... | MozillaCookieJar |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 15447,
"end": 15621
} | class ____(VegaLiteSchema):
"""Align schema wrapper."""
_schema = {"$ref": "#/definitions/Align"}
def __init__(self, *args):
super().__init__(*args)
| Align |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 639137,
"end": 639702
} | class ____(VegaLiteSchema):
"""
Locale schema wrapper.
Parameters
----------
number : dict, :class:`NumberLocale`
Locale definition for formatting numbers.
time : dict, :class:`TimeLocale`
Locale definition for formatting dates and times.
"""
_schema = {"$ref": "#/defin... | Locale |
python | ethereum__web3.py | web3/utils/subscriptions.py | {
"start": 8722,
"end": 9234
} | class ____(EthSubscription[SyncProgress]):
def __init__(
self,
label: str | None = None,
handler: SyncingSubscriptionHandler | None = None,
handler_context: dict[str, Any] | None = None,
parallelize: bool | None = None,
) -> None:
super().__init__(
sub... | SyncingSubscription |
python | keras-team__keras | keras/src/trainers/trainer_test.py | {
"start": 3210,
"end": 3770
} | class ____(Trainer, layers.Layer):
def __init__(self, units):
layers.Layer.__init__(self)
Trainer.__init__(self)
self.dense_1 = layers.Dense(
units,
use_bias=False,
kernel_initializer=initializers.Ones(),
)
self.dense_2 = layers.Dense(
... | ListInputModel |
python | viewflow__viewflow | tests/fsm/test_fsm__advanced.py | {
"start": 1328,
"end": 3373
} | class ____(TestCase): # noqa: D101
def test_no_target_transition(self):
publication = Publication(text="test")
publication.notify()
self.assertEqual(publication.stage, ReviewState.NEW)
def test_big_publication_process(self):
publication = Publication(text="test" * 251)
... | Test |
python | boto__boto3 | tests/integration/test_s3.py | {
"start": 5469,
"end": 9351
} | class ____(unittest.TestCase):
def setUp(self):
self.region = _DEFAULT_REGION
self.bucket_name = _SHARED_BUCKET
clear_out_bucket(self.bucket_name, self.region)
self.session = boto3.session.Session(region_name=self.region)
self.s3 = self.session.resource('s3')
self.buc... | TestS3Resource |
python | mlflow__mlflow | mlflow/store/tracking/dbmodels/models.py | {
"start": 26391,
"end": 27421
} | class ____(Base):
__tablename__ = "trace_request_metadata"
key = Column(String(250))
"""
Metadata key: `String` (limit 250 characters).
"""
value = Column(String(8000), nullable=True)
"""
Value associated with metadata: `String` (limit 250 characters). Could be *null*.
"""
reque... | SqlTraceMetadata |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 280203,
"end": 293264
} | class ____(CallNode):
# Specialised call to a (potential) PyMethodObject with non-constant argument tuple.
# Allows the self argument to be injected directly instead of repacking a tuple for it.
#
# function ExprNode the function/method object to call
# arg_tuple TupleNode the argument... | PyMethodCallNode |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass6.py | {
"start": 316,
"end": 664
} | class ____:
prop_1: str = field(init=False)
prop_2: str = field(default="hello")
prop_3: str = field(default_factory=lambda: "hello")
# This should generate an error because it appears after
# a property with a default value.
prop_4: str = field()
def __post_init__(self):
self.prop... | ParentA |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 261899,
"end": 267413
} | class ____:
@pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning:dask")
@pytest.mark.filterwarnings("ignore:divide by zero encountered:RuntimeWarning:dask")
def test_describe_scalar(self, xp):
with warnings.catch_warnings(), \
np.errstate(invalid="ignore", divid... | TestDescribe |
python | ray-project__ray | rllib/examples/curriculum/curriculum_learning.py | {
"start": 5309,
"end": 9246
} | class ____(RLlibCallback):
"""Custom callback implementing `on_train_result()` for changing the envs' maps."""
def on_algorithm_init(
self,
*,
algorithm: "Algorithm",
**kwargs,
) -> None:
# Set the initial task to 0.
algorithm._counters["current_env_task"] = ... | EnvTaskCallback |
python | walkccc__LeetCode | solutions/1833. Maximum Ice Cream Bars/1833.py | {
"start": 0,
"end": 221
} | class ____:
def maxIceCream(self, costs: list[int], coins: int) -> int:
for i, cost in enumerate(sorted(costs)):
if coins >= cost:
coins -= cost
else:
return i
return len(costs)
| Solution |
python | mamba-org__mamba | micromamba/tests/test_install.py | {
"start": 263,
"end": 35264
} | class ____:
current_root_prefix = os.environ["MAMBA_ROOT_PREFIX"]
current_prefix = os.environ["CONDA_PREFIX"]
env_name = helpers.random_string()
root_prefix = os.path.expanduser(os.path.join("~", "tmproot" + helpers.random_string()))
prefix = os.path.join(root_prefix, "envs", env_name)
@classm... | TestInstall |
python | tiangolo__fastapi | docs_src/query_param_models/tutorial002_an.py | {
"start": 166,
"end": 518
} | class ____(BaseModel):
model_config = {"extra": "forbid"}
limit: int = Field(100, gt=0, le=100)
offset: int = Field(0, ge=0)
order_by: Literal["created_at", "updated_at"] = "created_at"
tags: List[str] = []
@app.get("/items/")
async def read_items(filter_query: Annotated[FilterParams, Query()]):
... | FilterParams |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 17053,
"end": 17533
} | class ____(django_test.TestCase):
def test_build(self):
u = WithPasswordFactory.build()
self.assertTrue(check_password(PASSWORD, u.pw))
def test_build_with_kwargs(self):
password = 'V3R¥.S€C®€T'
u = WithPasswordFactory.build(pw=password)
self.assertTrue(check_password(pa... | DjangoPasswordTestCase |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_kubernetes_engine.py | {
"start": 14074,
"end": 23493
} | class ____:
def setup_method(self):
self.operator = GKECreateClusterOperator(
task_id=TEST_TASK_ID,
project_id=TEST_PROJECT_ID,
location=TEST_LOCATION,
body=GKE_CLUSTER_CREATE_BODY_DICT,
gcp_conn_id=TEST_CONN_ID,
impersonation_chain=TES... | TestGKECreateClusterOperator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constrainedTypeVar18.py | {
"start": 317,
"end": 387
} | class ____:
def fn(self, returnable: T1) -> Awaitable[T1]: ...
| Async |
python | django__django | tests/db_functions/math/test_asin.py | {
"start": 269,
"end": 2344
} | class ____(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = IntegerModel.objects.annotate(null_asin=ASin("normal")).first()
self.assertIsNone(obj.null_asin)
def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("0.9"), n2=Decimal("0.6"))
obj =... | ASinTests |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1067639,
"end": 1068829
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'base_ref_force_pushed' event on a given pull
request.
"""
__schema__ = github_schema
__field_names__ = ("actor", "after_commit", "before_commit", "created_at", "pull_request", "ref")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
... | BaseRefForcePushedEvent |
python | pappasam__jedi-language-server | tests/test_data/completion/completion_test_class_self.py | {
"start": 0,
"end": 131
} | class ____:
def some_method(self, x):
"""Great method."""
return x
instance = SomeClass()
instance.some
| SomeClass |
python | chroma-core__chroma | chromadb/types.py | {
"start": 9308,
"end": 9444
} | class ____(TypedDict):
"""A KNN/ANN query result"""
id: str
distance: float
embedding: Optional[Vector]
| VectorQueryResult |
python | Pylons__pyramid | tests/test_exceptions.py | {
"start": 1165,
"end": 1797
} | class ____(unittest.TestCase):
def _makeOne(self, message):
from pyramid.exceptions import NotFound
return NotFound(message)
def test_it(self):
from pyramid.interfaces import IExceptionResponse
e = self._makeOne('notfound')
self.assertTrue(IExceptionResponse.providedBy... | TestNotFound |
python | getsentry__sentry | tests/sentry/integrations/bitbucket/test_installed.py | {
"start": 923,
"end": 10160
} | class ____(APITestCase):
def setUp(self) -> None:
self.provider = "bitbucket"
self.path = "/extensions/bitbucket/installed/"
self.username = "sentryuser"
self.client_key = "connection:123"
self.public_key = "123abcDEFg"
self.shared_secret = "G12332434SDfsjkdfgsd"
... | BitbucketInstalledEndpointTest |
python | kamyu104__LeetCode-Solutions | Python/find-center-of-star-graph.py | {
"start": 29,
"end": 216
} | class ____(object):
def findCenter(self, edges):
"""
:type edges: List[List[int]]
:rtype: int
"""
return edges[0][edges[0][1] in edges[1]]
| Solution |
python | openai__openai-python | src/openai/types/batch_usage.py | {
"start": 521,
"end": 938
} | class ____(BaseModel):
input_tokens: int
"""The number of input tokens."""
input_tokens_details: InputTokensDetails
"""A detailed breakdown of the input tokens."""
output_tokens: int
"""The number of output tokens."""
output_tokens_details: OutputTokensDetails
"""A detailed breakdown ... | BatchUsage |
python | vyperlang__vyper | tests/functional/grammar/test_grammar.py | {
"start": 1247,
"end": 3352
} | class ____(LarkStrategy):
def __init__(self, grammar, start, explicit_strategies):
super().__init__(grammar, start, explicit_strategies, alphabet=ALLOWED_CHARS)
self.terminal_strategies = {
k: v.map(fix_terminal) for k, v in self.terminal_strategies.items() # type: ignore
}
... | GrammarStrategy |
python | django__django | django/utils/feedgenerator.py | {
"start": 8496,
"end": 8728
} | class ____:
"""An RSS enclosure"""
def __init__(self, url, length, mime_type):
"All args are expected to be strings"
self.length, self.mime_type = length, mime_type
self.url = iri_to_uri(url)
| Enclosure |
python | django-guardian__django-guardian | guardian/testapp/models.py | {
"start": 3532,
"end": 3636
} | class ____(AbstractUser, GuardianUserMixin):
custom_id = models.AutoField(primary_key=True)
| CustomUser |
python | django__django | tests/cache/failing_cache.py | {
"start": 60,
"end": 290
} | class ____(LocMemCache):
def set(self, *args, **kwargs):
raise Exception("Faked exception saving to cache")
async def aset(self, *args, **kwargs):
raise Exception("Faked exception saving to cache")
| CacheClass |
python | doocs__leetcode | solution/0200-0299/0296.Best Meeting Point/Solution.py | {
"start": 0,
"end": 474
} | class ____:
def minTotalDistance(self, grid: List[List[int]]) -> int:
def f(arr, x):
return sum(abs(v - x) for v in arr)
rows, cols = [], []
for i, row in enumerate(grid):
for j, v in enumerate(row):
if v:
rows.append(i)
... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py | {
"start": 10487,
"end": 10889
} | class ____(RawDataMixin, IncrementalAppsflyerStream):
cursor_field = "event_time"
additional_fields = additional_fields.uninstall_events
def path(
self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None
) -> str:
re... | UninstallEvents |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-code-hierarchy/llama_index/packs/code_hierarchy/query_engine.py | {
"start": 777,
"end": 6172
} | class ____(CustomQueryEngine):
"""A keyword table made specifically to work with the code hierarchy node parser."""
nodes: Sequence[BaseNode]
node_dict: Optional[Dict[str, Tuple[int, BaseNode]]] = None
repo_map_depth: int = -1
include_repo_map: bool = True
repo_map: Optional[Tuple[Dict[str, Any... | CodeHierarchyKeywordQueryEngine |
python | mlflow__mlflow | mlflow/data/evaluation_dataset_source.py | {
"start": 79,
"end": 1797
} | class ____(DatasetSource):
"""
Represents the source of an evaluation dataset stored in MLflow's tracking store.
"""
def __init__(self, dataset_id: str):
"""
Args:
dataset_id: The ID of the evaluation dataset.
"""
self._dataset_id = dataset_id
@staticmet... | EvaluationDatasetSource |
python | kamyu104__LeetCode-Solutions | Python/maximum-length-substring-with-two-occurrences.py | {
"start": 754,
"end": 1227
} | class ____(object):
def maximumLengthSubstring(self, s):
"""
:type s: str
:rtype: int
"""
COUNT = 2
result = 0
cnt = [0]*26
left = 0
for right, x in enumerate(s):
cnt[ord(x)-ord('a')] += 1
while cnt[ord(x)-ord('a')] > CO... | Solution2 |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_eks.py | {
"start": 2675,
"end": 2763
} | class ____(TypedDict):
nodegroup_name: str
nodegroup_role_arn: str
| NodeGroupParams |
python | catalyst-team__catalyst | catalyst/contrib/datasets/imagecar.py | {
"start": 1169,
"end": 4023
} | class ____(Dataset):
"""
The dataset contains images of cars and the corresponding binary masks for them
"""
def __init__(
self,
root: str,
train: bool = True,
download: bool = False,
transforms: Optional[Callable] = None,
):
"""
Args:
... | CarvanaOneCarDataset |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/conv.py | {
"start": 967,
"end": 12078
} | class ____(WeightedQuantizedModule):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
bias=True,
padding_mode="zeros",
device=None,
dtype=None,
):
# All s... | _ConvNd |
python | marshmallow-code__marshmallow | tests/test_deserialization.py | {
"start": 939,
"end": 2493
} | class ____:
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
def test_fields_allow_none_deserialize_to_none(self, FieldClass):
field = FieldClass(allow_none=True)
assert field.deserialize(None) is None
# https://github.com/marshmallow-code/marshmallow/issues/111
@pytest.mark.parametri... | TestDeserializingNone |
python | Lightning-AI__lightning | src/lightning/pytorch/demos/boring_classes.py | {
"start": 1979,
"end": 2340
} | class ____(IterableDataset):
"""
.. warning:: This is meant for testing/debugging and is experimental.
"""
def __init__(self, size: int, count: int):
self.count = count
self.size = size
def __iter__(self) -> Iterator[Tensor]:
for _ in range(self.count):
yield t... | RandomIterableDataset |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.