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 | ray-project__ray | python/ray/data/_internal/output_buffer.py | {
"start": 319,
"end": 1805
} | class ____:
target_max_block_size: Optional[int] = None
target_num_rows_per_block: Optional[int] = None
disable_block_shaping: bool = False
def __post_init__(self):
if (
self.target_max_block_size is None
and self.target_num_rows_per_block is None
and not sel... | OutputBlockSizeOption |
python | tensorflow__tensorflow | tensorflow/python/ops/parsing_config.py | {
"start": 1933,
"end": 2158
} | class ____(collections.namedtuple("VarLenFeature", ["dtype"])):
"""Configuration for parsing a variable-length input feature.
Fields:
dtype: Data type of input.
"""
pass
@tf_export("io.RaggedFeature")
| VarLenFeature |
python | mlflow__mlflow | dev/clint/src/clint/rules/os_environ_set_in_test.py | {
"start": 84,
"end": 700
} | class ____(Rule):
def _message(self) -> str:
return "Do not set `os.environ` in test directly. Use `monkeypatch.setenv` (https://docs.pytest.org/en/stable/reference/reference.html#pytest.MonkeyPatch.setenv)."
@staticmethod
def check(node: ast.Assign, resolver: Resolver) -> bool:
"""
... | OsEnvironSetInTest |
python | getsentry__sentry | src/sentry/issues/services/issue/impl.py | {
"start": 637,
"end": 4037
} | class ____(IssueService):
def get_external_issue_groups(
self, *, region_name: str, external_issue_key: str, integration_id: int
) -> list[RpcExternalIssueGroupMetadata] | None:
from sentry.integrations.services.integration import integration_service
external_issues = ExternalIssue.obje... | DatabaseBackedIssueService |
python | arrow-py__arrow | arrow/locales.py | {
"start": 95164,
"end": 96475
} | class ____(Locale):
names = ["rm", "rm-ch"]
past = "avant {0}"
future = "en {0}"
timeframes = {
"now": "en quest mument",
"second": "in secunda",
"seconds": "{0} secundas",
"minute": "ina minuta",
"minutes": "{0} minutas",
"hour": "in'ura",
"hour... | RomanshLocale |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/supervised_learning/support_vector_machine.py | {
"start": 308,
"end": 4024
} | class ____(object):
"""The Support Vector Machine classifier.
Uses cvxopt to solve the quadratic optimization problem.
Parameters:
-----------
C: float
Penalty term.
kernel: function
Kernel function. Can be either polynomial, rbf or linear.
power: int
The degree of t... | SupportVectorMachine |
python | getsentry__sentry | src/sentry/integrations/example/integration.py | {
"start": 8981,
"end": 9175
} | class ____(ExampleIntegrationProvider):
key = "alert_rule_integration"
name = "Alert Rule Integration"
features = frozenset([IntegrationFeatures.ALERT_RULE])
| AlertRuleIntegrationProvider |
python | doocs__leetcode | solution/3000-3099/3017.Count the Number of Houses at a Certain Distance II/Solution.py | {
"start": 0,
"end": 1441
} | class ____:
def countOfPairs(self, n: int, x: int, y: int) -> List[int]:
if abs(x - y) <= 1:
return [2 * x for x in reversed(range(n))]
cycle_len = abs(x - y) + 1
n2 = n - cycle_len + 2
res = [2 * x for x in reversed(range(n2))]
while len(res) < n:
res... | Solution |
python | bokeh__bokeh | src/bokeh/models/sources.py | {
"start": 4591,
"end": 29035
} | class ____(ColumnarDataSource):
''' Maps names of columns to sequences or arrays.
The ``ColumnDataSource`` is a fundamental data structure of Bokeh. Most
plots, data tables, etc. will be driven by a ``ColumnDataSource``.
If the ``ColumnDataSource`` initializer is called with a single argument that
... | ColumnDataSource |
python | django__django | tests/template_tests/filter_tests/test_chaining.py | {
"start": 114,
"end": 4418
} | class ____(SimpleTestCase):
"""
Chaining safeness-preserving filters should not alter the safe status.
"""
@setup({"chaining01": '{{ a|capfirst|center:"7" }}.{{ b|capfirst|center:"7" }}'})
def test_chaining01(self):
output = self.engine.render_to_string(
"chaining01", {"a": "a <... | ChainingTests |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_batch.py | {
"start": 1704,
"end": 10244
} | class ____:
# set up the test environment
@pytest.fixture(autouse=True)
def setup_test_cases(self, mocked_batch_service_client, create_mock_connections):
# set up mocked Azure Batch client
self.batch_client = mock.MagicMock(name="FakeBatchServiceClient")
mocked_batch_service_client.r... | TestAzureBatchOperator |
python | pytorch__pytorch | torch/fx/_lazy_graph_module.py | {
"start": 1841,
"end": 6855
} | class ____(GraphModule):
"""
The main difference between _LazyGraphModule and GraphModule is how recompile happens.
GraphModule will do a 'recompile' call to generate python code and the forward method when it's
constructed. Later on if the graph get updated, recompile method can be called again to refr... | _LazyGraphModule |
python | scrapy__scrapy | tests/test_engine.py | {
"start": 2752,
"end": 2813
} | class ____(MySpider):
item_cls = AttrsItem
| AttrsItemsSpider |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_mcp_tool_use_block_param.py | {
"start": 338,
"end": 723
} | class ____(TypedDict, total=False):
id: Required[str]
input: Required[Dict[str, object]]
name: Required[str]
server_name: Required[str]
"""The name of the MCP server"""
type: Required[Literal["mcp_tool_use"]]
cache_control: Optional[BetaCacheControlEphemeralParam]
"""Create a cache ... | BetaMCPToolUseBlockParam |
python | kamyu104__LeetCode-Solutions | Python/minimize-maximum-value-in-a-grid.py | {
"start": 67,
"end": 530
} | class ____(object):
def minScore(self, grid):
"""
:type grid: List[List[int]]
:rtype: List[List[int]]
"""
idxs = [(i, j) for i in xrange(len(grid)) for j in xrange(len(grid[0]))]
idxs.sort(key=lambda x: grid[x[0]][x[1]])
row_max, col_max = [0]*len(grid), [0]*l... | Solution |
python | spyder-ide__spyder | spyder/widgets/comboboxes.py | {
"start": 11598,
"end": 12271
} | class ____(PathComboBox):
"""
QComboBox handling urls
"""
def __init__(self, parent, adjust_to_contents=False, id_=None):
if not PYSIDE2:
super().__init__(parent, adjust_to_contents)
else:
PathComboBox.__init__(self, parent, adjust_to_contents)
line_edit ... | UrlComboBox |
python | getsentry__sentry | tests/sentry/monitors/processing_errors/test_manager.py | {
"start": 984,
"end": 10611
} | class ____(TestCase):
def test_store_with_monitor(self) -> None:
monitor = self.create_monitor()
processing_error = build_checkin_processing_error()
store_error(processing_error, monitor)
fetched_processing_error = get_errors_for_monitor(monitor)
assert len(fetched_processing... | CheckinProcessErrorsManagerTest |
python | pytorch__pytorch | torch/_inductor/triton_bundler.py | {
"start": 1903,
"end": 2108
} | class ____:
"""
Metadata used for instrumentation
"""
cached_kernel_names: list[str]
statically_launched_kernel_names: list[str]
@dataclasses.dataclass(frozen=True)
| TritonBundlerMetadata |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_function_base.py | {
"start": 41380,
"end": 42120
} | class ____(TestCase):
def test_basic(self):
x = [
1 + 3j,
np.sqrt(2) / 2.0 + 1j * np.sqrt(2) / 2,
1,
1j,
-1,
-1j,
1 - 3j,
-1 + 3j,
]
y = angle(x)
yo = [
np.arctan(3.0 / 1.0),
... | TestAngle |
python | facelessuser__pymdown-extensions | pymdownx/blocks/admonition.py | {
"start": 185,
"end": 2138
} | class ____(Block):
"""
Admonition.
Arguments (1 optional):
- A title.
Options:
- `type` (string): Attach a single special class for styling purposes. If more are needed,
use the built-in `attributes` options to apply as many classes as desired.
Content:
Detail body.
"""
... | Admonition |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor27.py | {
"start": 557,
"end": 884
} | class ____(ClassB[S, T]):
def __new__(cls, subcon: ClassA[S]) -> ClassD[S, list[S]]: ...
c = ClassA[int]()
intermediate = ClassC(c)
v1 = ClassD(intermediate)
reveal_type(v1, expected_text="ClassD[list[int], list[list[int]]]")
v2 = ClassD(ClassC(c))
reveal_type(v2, expected_text="ClassD[list[int], list[list[int]... | ClassD |
python | milvus-io__pymilvus | tests/test_bulk_writer_buffer.py | {
"start": 397,
"end": 14540
} | class ____:
@pytest.fixture
def simple_schema(self):
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=False),
FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=128),
FieldSchema(name="text", dtype=DataType.VARCHAR, max_length=... | TestBuffer |
python | facelessuser__soupsieve | tests/test_api.py | {
"start": 17595,
"end": 19398
} | class ____(util.TestCase):
"""Test reporting of syntax errors."""
def test_syntax_error_has_text_and_position(self):
"""Test that selector syntax errors contain the position."""
with self.assertRaises(sv.SelectorSyntaxError) as cm:
sv.compile('input.field[type=42]')
e = cm.... | TestSyntaxErrorReporting |
python | scipy__scipy | scipy/stats/_resampling.py | {
"start": 42581,
"end": 57651
} | class ____:
"""Result object returned by `scipy.stats.power`.
Attributes
----------
power : float or ndarray
The estimated power.
pvalues : float or ndarray
The simulated p-values.
"""
power: float | np.ndarray
pvalues: float | np.ndarray
def _wrap_kwargs(fun):
"""... | PowerResult |
python | django-guardian__django-guardian | guardian/testapp/tests/test_core.py | {
"start": 928,
"end": 1244
} | class ____(TestCase):
def test_create_anonymous_user(self):
create_anonymous_user(object(), using="default")
self.assertEqual(1, User.objects.all().count())
anonymous = User.objects.all()[0]
self.assertEqual(anonymous.username, guardian_settings.ANONYMOUS_USER_NAME)
| CustomUserTests |
python | encode__starlette | tests/test_endpoints.py | {
"start": 381,
"end": 5780
} | class ____(HTTPEndpoint):
async def get(self, request: Request) -> PlainTextResponse:
username = request.path_params.get("username")
if username is None:
return PlainTextResponse("Hello, world!")
return PlainTextResponse(f"Hello, {username}!")
app = Router(routes=[Route("/", en... | Homepage |
python | getsentry__sentry | src/sentry/notifications/platform/discord/provider.py | {
"start": 4518,
"end": 5728
} | class ____(NotificationProvider[DiscordRenderable]):
key = NotificationProviderKey.DISCORD
default_renderer = DiscordRenderer
target_class = IntegrationNotificationTarget
target_resource_types = [
NotificationTargetResourceType.CHANNEL,
NotificationTargetResourceType.DIRECT_MESSAGE,
... | DiscordNotificationProvider |
python | getsentry__sentry | src/sentry/analytics/events/plugin_enabled.py | {
"start": 71,
"end": 240
} | class ____(analytics.Event):
user_id: int | None
organization_id: int
project_id: int
plugin: str
analytics.register(PluginEnabledEvent)
| PluginEnabledEvent |
python | lazyprogrammer__machine_learning_examples | rl2/mountaincar/q_learning.py | {
"start": 2489,
"end": 6463
} | class ____:
def __init__(self, env, feature_transformer, learning_rate):
self.env = env
self.models = []
self.feature_transformer = feature_transformer
for i in range(env.action_space.n):
model = SGDRegressor(learning_rate=learning_rate)
model.partial_fit(feature_transformer.transform( [en... | Model |
python | cherrypy__cherrypy | cherrypy/scaffold/__init__.py | {
"start": 589,
"end": 2015
} | class ____:
"""Declaration of the CherryPy app URI structure."""
@cherrypy.expose
def index(self):
"""Render HTML-template at the root path of the web-app."""
return """<html>
<body>Try some <a href='%s?a=7'>other</a> path,
or a <a href='%s?n=14'>default</a> path.<br />
Or, just look at the... | Root |
python | huggingface__transformers | src/transformers/models/mimi/modeling_mimi.py | {
"start": 17015,
"end": 18560
} | class ____(nn.Module):
"""
Residual block from SEANet model as used by Mimi.
"""
def __init__(self, config: MimiConfig, dim: int, dilations: list[int]):
super().__init__()
kernel_sizes = (config.residual_kernel_size, 1)
if len(kernel_sizes) != len(dilations):
raise V... | MimiResnetBlock |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_estimator_checks.py | {
"start": 8431,
"end": 9174
} | class ____(BaseBadClassifier):
def __init__(self, class_weight=None):
self.class_weight = class_weight
def fit(self, X, y):
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import compute_class_weight
label_encoder = LabelEncoder().fit(y)
classes = labe... | BadBalancedWeightsClassifier |
python | yaml__pyyaml | lib/yaml/__init__.py | {
"start": 10922,
"end": 11507
} | class ____(type):
"""
The metaclass for YAMLObject.
"""
def __init__(cls, name, bases, kwds):
super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds)
if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None:
if isinstance(cls.yaml_loader, list):
for loader i... | YAMLObjectMetaclass |
python | python-markdown__markdown | markdown/inlinepatterns.py | {
"start": 8012,
"end": 8250
} | class ____(NamedTuple):
"""Emphasis/strong pattern item."""
pattern: re.Pattern[str]
builder: str
tags: str
# The pattern classes
# -----------------------------------------------------------------------------
| EmStrongItem |
python | Lightning-AI__lightning | src/lightning/fabric/plugins/collectives/torch_collective.py | {
"start": 492,
"end": 8796
} | class ____(Collective):
"""Collective operations using `torch.distributed <https://pytorch.org/docs/stable/distributed.html>`__.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature which is still in development.
"""
manages_default_group = False
addr_key = "MASTER_AD... | TorchCollective |
python | realpython__materials | solid-principles-python/app_dip.py | {
"start": 810,
"end": 892
} | class ____(DataSource):
def get_data(self):
return "Data from the API"
| API |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 343116,
"end": 343317
} | class ____(VegaLiteSchema):
"""ErrorBarExtent schema wrapper."""
_schema = {"$ref": "#/definitions/ErrorBarExtent"}
def __init__(self, *args):
super().__init__(*args)
| ErrorBarExtent |
python | huggingface__transformers | src/transformers/models/canine/modeling_canine.py | {
"start": 23701,
"end": 24336
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forwa... | CanineOutput |
python | kevin1024__vcrpy | vcr/stubs/__init__.py | {
"start": 346,
"end": 1464
} | class ____:
"""
A socket that doesn't do anything!
Used when playing back cassettes, when there
is no actual open socket.
"""
def close(self):
pass
def settimeout(self, *args, **kwargs):
pass
def fileno(self):
"""
This is kinda crappy. requests will wa... | VCRFakeSocket |
python | wandb__wandb | wandb/vendor/pygments/lexers/csound.py | {
"start": 770,
"end": 3055
} | class ____(RegexLexer):
# Subclasses must define a 'single-line string' state.
tokens = {
'whitespace': [
(r'[ \t]+', Text),
(r'\\\n', Text),
(r'/[*](.|\n)*?[*]/', Comment.Multiline)
],
'macro call': [
(r'(\$\w+\.?)(\()', bygroups(Comment.... | CsoundLexer |
python | PyCQA__pylint | tests/functional/s/super/super_init_not_called.py | {
"start": 1581,
"end": 1691
} | class ____:
def __init__(self, param: int, param_two: str) -> None:
raise NotImplementedError()
| Base |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/supervised_learning/multi_class_lda.py | {
"start": 185,
"end": 2627
} | class ____():
"""Enables dimensionality reduction for multiple
class distributions. It transforms the features space into a space where
the between class scatter is maximized and the within class scatter is
minimized.
Parameters:
-----------
solver: str
If 'svd' we use the pseudo-in... | MultiClassLDA |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_organization_group_search_view_details_starred.py | {
"start": 239,
"end": 7449
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-group-search-view-starred"
method = "post"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.org = self.create_organization(owner=self.user)
def get_url(self, view_id: int) -> str:
... | OrganizationGroupSearchViewDetailsStarredEndpointTest |
python | walkccc__LeetCode | solutions/1122. Relative Sort Array/1122.py | {
"start": 0,
"end": 363
} | class ____:
def relativeSortArray(self, arr1: list[int], arr2: list[int]) -> list[int]:
ans = []
count = [0] * 1001
for a in arr1:
count[a] += 1
for a in arr2:
while count[a] > 0:
ans.append(a)
count[a] -= 1
for num in range(1001):
for _ in range(count[num]):
... | Solution |
python | SmileyChris__easy-thumbnails | easy_thumbnails/tests/utils.py | {
"start": 369,
"end": 1285
} | class ____(FileSystemStorage):
"""
A storage class useful for tests that uses a temporary location to store
all files and provides a method to remove this location when it is finished
with.
"""
def __init__(self, location=None, *args, **kwargs):
"""
Create the temporary location... | TemporaryStorage |
python | tornadoweb__tornado | tornado/test/asyncio_test.py | {
"start": 4070,
"end": 5584
} | class ____(unittest.TestCase):
def setUp(self):
# Trigger a cleanup of the mapping so we start with a clean slate.
AsyncIOLoop(make_current=False).close()
def tearDown(self):
try:
loop = asyncio.get_event_loop_policy().get_event_loop()
except Exception:
#... | LeakTest |
python | pytorch__pytorch | torch/_higher_order_ops/scan.py | {
"start": 8312,
"end": 15558
} | class ____(HigherOrderOperator):
def __init__(self):
super().__init__("scan")
def __call__(self, combine_fn, init, xs, additional_inputs):
# There is currently an issue that the ScanOp is sometimes called with
# the additional_inputs being a list. See https://github.com/pytorch/pytorch/... | ScanOp |
python | lepture__authlib | authlib/integrations/requests_client/assertion_session.py | {
"start": 217,
"end": 446
} | class ____(OAuth2Auth):
def ensure_active_token(self):
if self.client and (
not self.token or self.token.is_expired(self.client.leeway)
):
return self.client.refresh_token()
| AssertionAuth |
python | huggingface__transformers | src/transformers/models/omdet_turbo/modeling_omdet_turbo.py | {
"start": 28782,
"end": 37020
} | class ____(nn.Module):
"""
Encoder consisting of channel projection layers, a set of `OmDetTurboEncoder`, a top-down Feature Pyramid Network
(FPN) and a bottom-up Path Aggregation Network (PAN). More details on the paper: https://huggingface.co/papers/2304.08069
Args:
config: OmDetTurboConfig
... | OmDetTurboHybridEncoder |
python | sqlalchemy__sqlalchemy | test/orm/test_syntax_extensions.py | {
"start": 2212,
"end": 2589
} | class ____(PostCriteriaClause):
_traverse_internals: _TraverseInternalsType = [
("exprs", InternalTraversal.dp_clauseelement_tuple),
]
def __init__(self, *exprs: _ColumnExpressionArgument[Any]):
self.exprs = tuple(
coercions.expect(roles.ByOfRole, e, apply_propagate_attrs=self)
... | PostCriteriaClauseCols |
python | kamyu104__LeetCode-Solutions | Python/count-islands-with-total-value-divisible-by-k.py | {
"start": 55,
"end": 1032
} | class ____(object):
def countIslands(self, grid, k):
"""
:type grid: List[List[int]]
:type k: int
:rtype: int
"""
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
def bfs(i, j):
if not grid[i][j]:
return False
total = gri... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_gradient12.py | {
"start": 315,
"end": 1549
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_gradient12.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.... | TestCompareXLSXFiles |
python | pydantic__pydantic | pydantic/types.py | {
"start": 56342,
"end": 57603
} | class ____(_SecretField[bytes]):
"""A bytes used for storing sensitive information that you do not want to be visible in logging or tracebacks.
It displays `b'**********'` instead of the string value on `repr()` and `str()` calls.
When the secret value is nonempty, it is displayed as `b'**********'` instea... | SecretBytes |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/linux/mkl/set-build-env.py | {
"start": 3993,
"end": 4454
} | class ____(IntelPlatform):
def __init__(self):
IntelPlatform.__init__(self, 4, 8)
def get_bazel_gcc_flags(self):
SANDYBRIDGE_ARCH_OLD = "corei7-avx"
SANDYBRIDGE_ARCH_NEW = "sandybridge"
if self.use_old_arch_names(4, 9):
return self.BAZEL_PREFIX_ + self.ARCH_PREFIX_ + \
SANDYBRID... | SandyBridgePlatform |
python | run-llama__llama_index | llama-index-core/llama_index/core/vector_stores/types.py | {
"start": 664,
"end": 864
} | class ____:
"""Vector store query result."""
nodes: Optional[Sequence[BaseNode]] = None
similarities: Optional[List[float]] = None
ids: Optional[List[str]] = None
| VectorStoreQueryResult |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_sagemaker_unified_studio.py | {
"start": 1142,
"end": 7580
} | class ____:
def test_init(self):
operator = SageMakerNotebookOperator(
task_id="test_id",
input_config={
"notebook_path": "tests/amazon/aws/operators/test_notebook.ipynb",
},
output_config={"output_format": "ipynb"},
)
assert o... | TestSageMakerNotebookOperator |
python | pytorch__pytorch | torch/package/_package_pickler.py | {
"start": 432,
"end": 752
} | class ____(_Pickler):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._persistent_id = None
def persistent_id(self, obj):
if self._persistent_id is None:
return super().persistent_id(obj)
return self._persistent_id(obj)
| _PyTorchLegacyPickler |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/cursor.py | {
"start": 53882,
"end": 86183
} | class ____(Result[Unpack[_Ts]]):
"""A Result that is representing state from a DBAPI cursor.
.. versionchanged:: 1.4 The :class:`.CursorResult``
class replaces the previous :class:`.ResultProxy` interface.
This classes are based on the :class:`.Result` calling API
which provides an update... | CursorResult |
python | PrefectHQ__prefect | src/prefect/filesystems.py | {
"start": 1421,
"end": 1922
} | class ____(Block, abc.ABC):
_block_schema_capabilities = ["get-directory", "put-directory"]
@abc.abstractmethod
async def get_directory(
self, from_path: Optional[str] = None, local_path: Optional[str] = None
) -> None:
pass
@abc.abstractmethod
async def put_directory(
... | WritableDeploymentStorage |
python | facebook__pyre-check | client/configuration/site_packages.py | {
"start": 1647,
"end": 2152
} | class ____:
name: str
path: Path # NOTE: parent of this path would be the site root
is_partial: bool = False
def to_search_path_element(self) -> search_path.SitePackageElement:
return search_path.SitePackageElement(
site_root=str(self.path.parent), package_name=self.path.name
... | StubPackage |
python | readthedocs__readthedocs.org | readthedocs/profiles/views.py | {
"start": 5614,
"end": 6068
} | class ____(PrivateViewMixin, SuccessMessageMixin, UpdateView):
model = UserProfile
form_class = UserAdvertisingForm
context_object_name = "profile"
template_name = "profiles/private/advertising_profile.html"
success_message = _("Updated your advertising preferences")
def get_object(self):
... | AccountAdvertisingEdit |
python | huggingface__transformers | src/transformers/models/metaclip_2/modeling_metaclip_2.py | {
"start": 11786,
"end": 15311
} | class ____(PreTrainedModel):
config: MetaClip2Config
base_model_prefix = "metaclip_2"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
_supports_sdpa = True
_supports_flash_attn = True
_supports_flex_attn = True
_supports_attention_backend = True
_can_recor... | MetaClip2PreTrainedModel |
python | protocolbuffers__protobuf | python/google/protobuf/internal/python_message.py | {
"start": 55685,
"end": 57289
} | class ____(object):
"""MessageListener implementation that a parent message registers with its
child message.
In order to support semantics like:
foo.bar.baz.moo = 23
assert foo.HasField('bar')
...child objects must have back references to their parents.
This helper class is at the heart of this s... | _Listener |
python | ansible__ansible | lib/ansible/module_utils/facts/network/base.py | {
"start": 1401,
"end": 2387
} | class ____(BaseFactCollector):
# MAYBE: we could try to build this based on the arch specific implementation of Network() or its kin
name = 'network'
_fact_class = Network
_fact_ids = set(['interfaces',
'default_ipv4',
'default_ipv6',
'all_i... | NetworkCollector |
python | fluentpython__example-code-2e | 21-async/mojifinder/web_mojifinder.py | {
"start": 372,
"end": 916
} | class ____(BaseModel): # <3>
char: str
name: str
def init(app): # <4>
app.state.index = InvertedIndex()
app.state.form = (STATIC_PATH / 'form.html').read_text()
init(app) # <5>
@app.get('/search', response_model=list[CharName]) # <6>
async def search(q: str): # <7>
chars = sorted(app.state.i... | CharName |
python | jazzband__django-model-utils | tests/test_fields/test_urlsafe_token_field.py | {
"start": 195,
"end": 2285
} | class ____(TestCase):
def test_editable_default(self) -> None:
field = UrlsafeTokenField()
self.assertFalse(field.editable)
def test_editable(self) -> None:
field = UrlsafeTokenField(editable=True)
self.assertTrue(field.editable)
def test_max_length_default(self) -> None:
... | UrlsaftTokenFieldTests |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/vendor/pretty.py | {
"start": 22146,
"end": 35133
} | class ____:
def __init__(self, *groups: Group) -> None:
self.queue: list[list[Group]] = []
for group in groups:
self.enq(group)
def enq(self, group: Group) -> None:
depth = group.depth
while depth > len(self.queue) - 1:
self.queue.append([])
self.... | GroupQueue |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/sql_datasource.py | {
"start": 11263,
"end": 12028
} | class ____(_PartitionerOneColumnOneParam):
mod: int
column_name: str
method_name: Literal["partition_on_mod_integer"] = "partition_on_mod_integer"
@property
@override
def param_names(self) -> List[str]:
return ["remainder"]
@override
def partitioner_method_kwargs(self) -> Dict[... | SqlPartitionerModInteger |
python | getsentry__sentry | tests/sentry/integrations/jira/models/test_jira_schema.py | {
"start": 203,
"end": 629
} | class ____(TestCase):
def test_schema_parsing(self) -> None:
create_meta = StubJiraApiClient().get_create_meta_for_project("proj-1")
issue_configs = list(JiraIssueTypeMetadata.from_jira_meta_config(create_meta).values())
assert len(issue_configs) == 1
assert issue_configs[0].name == ... | TestJiraSchema |
python | django__django | tests/test_utils/tests.py | {
"start": 43011,
"end": 45320
} | class ____(SimpleTestCase):
def test_simple_equal(self):
json1 = '{"attr1": "foo", "attr2":"baz"}'
json2 = '{"attr1": "foo", "attr2":"baz"}'
self.assertJSONEqual(json1, json2)
def test_simple_equal_unordered(self):
json1 = '{"attr1": "foo", "attr2":"baz"}'
json2 = '{"att... | JSONEqualTests |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 858098,
"end": 858313
} | class ____(BinExtent):
"""ParameterExtent schema wrapper."""
_schema = {"$ref": "#/definitions/ParameterExtent"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| ParameterExtent |
python | huggingface__transformers | src/transformers/models/bridgetower/modeling_bridgetower.py | {
"start": 65848,
"end": 66213
} | class ____(nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.fc = nn.Linear(hidden_size, 2)
def forward(self, x):
itm_score = self.fc(x)
return itm_score
@auto_docstring(
custom_intro="""
BridgeTower Model with a language modeling head on top as done... | BridgeTowerITMHead |
python | geekcomputers__Python | Add_two_Linked_List.py | {
"start": 94,
"end": 1810
} | class ____:
def __init__(self):
self.head = None
def insert_at_beginning(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
new_node.next = self.head
self.head = new_node
def add_two_no(self, first, s... | LinkedList |
python | explosion__spaCy | spacy/lang/lt/__init__.py | {
"start": 452,
"end": 557
} | class ____(Language):
lang = "lt"
Defaults = LithuanianDefaults
__all__ = ["Lithuanian"]
| Lithuanian |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox13.py | {
"start": 315,
"end": 1062
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox13.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | Textualize__textual | src/textual/__init__.py | {
"start": 1036,
"end": 1125
} | class ____(Exception):
"""Raised when the logger failed."""
@rich.repr.auto
| LoggerError |
python | astropy__astropy | astropy/modeling/functional_models.py | {
"start": 108293,
"end": 113674
} | class ____(Sersic2D):
r"""
Generalized two dimensional Sersic surface brightness profile that
allows for "boxy" or "disky" (kite-like) isophote shapes.
Parameters
----------
amplitude : float
Surface brightness at ``r_eff``.
r_eff : float
Effective (half-light) radius.
n... | GeneralSersic2D |
python | pypa__hatch | tests/project/test_config.py | {
"start": 111856,
"end": 116310
} | class ____:
def test_not_table(self, isolation):
config = {"scripts": 9000}
project_config = ProjectConfig(isolation, config)
with pytest.raises(TypeError, match="Field `tool.hatch.scripts` must be a table"):
_ = project_config.scripts
def test_name_contains_spaces(self, is... | TestScripts |
python | pytorch__pytorch | test/distributed/test_c10d_common.py | {
"start": 10967,
"end": 11158
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.t0 = Task()
def forward(self, x, rank):
return self.t0(x + rank)
| ModuleForDdpCommHook |
python | instagram__MonkeyType | monkeytype/typing.py | {
"start": 12642,
"end": 13391
} | class ____(TypeRewriter):
"""Remove redundant, empty containers from union types.
Empty containers are typed as C[Any] by MonkeyType. They should be removed
if there is a single concrete, non-null type in the Union. For example,
Union[Set[Any], Set[int]] -> Set[int]
Union[] handles the case w... | RemoveEmptyContainers |
python | huggingface__transformers | tests/models/video_llama_3/test_video_processing_video_llama_3.py | {
"start": 4936,
"end": 16909
} | class ____(VideoProcessingTestMixin, unittest.TestCase):
fast_video_processing_class = VideoLlama3VideoProcessor if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.video_processor_tester = VideoLlama3VideoProcessingTester(self)
@property
def video_processor_d... | VideoLlama3VideoProcessingTest |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-gemini-live/tests/test_audio_interface.py | {
"start": 294,
"end": 1036
} | class ____(AsyncSession):
@override
def __init__(self):
pass
@pytest.mark.asyncio
async def test_audio_interface():
interface = GeminiLiveVoiceAgentInterface()
assert isinstance(interface, BaseVoiceAgentInterface)
assert interface.audio_in_queue is None
assert interface.out_queue is No... | MockSession |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 125016,
"end": 126768
} | class ____(threading.Thread):
''' Interrupt main-thread as soon as a changed module file is detected,
the lockfile gets deleted or gets to old. '''
def __init__(self, lockfile, interval):
threading.Thread.__init__(self)
self.lockfile, self.interval = lockfile, interval
#: Is one... | FileCheckerThread |
python | PrefectHQ__prefect | src/prefect/task_engine.py | {
"start": 3094,
"end": 3202
} | class ____(TimeoutError):
"""Raised when a task run exceeds its timeout."""
@dataclass
| TaskRunTimeoutError |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 402800,
"end": 405950
} | class ____(Request):
"""
Signal a task has stopped
:param force: If not true, call fails if the task status is not 'stopped'
:type force: bool
:param task: Task ID
:type task: str
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: Extra in... | StoppedRequest |
python | django__django | tests/admin_widgets/tests.py | {
"start": 1249,
"end": 1671
} | class ____:
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email=None
)
cls.u2 = User.objects.create_user(username="testser", password="secret")
Car.objects.create(owner=cls.superuser, make="Vol... | TestDataMixin |
python | kamyu104__LeetCode-Solutions | Python/longest-palindromic-subsequence-after-at-most-k-operations.py | {
"start": 46,
"end": 876
} | class ____(object):
def longestPalindromicSubsequence(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
dp = [[[1 if i == j else 0 for _ in xrange(k+1)] for j in xrange(len(s))] for i in xrange(len(s))]
for i in reversed(xrange(len(s)-1)):
... | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-aws/prefect_aws/settings.py | {
"start": 172,
"end": 665
} | class ____(PrefectBaseSettings):
model_config = build_settings_config(
("integrations", "aws", "ecs", "observer", "sqs")
)
queue_name: str = Field(
default="prefect-ecs-tasks-events",
description="The name of the SQS queue to watch for Prefect-submitted ECS tasks.",
)
queue... | EcsObserverSqsSettings |
python | allegroai__clearml | clearml/utilities/gpu/pynvml.py | {
"start": 44793,
"end": 44994
} | class ____(Union):
_fields_ = [
('dVal', c_double),
('uiVal', c_uint),
('ulVal', c_ulong),
('ullVal', c_ulonglong),
('sllVal', c_longlong),
]
| c_nvmlValue_t |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/types.py | {
"start": 1386,
"end": 2229
} | class ____(
_NumericCommonType, sqltypes.Float[Union[decimal.Decimal, float]]
):
def __init__(
self,
precision: Optional[int] = None,
scale: Optional[int] = None,
asdecimal: bool = True,
**kw: Any,
):
if isinstance(self, (REAL, DOUBLE)) and (
(pre... | _FloatType |
python | readthedocs__readthedocs.org | readthedocs/core/mixins.py | {
"start": 724,
"end": 915
} | class ____:
# DRF has BasicAuthentication and SessionAuthentication as default classes.
# We don't support neither in the community site.
authentication_classes = []
| ProxiedAPIMixin |
python | tensorflow__tensorflow | tensorflow/python/autograph/tests/loop_basic_test.py | {
"start": 2929,
"end": 10525
} | class ____(reference_test_base.TestCase, parameterized.TestCase):
@parameterized.parameters(*itertools.product(
(
0,
1,
2,
),
(
int,
_int_tensor,
),
))
def test_while_no_vars(self, n, type_):
n = type_(n)
self.assertFunctionMatches... | ReferenceTest |
python | walkccc__LeetCode | solutions/1726. Tuple with Same Product/1726.py | {
"start": 0,
"end": 415
} | class ____:
def tupleSameProduct(self, nums: list[int]) -> int:
# nums of ways to arrange (a, b) = 2
# nums of ways to arrange (c, d) = 2
# nums of ways to arrange (a, b), (c, d) = 2^3 = 8
ans = 0
count = collections.Counter()
for i in range(len(nums)):
for j in range(i):
prod =... | Solution |
python | kamyu104__LeetCode-Solutions | Python/sentence-similarity-ii.py | {
"start": 510,
"end": 1299
} | class ____(object):
def areSentencesSimilarTwo(self, words1, words2, pairs):
"""
:type words1: List[str]
:type words2: List[str]
:type pairs: List[List[str]]
:rtype: bool
"""
if len(words1) != len(words2): return False
lookup = {}
union_find =... | Solution |
python | Textualize__textual | src/textual/css/scalar.py | {
"start": 4206,
"end": 8206
} | class ____(NamedTuple):
"""A numeric value and a unit."""
value: float
unit: Unit
percent_unit: Unit
def __str__(self) -> str:
value, unit, _ = self
if unit == Unit.AUTO:
return "auto"
return f"{int(value) if value.is_integer() else value}{self.symbol}"
@pr... | Scalar |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/annotate_max_batch_sizes_test.py | {
"start": 3123,
"end": 4097
} | class ____(MaxBatchSizesTestBase):
def GraphFn(self, inp):
"""Builds a tf.Graph for the test."""
tensor = inp * 2.0
tensor = array_ops.reshape(tensor, [-1] + self.tensor_shapes[1][1:])
with ops.get_default_graph()._attr_scope({
'_tftrt_op_max_batch_size':
attr_value_pb2.AttrValue(... | AnnotateMaxBatchSizesTest |
python | scipy__scipy | scipy/linalg/tests/test_fblas.py | {
"start": 16634,
"end": 18126
} | class ____(BaseGer):
def get_data(self,x_stride=1,y_stride=1):
rng = np.random.default_rng(1234)
alpha = array(1+1j, dtype = self.dtype)
a = rng.normal(0.,1.,(3,3)).astype(self.dtype)
a = a + rng.normal(0.,1.,(3,3)) * array(1j, dtype = self.dtype)
x = rng.normal(0.,1.,shape(a... | BaseGerComplex |
python | PyCQA__pylint | tests/functional/u/unpacking/unpacking_non_sequence.py | {
"start": 3768,
"end": 3882
} | class ____(NamedTuple):
x: float
y: float
def sum(self):
x, y = self
return x + y
| MyClass |
python | realpython__materials | python-sqlite-sqlalchemy/project/examples/example_3/app/artists/routes.py | {
"start": 622,
"end": 1277
} | class ____(FlaskForm):
name = StringField(
label="Artist's Name", validators=[InputRequired(), does_artist_exist]
)
@artists_bp.route("/")
@artists_bp.route("/artists", methods=["GET", "POST"])
def artists():
form = CreateArtistForm()
# Is the form valid?
if form.validate_on_submit():
... | CreateArtistForm |
python | keras-team__keras | keras/src/optimizers/muon.py | {
"start": 169,
"end": 10809
} | class ____(optimizer.Optimizer):
"""Optimizer that implements the Muon algorithm.
Note that this optimizer should not be used in the following layers:
1. Embedding layer
2. Final output fully connected layer
3. Any {0,1}-D variables
These should all be optimized using AdamW.
The Muon opt... | Muon |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.