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 | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 14163,
"end": 14837
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to update a flow run."""
name: Optional[str] = Field(None)
flow_version: Optional[str] = Field(None)
parameters: Dict[str, Any] = Field(default_factory=dict)
empirical_policy: schemas.core.FlowRunPolicy = Field(
default_facto... | FlowRunUpdate |
python | encode__django-rest-framework | tests/test_viewsets.py | {
"start": 530,
"end": 658
} | class ____(GenericViewSet):
def list(self, request, *args, **kwargs):
return Response({'ACTION': 'LIST'})
| BasicViewSet |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/kubernetes_helper_functions.py | {
"start": 2523,
"end": 7185
} | class ____(tenacity.wait.wait_base):
"""Wait strategy that honors Retry-After header on 429, else falls back to exponential backoff."""
def __call__(self, retry_state):
exc = retry_state.outcome.exception() if retry_state.outcome else None
if isinstance(exc, (SyncApiException, AsyncApiException... | WaitRetryAfterOrExponential |
python | yaml__pyyaml | lib/yaml/dumper.py | {
"start": 1950,
"end": 2837
} | class ____(Emitter, Serializer, Representer, Resolver):
def __init__(self, stream,
default_style=None, default_flow_style=False,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding=None, explicit_start=None, explicit_end=None,
... | Dumper |
python | spack__spack | lib/spack/spack/util/compression.py | {
"start": 17864,
"end": 18046
} | class ____(FileTypeInterface):
OFFSET = 257
_MAGIC_NUMBER_GNU = b"ustar \0"
_MAGIC_NUMBER_POSIX = b"ustar\x0000"
extension = "tar"
name = "tar archive"
| TarFileType |
python | pandas-dev__pandas | pandas/tests/indexing/test_loc.py | {
"start": 109712,
"end": 122354
} | class ____:
@pytest.mark.parametrize("val,expected", [(2**63 - 1, 3), (2**63, 4)])
def test_loc_uint64(self, val, expected):
# see GH#19399
ser = Series({2**63 - 1: 3, 2**63: 4})
assert ser.loc[val] == expected
def test_loc_getitem(self, string_series, datetime_series):
inds... | TestLocSeries |
python | plotly__plotly.py | plotly/graph_objs/layout/map/_center.py | {
"start": 235,
"end": 2800
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.map"
_path_str = "layout.map.center"
_valid_props = {"lat", "lon"}
@property
def lat(self):
"""
Sets the latitude of the center of the map (in degrees North).
The 'lat' property is a number and may be specifie... | Center |
python | pypa__pipenv | pipenv/patched/pip/_internal/resolution/resolvelib/reporter.py | {
"start": 260,
"end": 2201
} | class ____(BaseReporter[Requirement, Candidate, str]):
def __init__(self) -> None:
self.reject_count_by_package: DefaultDict[str, int] = defaultdict(int)
self._messages_at_reject_count = {
1: (
"pip is looking at multiple versions of {package_name} to "
"... | PipReporter |
python | apache__airflow | dev/breeze/src/airflow_breeze/commands/release_management_commands.py | {
"start": 10076,
"end": 106240
} | class ____(NamedTuple):
filepath: Path
package: str
version: Version
dist_type: Literal["sdist", "wheel"]
@classmethod
def from_sdist(cls, filepath: Path) -> DistributionPackageInfo:
from packaging.utils import parse_sdist_filename
package, version = parse_sdist_filename(filepa... | DistributionPackageInfo |
python | apache__airflow | providers/databricks/tests/unit/databricks/hooks/test_databricks.py | {
"start": 53276,
"end": 55667
} | class ____(TestDatabricksHookToken):
"""
Tests that `schema` and/or `port` get reflected in the requested API URLs.
"""
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id=DEFA... | TestDatabricksHookConnSettings |
python | celery__celery | t/unit/worker/test_bootsteps.py | {
"start": 85,
"end": 1329
} | class ____:
def test_get_prefix(self):
f = bootsteps.StepFormatter()
s = Mock()
s.last = True
assert f._get_prefix(s) == f.blueprint_prefix
s2 = Mock()
s2.last = False
s2.conditional = True
assert f._get_prefix(s2) == f.conditional_prefix
s3... | test_StepFormatter |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/notifications/ses.py | {
"start": 1173,
"end": 5109
} | class ____(BaseNotifier):
"""
Amazon Simple Email Service (SES) Notifier.
:param mail_from: Email address to set as email's from
:param to: List of email addresses to set as email's to
:param subject: Email's subject
:param html_content: Content of email in HTML format
:param files: List of... | SesNotifier |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/exceptions.py | {
"start": 1334,
"end": 1747
} | class ____(Exception):
"""Raise when ECS cannot handle the request."""
def __init__(self, failures: list, message: str):
self.failures = failures
self.message = message
super().__init__(message)
def __reduce__(self):
"""Return EcsOperator state and a tuple of failures list ... | EcsOperatorError |
python | wandb__wandb | wandb/errors/links.py | {
"start": 440,
"end": 2520
} | class ____:
"""A collection of URLs that can be associated with a name."""
def __init__(self) -> None:
self.urls: dict[str, WBURL] = {
"wandb-launch": WBURL(
"https://wandb.me/launch",
"Link to the W&B launch marketing page",
),
"wandb... | Registry |
python | davidhalter__jedi | jedi/inference/context.py | {
"start": 11809,
"end": 12227
} | class ____(TreeContextMixin, ValueContext):
def get_filters(self, until_position=None, origin_scope=None):
return self._value.get_filters()
def get_value(self):
return self._value
@property
def string_names(self):
return self._value.string_names
def py__file__(self) -> Opt... | NamespaceContext |
python | pytorch__pytorch | test/inductor/test_kernel_optimization.py | {
"start": 892,
"end": 3515
} | class ____(TestCase):
def compare_dict_tensors(self, ref_dict, res_dict, rtol=1e-3, atol=1e-3):
if len(set(ref_dict.keys())) != len(set(res_dict.keys())):
return False
for key1 in ref_dict:
key2 = "_orig_mod." + key1
assert key2 in res_dict, f"{key1} does not exis... | TestKernelOptimization |
python | getsentry__sentry | tests/sentry/uptime/subscriptions/test_subscriptions.py | {
"start": 35709,
"end": 39640
} | class ____(UptimeTestCase):
@mock.patch("sentry.quotas.backend.disable_seat")
def test(self, mock_disable_seat: mock.MagicMock) -> None:
detector = create_uptime_detector(
self.project,
self.environment,
url="https://sentry.io",
interval_seconds=3600,
... | DisableUptimeDetectorTest |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 68105,
"end": 78494
} | class ____(Response):
"""
Response of projects.get_all endpoint.
:param projects: Projects list
:type projects: Sequence[ProjectsGetAllResponseSingle]
:param scroll_id: Scroll ID that can be used with the next calls to get_all_ex to retrieve more data
:type scroll_id: str
"""
_service ... | GetAllResponse |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_flip.py | {
"start": 693,
"end": 8057
} | class ____(BaseImagePreprocessingLayer):
"""A preprocessing layer which randomly flips images during training.
This layer will flip the images horizontally and or vertically based on the
`mode` attribute. During inference time, the output will be identical to
input. Call the layer with `training=True` ... | RandomFlip |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/visitors.py | {
"start": 1552,
"end": 4017
} | class ____:
"""Base class for visitable objects.
:class:`.Visitable` is used to implement the SQL compiler dispatch
functions. Other forms of traversal such as for cache key generation
are implemented separately using the :class:`.HasTraverseInternals`
interface.
.. versionchanged:: 2.0 Th... | Visitable |
python | jazzband__django-pipeline | tests/tests/test_conf.py | {
"start": 131,
"end": 1520
} | class ____(TestCase):
def test_3unicode(self):
s = PipelineSettings({"FOO_BINARY": "env actualprogram"})
self.assertEqual(s.FOO_BINARY, ("env", "actualprogram"))
def test_2unicode(self):
s = PipelineSettings({"FOO_BINARY": "env actualprogram"})
self.assertEqual(s.FOO_BINARY, ("e... | TestSettings |
python | PyCQA__pylint | tests/functional/a/arguments.py | {
"start": 2769,
"end": 3101
} | class ____:
@staticmethod
def test(first, second=None, **kwargs):
return first, second, kwargs
def func(self):
self.test(42)
self.test(42, second=34)
self.test(42, 42)
self.test() # [no-value-for-parameter]
self.test(42, 42, 42) # [too-many-function-args]
| TestStaticMethod |
python | getsentry__sentry | tests/sentry/snuba/test_tasks.py | {
"start": 2156,
"end": 4527
} | class ____(TestCase, metaclass=abc.ABCMeta):
__test__ = Abstract(__module__, __qualname__)
status_translations = {
QuerySubscription.Status.CREATING: "create",
QuerySubscription.Status.UPDATING: "update",
QuerySubscription.Status.DELETING: "delete",
}
@pytest.fixture(autouse=Tr... | BaseSnubaTaskTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/looker.py | {
"start": 1367,
"end": 7418
} | class ____(BaseHook):
"""Hook for Looker APIs."""
conn_name_attr = "looker_conn_id"
default_conn_name = "looker_default"
conn_type = "gcp_looker"
hook_name = "Google Looker"
def __init__(
self,
looker_conn_id: str,
**kwargs,
) -> None:
super().__init__(**kwa... | LookerHook |
python | scrapy__scrapy | scrapy/extensions/httpcache.py | {
"start": 949,
"end": 1792
} | class ____:
def __init__(self, settings: BaseSettings):
self.ignore_schemes: list[str] = settings.getlist("HTTPCACHE_IGNORE_SCHEMES")
self.ignore_http_codes: list[int] = [
int(x) for x in settings.getlist("HTTPCACHE_IGNORE_HTTP_CODES")
]
def should_cache_request(self, reques... | DummyPolicy |
python | fastai__fastai | fastai/vision/augment.py | {
"start": 3913,
"end": 7151
} | class ____(RandTransform):
"Randomly flip with probability `p`"
def before_call(self, b, split_idx):
super().before_call(b, split_idx)
self.k = random.randint(0,7)
def encodes(self, x:(Image.Image,*TensorTypes)): return x.dihedral(self.k)
# %% ../../nbs/09_vision.augment.ipynb 27
from torc... | DihedralItem |
python | sympy__sympy | sympy/codegen/approximations.py | {
"start": 474,
"end": 3428
} | class ____(Optimization):
"""
Approximates sum by neglecting small terms.
Explanation
===========
If terms are expressions which can be determined to be monotonic, then
bounds for those expressions are added.
Parameters
==========
bounds : dict
Mapping expressions to leng... | SumApprox |
python | crytic__slither | slither/vyper_parsing/ast/types.py | {
"start": 2178,
"end": 2258
} | class ____(ASTNode):
arg: str
annotation: Optional[ASTNode]
@dataclass
| Arg |
python | django-haystack__django-haystack | test_haystack/solr_tests/test_solr_backend.py | {
"start": 30069,
"end": 32503
} | class ____(TestCase):
fixtures = ["base_data.json"]
def setUp(self):
super().setUp()
# Wipe it clean.
clear_solr_index()
# Stow.
self.old_ui = connections["solr"].get_unified_index()
self.ui = UnifiedIndex()
self.smmi = SolrMockSearchIndex()
sel... | LiveSolrSearchQueryTestCase |
python | neetcode-gh__leetcode | python/0013-roman-to-integer.py | {
"start": 0,
"end": 359
} | class ____:
def romanToInt(self, s: str) -> int:
roman = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
res = 0
for i in range(len(s)):
if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]:
res -= roman[s[i]]
else:
res... | Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/multi_asset_sensor_definition.py | {
"start": 38457,
"end": 51107
} | class ____:
_advanced_record_ids_by_key: dict[AssetKey, set[int]]
_partition_key_by_record_id: dict[int, Optional[str]]
advance_all_cursors_called: bool
def __init__(self):
self._advanced_record_ids_by_key = defaultdict(set)
self._partition_key_by_record_id = {}
self.advance_all... | MultiAssetSensorCursorAdvances |
python | pypa__hatch | tests/backend/builders/test_config.py | {
"start": 26353,
"end": 35015
} | class ____:
def test_default(self, isolation):
builder = MockBuilder(str(isolation))
assert builder.config.sources == builder.config.sources == {}
assert builder.config.get_distribution_path(pjoin("src", "foo", "bar.py")) == pjoin("src", "foo", "bar.py")
def test_global_invalid_type(se... | TestSources |
python | pytorch__pytorch | torch/distributed/elastic/agent/server/api.py | {
"start": 12540,
"end": 14149
} | class ____:
"""Return results of the worker executions.
Run results follow an "all-or-nothing" policy where the run is successful if and
only if ALL local workers managed by this agent complete successfully.
If the result is successful (e.g. ``is_failed() = False``) then the ``return_values``
fiel... | RunResult |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 7550,
"end": 7967
} | class ____(_TestDCTBase):
def test_definition_ortho(self):
# Test orthornomal mode.
dt = np.result_type(np.float32, self.rdt)
for xr in X:
x = np.array(xr, dtype=self.rdt)
y = dct(x, norm='ortho', type=2)
xi = dct(y, norm="ortho", type=3)
asser... | _TestDCTIIIBase |
python | walkccc__LeetCode | solutions/1749. Maximum Absolute Sum of Any Subarray/1749.py | {
"start": 0,
"end": 252
} | class ____:
def maxAbsoluteSum(self, nums):
ans = -math.inf
maxSum = 0
minSum = 0
for num in nums:
maxSum = max(num, maxSum + num)
minSum = min(num, minSum + num)
ans = max(ans, maxSum, -minSum)
return ans
| Solution |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/programmatic_disable_button.py | {
"start": 133,
"end": 900
} | class ____(App):
CSS = """
Screen {
align: center middle;
}
"""
BINDINGS = [("space", "toggle_button", "Toggle Button")]
def compose(self) -> ComposeResult:
with Center():
yield Label("Hover the button then hit space")
with Center():
yield Button... | ExampleApp |
python | astropy__astropy | astropy/cosmology/_src/utils.py | {
"start": 2344,
"end": 3920
} | class ____(Protocol):
shape: tuple[int, ...]
def aszarr(
z: Quantity | NDArray[Any] | ArrayLike | ScalarTypes | HasShape, /
) -> NDArray[Any]:
"""Redshift as an Array duck type.
Allows for any ndarray ducktype by checking for attribute "shape".
"""
# Scalars
if isinstance(z, SCALAR_TYPES)... | HasShape |
python | getsentry__sentry | src/sentry/shared_integrations/response/mapping.py | {
"start": 167,
"end": 452
} | class ____(dict, BaseApiResponse):
def __init__(self, data: Mapping[str, Any], *args: Any, **kwargs: Any) -> None:
dict.__init__(self, data)
BaseApiResponse.__init__(self, *args, **kwargs)
@property
def json(self) -> Any:
return self
| MappingApiResponse |
python | getsentry__sentry | tests/sentry/integrations/vsts/test_provider.py | {
"start": 6445,
"end": 10827
} | class ____(TestCase):
def setUp(self) -> None:
responses.reset()
account_id = "1234567-8910"
self.base_url = "http://sentry2.visualstudio.com/"
self.accounts: list[dict[str, Any]] = [
{
"accountId": "1234567-89",
"NamespaceId": "00000000-00... | TestAccountConfigView |
python | huggingface__transformers | src/transformers/models/phimoe/configuration_phimoe.py | {
"start": 873,
"end": 10474
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`PhimoeModel`]. It is used to instantiate a Phi-moe
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar config... | PhimoeConfig |
python | ray-project__ray | python/ray/data/_internal/execution/autoscaling_requester.py | {
"start": 780,
"end": 5152
} | class ____:
"""Actor to make resource requests to autoscaler for the datasets.
The resource requests are set to timeout after RESOURCE_REQUEST_TIMEOUT seconds.
For those live requests, we keep track of the last request made for each execution,
which overrides all previous requests it made; then sum the... | AutoscalingRequester |
python | xlwings__xlwings | xlwings/main.py | {
"start": 98185,
"end": 99104
} | class ____:
def __init__(self, impl):
"""
Represents a PageSetup object.
.. versionadded:: 0.24.2
"""
self.impl = impl
@property
def api(self):
"""
Returns the native object (``pywin32`` or ``appscript`` obj)
of the engine being used.
... | PageSetup |
python | keras-team__keras | keras/src/optimizers/adagrad_test.py | {
"start": 174,
"end": 3249
} | class ____(testing.TestCase):
def test_config(self):
optimizer = Adagrad(
learning_rate=0.5,
initial_accumulator_value=0.2,
epsilon=1e-5,
)
self.run_class_serialization_test(optimizer)
def test_single_step(self):
optimizer = Adagrad(learning_r... | AdagradTest |
python | falconry__falcon | tests/test_wsgi_servers.py | {
"start": 5031,
"end": 8839
} | class ____:
def test_get(self, server_url, requests):
resp = requests.get(server_url + '/hello', timeout=_REQUEST_TIMEOUT)
assert resp.status_code == 200
assert resp.text == 'Hello, World!\n'
assert resp.headers.get('Content-Type') == 'text/plain; charset=utf-8'
assert resp.h... | TestWSGIServer |
python | Textualize__textual | tests/test_path.py | {
"start": 215,
"end": 281
} | class ____(App[None]):
CSS_PATH = "test.tcss"
| RelativePathStrApp |
python | streamlit__streamlit | lib/streamlit/runtime/caching/storage/cache_storage_protocol.py | {
"start": 2643,
"end": 2765
} | class ____(CacheStorageError):
"""Raised when the key is not found in the cache storage."""
| CacheStorageKeyNotFoundError |
python | pytorch__pytorch | torch/fx/graph.py | {
"start": 8257,
"end": 8742
} | class ____:
def __init__(self, graph: "Graph", direction: Literal["_prev", "_next"] = "_next"):
assert direction in ("_next", "_prev")
self.graph = graph
self.direction = direction
def __len__(self):
return self.graph._len
def __iter__(self):
return _NodeIter(self.g... | _node_list |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 81546,
"end": 82134
} | class ____(sgqlc.types.Enum):
"""The merge options available for pull requests to this repository.
Enumeration Choices:
* `MERGE`: The pull request is added to the base branch in a merge
commit.
* `REBASE`: Commits from the pull request are added onto the base
branch individually without a... | RepoChangeMergeSettingAuditEntryMergeType |
python | django__django | tests/constraints/models.py | {
"start": 4459,
"end": 4848
} | class ____(models.Model):
age = models.IntegerField()
class Meta:
abstract = True
required_db_features = {
"supports_table_check_constraints",
}
constraints = [
models.CheckConstraint(
condition=models.Q(age__gte=18),
name=... | AbstractModel |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 779049,
"end": 786450
} | class ____(MarkPropDefnumber, NumericMarkPropDef):
"""
FieldOrDatumDefWithConditionDatumDefnumber schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the b... | FieldOrDatumDefWithConditionDatumDefnumber |
python | ansible__ansible | test/units/module_utils/facts/test_ansible_collector.py | {
"start": 10644,
"end": 11046
} | class ____(collector.BaseFactCollector):
name = 'requires_something'
def collect(self, module=None, collected_facts=None):
collected_facts = collected_facts or {}
fact_dict = {}
fact_dict['needed_fact'] = collected_facts['needed_fact']
fact_dict['compound_fact'] = "compound-%s" ... | RequiresOtherFactCollector |
python | pytorch__pytorch | benchmarks/dynamo/common.py | {
"start": 55452,
"end": 57815
} | class ____:
def scale(self, loss):
return loss
def get_dynamo_stats():
# TODO: consider deepcopy'ing the entire counters struct and
# adding a helper to do subtraction on it
return collections.Counter(
{
"calls_captured": torch._dynamo.utils.counters["stats"]["calls_capture... | DummyGradScaler |
python | apache__airflow | airflow-core/tests/unit/utils/test_logging_mixin.py | {
"start": 1807,
"end": 3375
} | class ____:
def setup_method(self):
warnings.filterwarnings(action="always")
def test_set_context(self, child_logger, parent_child_handlers):
handler1, handler2 = parent_child_handlers
handler1.set_context = mock.MagicMock()
handler2.set_context = mock.MagicMock()
paren... | TestLoggingMixin |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 249059,
"end": 251382
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[3, 3, 3]", L_y_: "f32[3, 3, 3]"):
l_x_ = L_x_
l_y_ = L_y_
lazy_load_decompositions = torch._functorch.predispatch.lazy_load_decompositions(); lazy_load_decompositions = None
_vmap_increment_nesting = torch._functorch.predis... | GraphModule |
python | realpython__materials | django-todo-list/source_code_final/todo_app/apps.py | {
"start": 36,
"end": 147
} | class ____(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "todo_app"
| TodoAppConfig |
python | pandas-dev__pandas | pandas/tests/indexes/string/test_indexing.py | {
"start": 3668,
"end": 5268
} | class ____:
@pytest.mark.parametrize("null", [None, np.nan, float("nan"), pd.NA])
def test_get_indexer_non_unique_nas(
self, any_string_dtype, null, using_infer_string
):
index = Index(["a", "b", null], dtype=any_string_dtype)
indexer, missing = index.get_indexer_non_unique(["a", nul... | TestGetIndexerNonUnique |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/dataproc.py | {
"start": 6605,
"end": 6829
} | class ____(BaseGoogleLink):
"""Helper class for constructing Dataproc Batches List Link."""
name = "Dataproc Batches List"
key = "dataproc_batches_list"
format_str = DATAPROC_BATCHES_LINK
| DataprocBatchesListLink |
python | doocs__leetcode | solution/1300-1399/1396.Design Underground System/Solution.py | {
"start": 0,
"end": 794
} | class ____:
def __init__(self):
self.ts = {}
self.d = {}
def checkIn(self, id: int, stationName: str, t: int) -> None:
self.ts[id] = (t, stationName)
def checkOut(self, id: int, stationName: str, t: int) -> None:
t0, station = self.ts[id]
x = self.d.get((station, st... | UndergroundSystem |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/widgets/toolbars.py | {
"start": 1478,
"end": 1907
} | class ____(Window):
def __init__(self, text: AnyFormattedText, style: str = "", **kw: Any) -> None:
# Note: The style needs to be applied to the toolbar as a whole, not
# just the `FormattedTextControl`.
super().__init__(
FormattedTextControl(text, **kw),
style=... | FormattedTextToolbar |
python | kamyu104__LeetCode-Solutions | Python/maximum-profit-from-trading-stocks.py | {
"start": 624,
"end": 1123
} | class ____(object):
def maximumProfit(self, present, future, budget):
"""
:type present: List[int]
:type future: List[int]
:type budget: int
:rtype: int
"""
dp = [[0]*(budget+1) for _ in xrange(2)]
for i, (p, f) in enumerate(itertools.izip(present, fut... | Solution2 |
python | numpy__numpy | numpy/_core/tests/test_numeric.py | {
"start": 137991,
"end": 139310
} | class ____:
def test_object(self):
d = [1.] * 100
k = [1.] * 3
assert_array_almost_equal(np.convolve(d, k)[2:-2], np.full(98, 3))
def test_no_overwrite(self):
d = np.ones(100)
k = np.ones(3)
np.convolve(d, k)
assert_array_equal(d, np.ones(100))
as... | TestConvolve |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_points01.py | {
"start": 315,
"end": 1128
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_points01.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with point formatting."""
workbook = ... | TestCompareXLSXFiles |
python | run-llama__llama_index | llama-index-integrations/retrievers/llama-index-retrievers-kendra/llama_index/retrievers/kendra/base.py | {
"start": 361,
"end": 5934
} | class ____(BaseRetriever):
"""
AWS Kendra retriever for LlamaIndex.
See https://aws.amazon.com/kendra/ for more info.
Args:
index_id: Kendra Index ID.
query_config: Configuration for querying Kendra.
profile_name: The name of the profile in the ~/.aws/credentials
or... | AmazonKendraRetriever |
python | sqlalchemy__sqlalchemy | test/perf/compiled_extensions/misc.py | {
"start": 5059,
"end": 6663
} | class ____(Case):
NUMBER = 5_000_000
@staticmethod
def python():
from sqlalchemy.sql import _util_cy
py_util = load_uncompiled_module(_util_cy)
assert not py_util._is_compiled()
return py_util.anon_map
@staticmethod
def cython():
from sqlalchemy.sql import ... | AnonMap |
python | mwaskom__seaborn | seaborn/_core/properties.py | {
"start": 11523,
"end": 11659
} | class ____(IntervalProperty):
"""Offset for edge-aligned text, in point units."""
_default_range = 0, 5
_legend = False
| Offset |
python | tiangolo__fastapi | fastapi/exceptions.py | {
"start": 336,
"end": 1877
} | class ____(StarletteHTTPException):
"""
An HTTP exception you can raise in your own code to show errors to the client.
This is for client errors, invalid authentication, invalid data, etc. Not for server
errors in your code.
Read more about it in the
[FastAPI docs for Handling Errors](https://... | HTTPException |
python | pypa__pip | src/pip/_internal/metadata/importlib/_compat.py | {
"start": 455,
"end": 2804
} | class ____(Protocol):
"""A protocol that various path objects conform.
This exists because importlib.metadata uses both ``pathlib.Path`` and
``zipfile.Path``, and we need a common base for type hints (Union does not
work well since ``zipfile.Path`` is too new for our linter setup).
This does not m... | BasePath |
python | jazzband__django-simple-history | simple_history/models.py | {
"start": 47650,
"end": 47762
} | class ____:
field: str
old: ModelChangeValue
new: ModelChangeValue
@dataclass(frozen=True)
| ModelChange |
python | pytorch__pytorch | torch/fx/passes/splitter_base.py | {
"start": 2323,
"end": 4694
} | class ____:
def __init__(
self,
min_acc_module_size=DEFAULT_MIN_ACC_MODULE_SIZE,
skip_fusion=DEFAULT_SKIP_FUSION,
allow_non_tensor=DEFAULT_ALLOW_NON_TENSOR,
max_acc_splits: int = -1,
):
parser = argparse.ArgumentParser()
parser.add_argument(
"-... | _SplitterSettingBase |
python | pandas-dev__pandas | pandas/tests/series/methods/test_searchsorted.py | {
"start": 190,
"end": 2493
} | class ____:
def test_searchsorted(self):
ser = Series([1, 2, 3])
result = ser.searchsorted(1, side="left")
assert is_scalar(result)
assert result == 0
result = ser.searchsorted(1, side="right")
assert is_scalar(result)
assert result == 1
def test_search... | TestSeriesSearchSorted |
python | openai__gym | gym/wrappers/frame_stack.py | {
"start": 195,
"end": 2946
} | class ____:
"""Ensures common frames are only stored once to optimize memory use.
To further reduce the memory use, it is optionally to turn on lz4 to compress the observations.
Note:
This object should only be converted to numpy array just before forward pass.
"""
__slots__ = ("frame_sha... | LazyFrames |
python | getsentry__sentry | tests/sentry/notifications/api/endpoints/test_notification_actions_index.py | {
"start": 1038,
"end": 1768
} | class ____(TypedDict):
query: _Query
result: set[NotificationAction]
def _mock_register(
data: MutableMapping[str, Any],
) -> Callable[[type[ActionRegistrationT]], type[ActionRegistrationT]]:
trigger_type = ActionTrigger.get_value(data["triggerType"])
service_type = ActionService.get_value(data["s... | _QueryResult |
python | kamyu104__LeetCode-Solutions | Python/sum-of-k-subarrays-with-length-at-least-m.py | {
"start": 50,
"end": 815
} | class ____(object):
def maxSum(self, nums, k, m):
"""
:type nums: List[int]
:type k: int
:type m: int
:rtype: int
"""
prefix = [0]*(len(nums)+1)
for i in xrange(len(nums)):
prefix[i+1] = prefix[i]+nums[i]
dp = [float("-inf")]*(len(n... | Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/vertex_ai.py | {
"start": 5240,
"end": 5497
} | class ____(BaseGoogleLink):
"""Helper class for constructing Vertex AI BatchPredictionJob link."""
name = "Batch Prediction Job"
key = "batch_prediction_job_conf"
format_str = VERTEX_AI_BATCH_PREDICTION_JOB_LINK
| VertexAIBatchPredictionJobLink |
python | coleifer__peewee | tests/models.py | {
"start": 177487,
"end": 181957
} | class ____(ModelTestCase):
requires = [C_Product, C_Archive, C_Part]
def setUp(self):
super(TestDataModifyingCTEIntegration, self).setUp()
for i in range(5):
C_Product.create(name='p%s' % i, price=i)
mp1_c_g = C_Part.create(part='mp1-c-g')
mp1_c = C_Part.create(part=... | TestDataModifyingCTEIntegration |
python | pandas-dev__pandas | pandas/tests/io/json/test_ujson.py | {
"start": 22685,
"end": 26855
} | class ____:
@pytest.mark.parametrize("bool_input", [True, False])
def test_bool(self, bool_input):
b = bool(bool_input)
assert ujson.ujson_loads(ujson.ujson_dumps(b)) == b
def test_bool_array(self):
bool_array = np.array(
[True, False, True, True, False, True, False, Fal... | TestNumpyJSONTests |
python | langchain-ai__langchain | libs/core/langchain_core/messages/base.py | {
"start": 12874,
"end": 16456
} | class ____(BaseMessage):
"""Message chunk, which can be concatenated with other Message chunks."""
def __add__(self, other: Any) -> BaseMessageChunk: # type: ignore[override]
"""Message chunks support concatenation with other message chunks.
This functionality is useful to combine message chu... | BaseMessageChunk |
python | doocs__leetcode | solution/3100-3199/3162.Find the Number of Good Pairs I/Solution2.py | {
"start": 0,
"end": 403
} | class ____:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
cnt1 = Counter(x // k for x in nums1 if x % k == 0)
if not cnt1:
return 0
cnt2 = Counter(nums2)
ans = 0
mx = max(cnt1)
for x, v in cnt2.items():
s = sum(cnt... | Solution |
python | plotly__plotly.py | plotly/graph_objs/isosurface/_stream.py | {
"start": 233,
"end": 3526
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface"
_path_str = "isosurface.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set... | Stream |
python | pytorch__pytorch | torch/distributed/_tools/memory_tracker.py | {
"start": 419,
"end": 1262
} | class ____(TorchDispatchMode):
"""Run in ``TorchDispatchMode`` to get memory stats at operator level."""
def __init__(self, memory_tracker) -> None:
self.memory_tracker = memory_tracker
def __torch_dispatch__(self, func, types, args=..., kwargs=None):
rs = func(*args, **kwargs)
if ... | MemoryProfileDispatchMode |
python | getsentry__sentry | src/sentry/plugins/sentry_interface_types/apps.py | {
"start": 36,
"end": 279
} | class ____(AppConfig):
name = "sentry.plugins.sentry_interface_types"
def ready(self) -> None:
from sentry.plugins.base import register
from .models import InterfaceTypePlugin
register(InterfaceTypePlugin)
| Config |
python | davidhalter__jedi | jedi/inference/compiled/subprocess/__init__.py | {
"start": 4467,
"end": 8243
} | class ____(_InferenceStateProcess):
"""
API to functionality which will run in a subprocess.
This mediates the interaction between an `InferenceState` and the actual
execution of functionality running within a `CompiledSubprocess`. Available
functions are defined in `.functions`, though should be a... | InferenceStateSubprocess |
python | pikepdf__pikepdf | src/pikepdf/_methods.py | {
"start": 5713,
"end": 15752
} | class ____:
def _quick_save(self):
bio = BytesIO()
self.save(bio)
bio.seek(0)
return bio
def _repr_mimebundle_(self, include=None, exclude=None): # pylint: disable=unused-argument
pdf_data = self._quick_save().read()
data = {
'application/pdf': pdf_d... | Extend_Pdf |
python | openai__openai-python | src/openai/types/responses/tool_choice_mcp.py | {
"start": 218,
"end": 481
} | class ____(BaseModel):
server_label: str
"""The label of the MCP server to use."""
type: Literal["mcp"]
"""For MCP tools, the type is always `mcp`."""
name: Optional[str] = None
"""The name of the tool to call on the server."""
| ToolChoiceMcp |
python | django-haystack__django-haystack | test_haystack/solr_tests/test_solr_backend.py | {
"start": 6005,
"end": 6309
} | class ____(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
return MockModel
def prepare_text(self, obj):
return """Don't panic but %s has been iñtërnâtiônàlizéð""" % obj.author
| SolrQuotingMockSearchIndex |
python | getsentry__sentry | src/sentry/releases/endpoints/project_release_file_details.py | {
"start": 1177,
"end": 1794
} | class ____(serializers.Serializer):
name = serializers.CharField(max_length=200, required=True)
def _entry_from_index(release: Release, dist: Distribution | None, url: str) -> ReleaseFile:
index = read_artifact_index(release, dist)
if index is None:
raise ResourceDoesNotExist
try:
retu... | ReleaseFileSerializer |
python | django__django | tests/admin_views/admin.py | {
"start": 22929,
"end": 23181
} | class ____(admin.TabularInline):
model = RelatedPrepopulated
extra = 1
autocomplete_fields = ["fk", "m2m"]
prepopulated_fields = {
"slug1": ["name", "pubdate"],
"slug2": ["status", "name"],
}
| RelatedPrepopulatedInline2 |
python | kamyu104__LeetCode-Solutions | Python/linked-list-cycle-ii.py | {
"start": 29,
"end": 247
} | class ____(object):
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
if self:
return "{}".format(self.val)
else:
return None
| ListNode |
python | Pylons__pyramid | src/pyramid/config/routes.py | {
"start": 525,
"end": 24317
} | class ____:
@action_method
def add_route(
self,
name,
pattern=None,
factory=None,
for_=None,
header=None,
xhr=None,
accept=None,
path_info=None,
request_method=None,
request_param=None,
traverse=None,
custom_... | RoutesConfiguratorMixin |
python | ray-project__ray | python/ray/train/v2/horovod/horovod_trainer.py | {
"start": 368,
"end": 1442
} | class ____(DataParallelTrainer):
"""A Trainer for data parallel Horovod training. HorovodTrainer is deprecated."""
def __init__(
self,
train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]],
*,
train_loop_config: Optional[Dict] = None,
horovod_config: O... | HorovodTrainer |
python | wandb__wandb | wandb/sdk/artifacts/_generated/delete_artifact_sequence.py | {
"start": 300,
"end": 394
} | class ____(GQLResult):
result: Optional[DeleteArtifactSequenceResult]
| DeleteArtifactSequence |
python | facebook__pyre-check | client/language_server/connections.py | {
"start": 5816,
"end": 6466
} | class ____:
"""
An adapter for `AsyncBytesWriter` that encodes everything it writes immediately
from string to bytes. In other words, it tries to expose the same interfaces
as `AsyncBytesWriter` except it operates on strings rather than bytestrings.
"""
bytes_writer: AsyncBytesWriter
encodi... | AsyncTextWriter |
python | pennersr__django-allauth | allauth/socialaccount/providers/twitch/provider.py | {
"start": 789,
"end": 1318
} | class ____(OAuth2Provider):
id = "twitch"
name = "Twitch"
account_class = TwitchAccount
oauth2_adapter_class = TwitchOAuth2Adapter
def extract_uid(self, data):
return str(data["id"])
def extract_common_fields(self, data):
return {
"username": data.get("login"),
... | TwitchProvider |
python | Textualize__textual | docs/examples/app/question02.py | {
"start": 87,
"end": 551
} | class ____(App[str]):
CSS_PATH = "question02.tcss"
def compose(self) -> ComposeResult:
yield Label("Do you love Textual?", id="question")
yield Button("Yes", id="yes", variant="primary")
yield Button("No", id="no", variant="error")
def on_button_pressed(self, event: Button.Pressed)... | QuestionApp |
python | PyCQA__pylint | tests/functional/u/use/use_maxsplit_arg.py | {
"start": 2491,
"end": 3449
} | class ____():
split = '1,2,3'
# Error message should show Bar.split.split(',', maxsplit=1) or Bar.split.rsplit(',', maxsplit=1)
print(Bar.split.split(",")[0]) # [use-maxsplit-arg]
print(Bar.split.split(",")[-1]) # [use-maxsplit-arg]
print(Bar.split.rsplit(",")[0]) # [use-maxsplit-arg]
print(Bar.split.rsplit(","... | Bar |
python | sphinx-doc__sphinx | tests/test_builders/test_build_linkcheck.py | {
"start": 34733,
"end": 41595
} | class ____(InfiniteRedirectOnHeadHandler):
protocol_version = 'HTTP/1.1'
def do_GET(self) -> None:
self.send_response(301, 'Found')
if self.path == '/':
self.send_header('Location', '/local')
elif self.path == '/local':
self.send_header('Location', 'http://exampl... | RemoteDomainRedirectHandler |
python | plotly__plotly.py | plotly/graph_objs/scatterternary/marker/_line.py | {
"start": 233,
"end": 20964
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterternary.marker"
_path_str = "scatterternary.marker.line"
_valid_props = {
"autocolorscale",
"cauto",
"cmax",
"cmid",
"cmin",
"color",
"coloraxis",
"colorscale",
"colorsrc",... | Line |
python | huggingface__transformers | src/transformers/models/imagegpt/modeling_imagegpt.py | {
"start": 1926,
"end": 12178
} | class ____(nn.Module):
def __init__(self, config, is_cross_attention: Optional[bool] = False, layer_idx: Optional[int] = None):
super().__init__()
max_positions = config.max_position_embeddings
self.register_buffer(
"bias",
torch.tril(torch.ones((max_positions, max_p... | ImageGPTAttention |
python | mlflow__mlflow | dev/clint/tests/rules/test_mlflow_class_name.py | {
"start": 260,
"end": 311
} | class ____:
pass
# Bad - using MLFlow
| MLflowClient |
python | sqlalchemy__sqlalchemy | test/engine/test_ddlevents.py | {
"start": 16821,
"end": 17402
} | class ____(DDLEventWCreateHarness, fixtures.TestBase):
__requires__ = ("sequences",)
creates_implicitly_with_table = False
drops_implicitly_with_table = False
supports_standalone_create = True
@testing.fixture
def produce_subject(self):
return normalize_sequence(config, Sequence("my_se... | SequenceDDLEventTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.