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 | pandas-dev__pandas | asv_bench/benchmarks/dtypes.py | {
"start": 481,
"end": 645
} | class ____:
params = _dtypes + [dt.name for dt in _dtypes]
param_names = ["dtype"]
def time_pandas_dtype(self, dtype):
pandas_dtype(dtype)
| Dtypes |
python | dagster-io__dagster | python_modules/libraries/dagster-census/dagster_census/components/census_component.py | {
"start": 989,
"end": 1196
} | class ____(dg.Resolvable, dg.Model):
by_name: Annotated[
Sequence[str],
pydantic.Field(..., description="A list of sync names to include in the collection."),
]
| CensusSyncSelectorByName |
python | django__django | tests/responses/tests.py | {
"start": 1821,
"end": 6455
} | class ____(SimpleTestCase):
def test_status_code(self):
resp = HttpResponse(status=503)
self.assertEqual(resp.status_code, 503)
self.assertEqual(resp.reason_phrase, "Service Unavailable")
def test_change_status_code(self):
resp = HttpResponse()
resp.status_code = 503
... | HttpResponseTests |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 8131,
"end": 8917
} | class ____(BiffRecord):
"""
This record is part of the file protection. It contains the name of the
user that has saved the file. The user name is always stored as an
equal-sized string. All unused characters after the name are filled
with space characters. It is not required to write the m... | WriteAccessRecord |
python | pytorch__pytorch | torch/testing/_comparison.py | {
"start": 12835,
"end": 15922
} | class ____(abc.ABC):
"""ABC for all comparison pairs to be used in conjunction with :func:`assert_equal`.
Each subclass needs to overwrite :meth:`Pair.compare` that performs the actual comparison.
Each pair receives **all** options, so select the ones applicable for the subclass and forward the rest to th... | Pair |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/ops/from_list.py | {
"start": 1027,
"end": 4876
} | class ____(dataset_ops.DatasetSource):
"""A `Dataset` of elements from a list."""
def __init__(self, elements, name=None):
if not elements:
raise ValueError(
"Invalid `elements`. `elements` should not be empty. If you want an"
" empty dataset, use `tf.data.Dataset.range(0)`."
)
... | _ListDataset |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_index.py | {
"start": 381,
"end": 467
} | class ____:
def __index__(self):
return "ruff" # [invalid-index-return]
| Str |
python | numpy__numpy | numpy/distutils/fcompiler/intel.py | {
"start": 575,
"end": 996
} | class ____(FCompiler):
def update_executables(self):
f = dummy_fortran_file()
self.executables['version_cmd'] = ['<F77>', '-FI', '-V', '-c',
f + '.f', '-o', f + '.o']
def runtime_library_dir_option(self, dir):
# TODO: could use -Xlinker here, i... | BaseIntelFCompiler |
python | plotly__plotly.py | plotly/graph_objs/histogram/hoverlabel/_font.py | {
"start": 233,
"end": 17153
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram.hoverlabel"
_path_str = "histogram.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
... | Font |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI036.py | {
"start": 570,
"end": 846
} | class ____:
def __exit__(self, __typ: typing.Type[BaseException] | None, exc: BaseException | None, *args: object) -> None: ...
async def __aexit__(self, typ: typing_extensions.Type[BaseException] | None, __exc: BaseException | None, *args: object) -> None: ...
| GoodThree |
python | ray-project__ray | rllib/policy/policy.py | {
"start": 2024,
"end": 5860
} | class ____:
"""A policy spec used in the "config.multiagent.policies" specification dict.
As values (keys are the policy IDs (str)). E.g.:
config:
multiagent:
policies: {
"pol1": PolicySpec(None, Box, Discrete(2), {"lr": 0.0001}),
"pol2": PolicySpec(confi... | PolicySpec |
python | getsentry__sentry | src/sentry/releases/endpoints/project_release_files.py | {
"start": 2014,
"end": 6907
} | class ____(BaseEndpointMixin):
def get_releasefiles(self, request: Request, release, organization_id):
query = request.GET.getlist("query")
checksums = request.GET.getlist("checksum")
data_sources: list[QuerySet[ReleaseFile] | ArtifactSource] = []
# Exclude files which are also pre... | ReleaseFilesMixin |
python | Textualize__textual | tests/option_list/test_option_list_movement.py | {
"start": 6019,
"end": 7187
} | class ____(App[None]):
def compose(self) -> ComposeResult:
self.highlighted = []
yield OptionList(
Option("0", disabled=True),
Option("1"),
Option("2", disabled=True),
Option("3", disabled=True),
Option("4"),
Option("5"),
... | OptionListDisabledOptionsApp |
python | pandas-dev__pandas | pandas/tests/indexes/test_base.py | {
"start": 54284,
"end": 61114
} | class ____:
@pytest.mark.parametrize(
"data, names, expected",
[
([[1, 2, 4]], None, Index([1, 2, 4])),
([[1, 2, 4]], ["name"], Index([1, 2, 4], name="name")),
([[1, 2, 3]], None, RangeIndex(1, 4)),
([[1, 2, 3]], ["name"], RangeIndex(1, 4, name="name")... | TestIndexUtils |
python | matplotlib__matplotlib | galleries/examples/misc/custom_projection.py | {
"start": 13313,
"end": 16204
} | class ____(GeoAxes):
"""
A custom class for the Aitoff-Hammer projection, an equal-area map
projection.
https://en.wikipedia.org/wiki/Hammer_projection
"""
# The projection must specify a name. This will be used by the
# user to select the projection,
# i.e. ``subplot(projection='custo... | HammerAxes |
python | catalyst-team__catalyst | catalyst/metrics/_segmentation.py | {
"start": 9002,
"end": 13515
} | class ____(RegionBasedMetric):
"""
IoU Metric,
iou score = intersection / union = tp / (tp + fp + fn).
Args:
class_dim: indicates class dimension (K) for ``outputs`` and
``targets`` tensors (default = 1)
weights: class weights
class_names: class names
thresho... | IOUMetric |
python | great-expectations__great_expectations | tests/datasource/fluent/test_snowflake_datasource.py | {
"start": 8452,
"end": 39765
} | class ____:
@pytest.mark.parametrize(
"value",
[
"orgname.account_name",
"orgname-account_name",
"abc12345.us-east-1.aws",
"xy12345.us-gov-west-1.aws",
"xy12345.europe-west4.gcp",
"xy12345.central-us.azure",
],
)
... | TestAccountIdentifier |
python | fsspec__filesystem_spec | fsspec/implementations/asyn_wrapper.py | {
"start": 876,
"end": 3679
} | class ____(AsyncFileSystem):
"""
A wrapper class to convert a synchronous filesystem into an asynchronous one.
This class takes an existing synchronous filesystem implementation and wraps all
its methods to provide an asynchronous interface.
Parameters
----------
sync_fs : AbstractFileSyst... | AsyncFileSystemWrapper |
python | django__django | tests/gis_tests/geoapp/tests.py | {
"start": 25480,
"end": 31691
} | class ____(TestCase):
# TODO: GeoQuerySet is removed, organize these test better.
fixtures = ["initial"]
@skipUnlessDBFeature("supports_extent_aggr")
def test_extent(self):
"""
Testing the `Extent` aggregate.
"""
# Reference query:
# SELECT ST_extent(point)
... | GeoQuerySetTest |
python | h5py__h5py | h5py/_hl/base.py | {
"start": 15415,
"end": 15711
} | class ____:
def __init__(self, func):
self.__doc__ = getattr(func, "__doc__")
self.func = func
def __get__(self, obj, cls):
if obj is None:
return self
value = obj.__dict__[self.func.__name__] = self.func(obj)
return value
| cached_property |
python | pyca__cryptography | src/cryptography/hazmat/primitives/hashes.py | {
"start": 2263,
"end": 2378
} | class ____(HashAlgorithm): # noqa: N801
name = "sha512-224"
digest_size = 28
block_size = 128
| SHA512_224 |
python | walkccc__LeetCode | solutions/3429. Paint House IV/3429.py | {
"start": 0,
"end": 828
} | class ____:
def minCost(self, n: int, costs: list[list[int]]) -> int:
INVALID_COLOR = 3
def getValidColors(prevColor: int) -> list[int]:
return [color for color in range(3) if color != prevColor]
@functools.lru_cache(None)
def minCost(i: int, prevLeftColor: int, prevRightColor: int) -> int:
... | Solution |
python | great-expectations__great_expectations | docs/sphinx_api_docs_source/include_exclude_definition.py | {
"start": 139,
"end": 1205
} | class ____:
"""Include or exclude directive for a class, function or method.
Name and/or relative filepath of class, function or method definition
to exclude or include.
Args:
reason: Reason for include or exclude.
name: name of class, method or function.
filepath: Relative to ... | IncludeExcludeDefinition |
python | OmkarPathak__pygorithm | tests/test_data_structure.py | {
"start": 5133,
"end": 5944
} | class ____(unittest.TestCase):
def test_binary_search_tree(self):
root = tree.BinarySearchTree()
root.insert(10)
root.insert(12)
root.insert(5)
root.insert(4)
root.insert(20)
root.insert(8)
root.insert(7)
root.insert(15)
root.insert(13)... | TestBinarySearchTree |
python | wandb__wandb | wandb/sdk/launch/registry/google_artifact_registry.py | {
"start": 1050,
"end": 8510
} | class ____(AbstractRegistry):
"""Google Artifact Registry helper for interacting with the registry.
This helper should be constructed from either a uri or a repository,
project, and optional image-name. If constructed from a uri, the uri
must be of the form REGION-docker.pkg.dev/PROJECT/REPOSITORY/[IMA... | GoogleArtifactRegistry |
python | python-markdown__markdown | markdown/extensions/legacy_attrs.py | {
"start": 1662,
"end": 2497
} | class ____(Treeprocessor):
def run(self, doc: etree.Element) -> None:
"""Find and set values of attributes ({@key=value}). """
for el in doc.iter():
alt = el.get('alt', None)
if alt is not None:
el.set('alt', self.handleAttributes(el, alt))
if el.t... | LegacyAttrs |
python | python-pillow__Pillow | src/PIL/ImageDraw2.py | {
"start": 925,
"end": 1081
} | class ____:
"""Stores a fill color"""
def __init__(self, color: str, opacity: int = 255) -> None:
self.color = ImageColor.getrgb(color)
| Brush |
python | getsentry__sentry | tests/sentry/middleware/test_proxy.py | {
"start": 471,
"end": 1487
} | class ____(TestCase):
middleware = cached_property(SetRemoteAddrFromForwardedFor)
def test_ipv4(self) -> None:
request = HttpRequest()
request.META["HTTP_X_FORWARDED_FOR"] = "8.8.8.8:80,8.8.4.4"
self.middleware.process_request(request)
assert request.META["REMOTE_ADDR"] == "8.8.... | SetRemoteAddrFromForwardedForTestCase |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_gen_ai.py | {
"start": 6890,
"end": 7819
} | class ____:
@mock.patch(GEN_AI_PATH.format("GenAIGenerativeModelHook"))
def test_execute(self, mock_hook):
op = GenAICreateCachedContentOperator(
task_id=TASK_ID,
project_id=GCP_PROJECT,
location=GCP_LOCATION,
model=GEMINI_MODEL,
cached_content... | TestGenAICreateCachedContentOperator |
python | pytorch__pytorch | torch/_inductor/codecache.py | {
"start": 8353,
"end": 12086
} | class ____(CacheBase):
def lookup(
self,
choices: list[ChoiceCaller],
op: str,
inputs: str,
benchmark: Callable[[Any], dict[ChoiceCaller, float]] | None,
hint_override: int | None = None,
) -> dict[ChoiceCaller, float]:
"""
Check to see if we have ... | PersistentCache |
python | PyCQA__pylint | tests/functional/i/iterable_context.py | {
"start": 2880,
"end": 3239
} | class ____:
def __init__(self):
self._lineparser = None
self._init_lineparser()
# error should not be emitted here
for line in self._lineparser:
print(line)
def _init_lineparser(self):
raise NotImplementedError
# class is not named as abstract
# but still is... | AbstractUrlMarkManager |
python | django__django | tests/delete/models.py | {
"start": 6653,
"end": 6732
} | class ____(models.Model):
restrict = models.ForeignKey(R, models.RESTRICT)
| B3 |
python | PrefectHQ__prefect | src/integrations/prefect-aws/tests/observers/test_ecs_observer.py | {
"start": 2445,
"end": 4570
} | class ____:
def test_is_match_with_no_filter_statuses(self):
filter = LastStatusFilter()
assert filter.is_match("RUNNING")
assert filter.is_match("STOPPED")
assert filter.is_match("PENDING")
def test_is_match_with_single_status(self):
filter = LastStatusFilter("RUNNING")... | TestLastStatusFilter |
python | dagster-io__dagster | python_modules/libraries/dagster-azure/dagster_azure_tests/blob_tests/test_compute_log_manager.py | {
"start": 9845,
"end": 17099
} | class ____(TestComputeLogManager):
__test__ = True
@pytest.fixture(name="compute_log_manager")
def compute_log_manager(
self,
blob_client,
storage_account,
container,
credential,
):
with (
mock.patch(
"dagster_azure.blob.comput... | TestAzureComputeLogManager |
python | kamyu104__LeetCode-Solutions | Python/diet-plan-performance.py | {
"start": 48,
"end": 564
} | class ____(object):
def dietPlanPerformance(self, calories, k, lower, upper):
"""
:type calories: List[int]
:type k: int
:type lower: int
:type upper: int
:rtype: int
"""
total = sum(itertools.islice(calories, 0, k))
result = int(total > upper)... | Solution |
python | docker__docker-py | tests/integration/models_nodes_test.py | {
"start": 92,
"end": 1148
} | class ____(unittest.TestCase):
def setUp(self):
helpers.force_leave_swarm(docker.from_env(version=TEST_API_VERSION))
def tearDown(self):
helpers.force_leave_swarm(docker.from_env(version=TEST_API_VERSION))
def test_list_get_update(self):
client = docker.from_env(version=TEST_API_VE... | NodesTest |
python | plotly__plotly.py | plotly/graph_objs/scatterpolargl/_stream.py | {
"start": 233,
"end": 3546
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolargl"
_path_str = "scatterpolargl.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... | Stream |
python | openai__openai-python | src/openai/types/beta/realtime/rate_limits_updated_event.py | {
"start": 670,
"end": 949
} | class ____(BaseModel):
event_id: str
"""The unique ID of the server event."""
rate_limits: List[RateLimit]
"""List of rate limit information."""
type: Literal["rate_limits.updated"]
"""The event type, must be `rate_limits.updated`."""
| RateLimitsUpdatedEvent |
python | getsentry__sentry | src/sentry/snuba/outcomes.py | {
"start": 1791,
"end": 2252
} | class ____(ABC):
@abstractmethod
def get_snuba_columns(self, raw_groupby: Sequence[str] | None = None) -> list[str]:
raise NotImplementedError()
@abstractmethod
def extract_from_row(
self, row: Mapping[str, Any] | None, group: Mapping[str, Any] | None = None
) -> int:
raise ... | Field |
python | wandb__wandb | wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py | {
"start": 13008,
"end": 15604
} | class ____(FileSystemEventHandler):
"""
Matches given regexes with file paths associated with occurring events.
"""
def __init__(self, regexes=[r".*"], ignore_regexes=[],
ignore_directories=False, case_sensitive=False):
super(RegexMatchingEventHandler, self).__init__()
... | RegexMatchingEventHandler |
python | doocs__leetcode | solution/0600-0699/0663.Equal Tree Partition/Solution.py | {
"start": 192,
"end": 598
} | class ____:
def checkEqualTree(self, root: TreeNode) -> bool:
def sum(root):
if root is None:
return 0
l, r = sum(root.left), sum(root.right)
seen.append(l + r + root.val)
return seen[-1]
seen = []
s = sum(root)
if s % ... | Solution |
python | pydata__xarray | xarray/core/indexes.py | {
"start": 22711,
"end": 36641
} | class ____(Index):
"""Wrap a pandas.Index as an xarray compatible index."""
index: pd.Index
dim: Hashable
coord_dtype: Any
__slots__ = ("coord_dtype", "dim", "index")
def __init__(
self,
array: Any,
dim: Hashable,
coord_dtype: Any = None,
*,
fas... | PandasIndex |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-to-change-the-final-value-of-expression.py | {
"start": 1302,
"end": 2414
} | class ____(object):
def minOperationsToFlip(self, expression):
"""
:type expression: str
:rtype: int
"""
stk = [[None]*3]
for c in expression:
if c == '(':
stk.appe... | Solution2 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 9308,
"end": 10055
} | class ____(sgqlc.types.Enum):
"""The possible ecosystems of a dependency graph package.
Enumeration Choices:
* `ACTIONS`: GitHub Actions
* `COMPOSER`: PHP packages hosted at packagist.org
* `GO`: Go modules
* `MAVEN`: Java artifacts hosted at the Maven central repository
* `NPM`: JavaScrip... | DependencyGraphEcosystem |
python | astropy__astropy | astropy/coordinates/builtin_frames/cirs.py | {
"start": 978,
"end": 1550
} | class ____(BaseRADecFrame):
"""
A coordinate or frame in the Celestial Intermediate Reference System (CIRS).
The frame attributes are listed under **Other Parameters**.
"""
obstime = TimeAttribute(
default=DEFAULT_OBSTIME, doc="The reference time (e.g., time of observation"
)
locat... | CIRS |
python | tensorflow__tensorflow | tensorflow/python/training/proximal_adagrad.py | {
"start": 1074,
"end": 5649
} | class ____(optimizer.Optimizer):
# pylint: disable=line-too-long
"""Optimizer that implements the Proximal Adagrad algorithm.
References:
Adaptive Subgradient Methods for Online Learning and Stochastic Optimization:
[Duchi et al., 2011](http://jmlr.org/papers/v12/duchi11a.html)
([pdf](http://www.... | ProximalAdagradOptimizer |
python | django__django | tests/null_fk/models.py | {
"start": 468,
"end": 655
} | class ____(models.Model):
forum = models.ForeignKey(Forum, models.SET_NULL, null=True)
title = models.CharField(max_length=32)
def __str__(self):
return self.title
| Post |
python | lazyprogrammer__machine_learning_examples | rnn_class/srn_language_tf.py | {
"start": 530,
"end": 7826
} | class ____:
def __init__(self, D, M, V, f, session):
self.D = D # dimensionality of word embedding
self.M = M # hidden layer size
self.V = V # vocabulary size
self.f = f
self.session = session
def set_session(self, session):
self.session = session
def build(... | SimpleRNN |
python | matplotlib__matplotlib | lib/matplotlib/offsetbox.py | {
"start": 16418,
"end": 19321
} | class ____(OffsetBox):
"""
A container to add a padding around an `.Artist`.
The `.PaddedBox` contains a `.FancyBboxPatch` that is used to visualize
it when rendering.
.. code-block:: none
+----------------------------+
| |
| ... | PaddedBox |
python | tensorflow__tensorflow | tensorflow/python/ops/image_ops_test.py | {
"start": 160292,
"end": 164916
} | class ____(test_util.TensorFlowTestCase):
def _ResizeImageWithPad(self, x, target_height, target_width,
use_tensor_inputs):
if use_tensor_inputs:
target_height = ops.convert_to_tensor(target_height)
target_width = ops.convert_to_tensor(target_width)
x_tensor = ops.conv... | ResizeImageWithPadV2Test |
python | google__python-fire | fire/docstrings.py | {
"start": 3179,
"end": 25023
} | class ____(enum.Enum):
GOOGLE = 0
NUMPY = 1
RST = 2
SECTION_TITLES = {
Sections.ARGS: ('argument', 'arg', 'parameter', 'param', 'key'),
Sections.RETURNS: ('return',),
Sections.YIELDS: ('yield',),
Sections.RAISES: ('raise', 'except', 'exception', 'throw', 'error', 'warn'),
Sections.TYPE: ('ty... | Formats |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 113843,
"end": 117343
} | class ____(Response):
"""
Response of events.get_task_events endpoint.
:param events: Events list
:type events: Sequence[dict]
:param returned: Number of results returned
:type returned: int
:param total: Total number of results available for this query. In case there
are more than ... | GetTaskEventsResponse |
python | astropy__astropy | astropy/nddata/mixins/ndslicing.py | {
"start": 340,
"end": 4478
} | class ____:
"""Mixin to provide slicing on objects using the `NDData`
interface.
The ``data``, ``mask``, ``uncertainty`` and ``wcs`` will be sliced, if
set and sliceable. The ``unit`` and ``meta`` will be untouched. The return
will be a reference and not a copy, if possible.
Examples
-----... | NDSlicingMixin |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 14261,
"end": 14436
} | class ____(models.Model):
"""A series of works, like a trilogy of books."""
name = models.CharField(max_length=100)
author = models.CharField(max_length=100)
| Series |
python | pypa__warehouse | tests/unit/utils/test_wsgi.py | {
"start": 6173,
"end": 8283
} | class ____:
def test_removes_header(self):
response = pretend.stub()
app = pretend.call_recorder(lambda e, s: response)
environ = {"HTTP_X_VHM_ROOT": "/foo/bar"}
start_response = pretend.stub()
resp = wsgi.VhmRootRemover(app)(environ, start_response)
assert resp is ... | TestVhmRootRemover |
python | google__jax | tests/pallas/tpu_sparsecore_pallas_test.py | {
"start": 57088,
"end": 57168
} | class ____(TCTilingMixin, VectorSubcoreTest):
pass
| VectorSubcoreTestWithTCTiling |
python | tornadoweb__tornado | tornado/test/httpserver_test.py | {
"start": 1847,
"end": 2158
} | class ____(AsyncHTTPTestCase):
Handler = None
def get_app(self):
return Application([("/", self.__class__.Handler)])
def fetch_json(self, *args, **kwargs):
response = self.fetch(*args, **kwargs)
response.rethrow()
return json_decode(response.body)
| HandlerBaseTestCase |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/fftw/package.py | {
"start": 216,
"end": 719
} | class ____(Package):
"""Used to test that a few problematic concretization
cases with the old concretizer have been solved by the
new ones.
"""
homepage = "http://www.example.com"
url = "http://www.example.com/fftw-1.0.tar.gz"
version("2.0", md5="abcdef1234567890abcdef1234567890")
vers... | Fftw |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 10687,
"end": 11013
} | class ____(_GenerativeProvider):
generative: Union[GenerativeSearches, _EnumLikeStr] = Field(
default=GenerativeSearches.DATABRICKS, frozen=True, exclude=True
)
endpoint: str
maxTokens: Optional[int]
temperature: Optional[float]
topK: Optional[int]
topP: Optional[float]
| _GenerativeDatabricks |
python | instagram__MonkeyType | tests/test_typing.py | {
"start": 24855,
"end": 24945
} | class ____:
"""A name conflict that is not generic."""
pass
T = TypeVar("T")
| Tuple |
python | ray-project__ray | python/ray/experimental/raysort/tracing_utils.py | {
"start": 1950,
"end": 3456
} | class ____:
def __init__(
self,
gauges: List[str],
histograms: List[Tuple[str, List[int]]],
):
self.counts = {m: 0 for m in gauges}
self.gauges = {m: Gauge(m) for m in gauges}
self.reset_gauges()
self.histograms = {m: Histogram(m, boundaries=b) for m, b in... | ProgressTracker |
python | kamyu104__LeetCode-Solutions | Python/maximum-total-importance-of-roads.py | {
"start": 1139,
"end": 1492
} | class ____(object):
def maximumImportance(self, n, roads):
"""
:type n: int
:type roads: List[List[int]]
:rtype: int
"""
degree = [0]*n
for a, b in roads:
degree[a] += 1
degree[b] += 1
degree.sort()
return sum(i*x for i,... | Solution2 |
python | kamyu104__LeetCode-Solutions | Python/number-of-people-that-can-be-seen-in-a-grid.py | {
"start": 76,
"end": 1025
} | class ____(object):
def seePeople(self, heights):
"""
:type heights: List[List[int]]
:rtype: List[List[int]]
"""
def count(h, stk):
cnt = 0
while stk and stk[-1] < h:
stk.pop()
cnt += 1
if stk:
... | Solution |
python | django__django | tests/test_runner/runner.py | {
"start": 48,
"end": 862
} | class ____(DiscoverRunner):
def __init__(
self,
verbosity=1,
interactive=True,
failfast=True,
option_a=None,
option_b=None,
option_c=None,
**kwargs,
):
super().__init__(
verbosity=verbosity, interactive=interactive, failfast=fai... | CustomOptionsTestRunner |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 24183,
"end": 24279
} | class ____(DBAPIError):
"""Wraps a DB-API InterfaceError."""
code = "rvf5"
| InterfaceError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/solver14.py | {
"start": 1052,
"end": 1478
} | class ____(Protocol):
def __lt__(self, __other: Any) -> bool: ...
SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan)
def max2(__arg1: SupportsLessThanT, __arg2: SupportsLessThanT) -> SupportsLessThanT: ...
def min2(__arg1: SupportsLessThanT, __arg2: SupportsLessThanT) -> SupportsLessThan... | SupportsLessThan |
python | kamyu104__LeetCode-Solutions | Python/patching-array.py | {
"start": 662,
"end": 1333
} | class ____(object):
def minPatches(self, nums, n):
"""
:type nums: List[int]
:type n: int
:rtype: int
"""
result = reachable = 0
for x in nums:
while not reachable >= x-1:
result += 1
reachable += reachable+1
... | Solution2 |
python | google__pytype | pytype/tests/test_tracebacks2.py | {
"start": 95,
"end": 453
} | class ____(test_base.BaseTest):
"""Tests for tracebacks in error messages."""
def test_build_class(self):
errors = self.CheckWithErrors("""
class Foo:
def f(self, x: Bar): # name-error[e]
pass
""")
self.assertErrorRegexes(errors, {"e": r"Bar.*not defined$"})
if __name__ == "_... | TracebackTest |
python | ray-project__ray | python/ray/serve/tests/unit/test_schema.py | {
"start": 6048,
"end": 13770
} | class ____:
def get_minimal_deployment_schema(self):
# Generate a DeploymentSchema with the fewest possible attributes set
return {"name": "deep"}
def test_valid_deployment_schema(self):
# Ensure a valid DeploymentSchema can be generated
deployment_schema = {
"name... | TestDeploymentSchema |
python | huggingface__transformers | src/transformers/models/qwen2_vl/modeling_qwen2_vl.py | {
"start": 40685,
"end": 58695
} | class ____(Qwen2VLPreTrainedModel):
base_model_prefix = "model"
_checkpoint_conversion_mapping = {"^model": "language_model"}
# Reference: fix gemma3 grad acc #37208
accepts_loss_kwargs = False
def __init__(self, config: Qwen2VLConfig):
super().__init__(config)
self.visual = Qwen2Vi... | Qwen2VLModel |
python | pandas-dev__pandas | pandas/core/arrays/arrow/accessors.py | {
"start": 1438,
"end": 6551
} | class ____(ArrowAccessor):
"""
Accessor object for list data properties of the Series values.
Parameters
----------
data : Series
Series containing Arrow list data.
"""
def __init__(self, data=None) -> None:
super().__init__(
data,
validation_msg="Ca... | ListAccessor |
python | astropy__astropy | astropy/units/tests/test_quantity_non_ufuncs.py | {
"start": 63940,
"end": 64471
} | class ____(InvariantUnitTestSetup):
def test_sort(self):
self.check(np.sort)
def test_sort_axis(self):
self.check(np.sort, axis=0)
@pytest.mark.skipif(not NUMPY_LT_2_0, reason="np.msort was removed in numpy 2.0")
def test_msort(self):
with pytest.warns(DeprecationWarning, match... | TestSortFunctions |
python | django__django | tests/basic/models.py | {
"start": 303,
"end": 427
} | class ____(models.Model):
article = models.OneToOneField(Article, models.CASCADE, related_name="featured")
| FeaturedArticle |
python | skorch-dev__skorch | skorch/history.py | {
"start": 3511,
"end": 9587
} | class ____(list):
"""History contains the information about the training history of
a :class:`.NeuralNet`, facilitating some of the more common tasks
that are occur during training.
When you want to log certain information during training (say, a
particular score or the norm of the gradients), you ... | History |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 83802,
"end": 84135
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = FunctionalConv2d()
def forward(self, x):
x = self.conv(x)
x = F.relu(x)
return x
def get_example_inputs(self) -> tuple[Any, ...]:
return self.conv.get_example_inputs()
| FunctionalConvReluModel |
python | xlwings__xlwings | xlwings/main.py | {
"start": 2594,
"end": 4271
} | class ____:
def __init__(self):
self.active = None
self.engines = []
self.engines_by_name = {}
def add(self, engine):
self.engines.append(engine)
self.engines_by_name[engine.name] = engine
@property
def count(self):
return len(self)
def __call__(sel... | Engines |
python | kamyu104__LeetCode-Solutions | Python/cells-with-odd-values-in-a-matrix.py | {
"start": 509,
"end": 897
} | class ____(object):
def oddCells(self, n, m, indices):
"""
:type n: int
:type m: int
:type indices: List[List[int]]
:rtype: int
"""
fn = lambda x: sum(count&1 for count in collections.Counter(x).itervalues())
row_sum, col_sum = map(fn, itertools.izip(*... | Solution2 |
python | ray-project__ray | doc/source/ray-core/doc_code/direct_transport_gloo.py | {
"start": 81,
"end": 229
} | class ____:
def random_tensor(self):
return torch.randn(1000, 1000)
# __normal_example_end__
# __gloo_example_start__
@ray.remote
| MyActor |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/multiple_models/tutorial001_py310.py | {
"start": 303,
"end": 395
} | class ____(SQLModel):
name: str
secret_name: str
age: int | None = None
| HeroCreate |
python | pytorch__pytorch | test/test_nn.py | {
"start": 352457,
"end": 354094
} | class ____(TestCase):
@set_default_dtype(torch.double)
@given(X=hu.tensor(shapes=((5, 3, 5, 5),), dtype=np.double),
running_mean=hu.tensor(shapes=(6,), dtype=np.double),
running_var=hu.tensor(shapes=(6,), dtype=np.double))
def test_fuse_module_eval_numerics(self, X, running_mean, runni... | TestFusionEval |
python | getsentry__sentry | tests/sentry/digests/test_notifications.py | {
"start": 668,
"end": 1965
} | class ____(TestCase):
notification_uuid = str(uuid.uuid4())
@cached_property
def project(self) -> Project:
return self.create_project(fire_project_created=True)
@cached_property
def rule(self) -> Rule:
return self.event.project.rule_set.all()[0]
@cached_property
def record... | BindRecordsTestCase |
python | numba__numba | numba/cuda/models.py | {
"start": 844,
"end": 1328
} | class ____(models.PrimitiveModel):
def __init__(self, dmm, fe_type):
if fe_type == types.float16:
be_type = ir.IntType(16)
elif fe_type == types.float32:
be_type = ir.FloatType()
elif fe_type == types.float64:
be_type = ir.DoubleType()
else:
... | FloatModel |
python | redis__redis-py | tests/test_pubsub.py | {
"start": 29656,
"end": 33230
} | class ____:
@pytest.mark.onlynoncluster
@skip_if_server_version_lt("2.8.0")
def test_pubsub_channels(self, r):
p = r.pubsub()
p.subscribe("foo", "bar", "baz", "quux")
for i in range(4):
assert wait_for_message(p)["type"] == "subscribe"
expected = [b"bar", b"baz", ... | TestPubSubSubcommands |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/pygments/lexers/python.py | {
"start": 816,
"end": 18271
} | class ____(RegexLexer):
"""
For Python source code (version 3.x).
.. versionchanged:: 2.5
This is now the default ``PythonLexer``. It is still available as the
alias ``Python3Lexer``.
"""
name = 'Python'
url = 'https://www.python.org'
aliases = ['python', 'py', 'sage', 'pyth... | PythonLexer |
python | catalyst-team__catalyst | catalyst/contrib/layers/common.py | {
"start": 488,
"end": 801
} | class ____(nn.Module):
"""@TODO: Docs. Contribution is welcome."""
def __init__(self, lambda_fn):
"""@TODO: Docs. Contribution is welcome."""
super().__init__()
self.lambda_fn = lambda_fn
def forward(self, x):
"""Forward call."""
return self.lambda_fn(x)
| Lambda |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 233519,
"end": 234463
} | class ____(Operation):
def call(self, x1, x2):
return backend.numpy.floor_divide(x1, x2)
def compute_output_spec(self, x1, x2):
x1_shape = getattr(x1, "shape", [])
x2_shape = getattr(x2, "shape", [])
output_shape = broadcast_shapes(x1_shape, x2_shape)
output_dtype = dtyp... | FloorDivide |
python | mlflow__mlflow | mlflow/gateway/config.py | {
"start": 10503,
"end": 10574
} | class ____(ConfigModel):
limits: list[Limit] | None = []
| LimitsConfig |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 62432,
"end": 62918
} | class ____:
xlFilterAllDatesInPeriodDay = 2 # from enum XlFilterAllDatesInPeriod
xlFilterAllDatesInPeriodHour = 3 # from enum XlFilterAllDatesInPeriod
xlFilterAllDatesInPeriodMinute = 4 # from enum XlFilterAllDatesInPeriod
xlFilterAllDatesInPeriodMonth = 1 # from enum XlFilterAllDatesInPeriod
xl... | FilterAllDatesInPeriod |
python | pallets__werkzeug | src/werkzeug/sansio/multipart.py | {
"start": 10371,
"end": 11963
} | class ____:
def __init__(self, boundary: bytes) -> None:
self.boundary = boundary
self.state = State.PREAMBLE
def send_event(self, event: Event) -> bytes:
if isinstance(event, Preamble) and self.state == State.PREAMBLE:
self.state = State.PART
return event.data
... | MultipartEncoder |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/auto_materialize_policy.py | {
"start": 2258,
"end": 14363
} | class ____(
NamedTuple(
"_AutoMaterializePolicy",
[
("rules", frozenset["AutoMaterializeRule"]),
("max_materializations_per_minute", Optional[int]),
("asset_condition", Optional["AutomationCondition"]),
],
)
):
"""An AutoMaterializePolicy specifies... | AutoMaterializePolicy |
python | walkccc__LeetCode | solutions/3231. Minimum Number of Increasing Subsequence to Be Removed/3231.py | {
"start": 0,
"end": 444
} | class ____:
def minOperations(self, nums: list[int]) -> int:
return self._lengthOfLIS(nums[::-1])
def _lengthOfLIS(self, nums: list[int]) -> int:
# tails[i] := the minimum tail of all the increasing subsequences having
# length i + 1
tails = []
for num in nums:
if not tails or num >= tail... | Solution |
python | apache__airflow | airflow-ctl/src/airflowctl/api/operations.py | {
"start": 6593,
"end": 10971
} | class ____(BaseOperations):
"""Assets operations."""
def get(self, asset_id: str) -> AssetResponse | ServerResponseError:
"""Get an asset from the API server."""
try:
self.response = self.client.get(f"assets/{asset_id}")
return AssetResponse.model_validate_json(self.resp... | AssetsOperations |
python | ray-project__ray | rllib/utils/tf_utils.py | {
"start": 28787,
"end": 36914
} | class ____:
"""A class used to set and get weights for Tensorflow networks.
Attributes:
sess (tf.Session): The tensorflow session used to run assignment.
variables (Dict[str, tf.Variable]): Extracted variables from the loss
or additional variables that are passed in.
placeho... | TensorFlowVariables |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/pipeline_job.py | {
"start": 20540,
"end": 23540
} | class ____(GoogleCloudBaseOperator):
"""
Delete a Pipeline job.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param pipeline_job_id: Required. The ID of the Pipeli... | DeletePipelineJobOperator |
python | joblib__joblib | joblib/hashing.py | {
"start": 5761,
"end": 10694
} | class ____(Hasher):
"""Special case the hasher for when numpy is loaded."""
def __init__(self, hash_name="md5", coerce_mmap=False):
"""
Parameters
----------
hash_name: string
The hash algorithm to be used
coerce_mmap: boolean
Make no difference b... | NumpyHasher |
python | python__mypy | mypy/dmypy/client.py | {
"start": 788,
"end": 8774
} | class ____(argparse.RawDescriptionHelpFormatter):
def __init__(self, prog: str, **kwargs: Any) -> None:
super().__init__(prog=prog, max_help_position=30, **kwargs)
parser = argparse.ArgumentParser(
prog="dmypy", description="Client for mypy daemon mode", fromfile_prefix_chars="@"
)
parser.set_defaults... | AugmentedHelpFormatter |
python | RaRe-Technologies__gensim | gensim/topic_coherence/text_analysis.py | {
"start": 21721,
"end": 24317
} | class ____(UsesDictionary):
"""Accumulate context vectors for words using word vector embeddings.
Attributes
----------
model: Word2Vec (:class:`~gensim.models.keyedvectors.KeyedVectors`)
If None, a new Word2Vec model is trained on the given text corpus. Otherwise,
it should be a pre-tr... | WordVectorsAccumulator |
python | huggingface__transformers | src/transformers/models/dac/modeling_dac.py | {
"start": 7752,
"end": 9109
} | class ____(nn.Module):
"""
A residual unit composed of Snake1d and weight-normalized Conv1d layers with dilations.
"""
def __init__(self, dimension: int = 16, dilation: int = 1):
super().__init__()
pad = ((7 - 1) * dilation) // 2
self.snake1 = Snake1d(dimension)
self.co... | DacResidualUnit |
python | jina-ai__jina | tests/integration/concurrent_clients/test_multithread_client.py | {
"start": 178,
"end": 1562
} | class ____(Executor):
@requests
def foo(self, docs, **kwargs):
for doc in docs:
doc.text = 'I am coming from MyExecutor'
def flow_run(flow, stop_event):
with flow:
flow.block(stop_event)
def client_post(doc, port, client):
result = client.post(on='/', inputs=doc)[0]
p... | MyExecutor |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/managed_kafka.py | {
"start": 1451,
"end": 1670
} | class ____(BaseGoogleLink):
"""Helper class for constructing Apache Kafka Cluster link."""
name = "Apache Kafka Cluster"
key = "cluster_conf"
format_str = MANAGED_KAFKA_CLUSTER_LINK
| ApacheKafkaClusterLink |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.